Java Control Statements

Control statements are very important for any computer programming language, In Java also we have control statements. Which will help to control any part of the application behavior

Control Statements In Java

  • if-else block.
  • Nested if-else block
  • switch block
  • do-while loop
  • while loop
  • for loop
  • for each

Java If else

In the above example, if we see in the if statement we are checking whether 'i' is greater than the value of 'j'. As we know 'i' and j variables are initialized to 10 and 5 respectively.

So, i value 10 is always greater than the j value 5 hence the if block is going to be executed and else block will not be executed.

Lets see another example in reverse direction.

Java for loop

Java for loop is a control statement which iterates a piece of block continuously until the condition is met or infinite.

for loop example

In the above example, if we see the loop will be iterated 5 times and subsequently it prints 5 times the above SOP statement.

Java do-while loop

If you want to execute the loop at least once without condition constraint, then we can use the do-while loop.

This do-while loop will be executed once without checking the condition what is there in the while block. After completion of first execution it will be checking the condition of the while loop.

Java do-while example

If you want to execute the loop at least once without condition constraint, then we can use the do-while loop.

Java Switch Block

If you want to evaluate an expression, based on the evaluation results some piece of code needs to be executed then we have a switch block.

switch block evaluates expression based on the expression results, switch case will be executed.

If there is no switch case have the same value as what expression is resulted then default block will be executed.

Please remember switch block will be executed only once.

Java Switch Block Example

In the switch block having break key word is optional. If the break is not there then left over case blocks will be executed, in the above example case 2: block will be executed.

Java while loop

While loop almost similar to the for loop but slight difference is, if you don't know how many iterations should go. In this case while loop is suggested to use, the best example for the while loop is iterating through collections(We can see more about collections in upcoming chapters).

Java while loop example

While loop almost similar to the for loop but slight difference is, if you don't know how many iterations should go. In this case while loop is suggested to use.
<-PREV NEXT->