Fully grasp the use of loop control statements and conditional judgment statements in Java

  • 2020-05-05 11:16:18
  • OfStack

loop controls
may have a situation where we need to execute a block of code several times, often referred to as a loop.
Java has a very flexible three-cycle mechanism. You can use one of three loops:

do while cycle... while loop for loop

As of Java5, the enhanced for loop is described. This is mainly used for arrays.

while cycle
The
while loop is a control structure for the number of specific tasks that can be repeated.

Grammar

The syntax for the while loop is:


while(Boolean_expression)
{
  //Statements
}

At execution time, if the result of the Boolean expression is true, the action in the loop is executed. As long as the result of this expression is true, execution continues.

The key point of the while loop here is that the loop may not run forever. When the expression is tested and the result is false, the body of the loop is skipped and the first statement after the while loop is executed.

Sample


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

This will produce the following results :


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

do... while cycle
do... The while loop is similar to the while loop, except that an do... The while loop is guaranteed to be executed at least once.

Grammar

do... The syntax for the while loop is:


do
{
  //Statements
} while (Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statement in the loop executes the previous Boolean test.

If the Boolean expression is true, the control flow jumps back and the statement in the loop is executed again. This process is repeated until the Boolean expression is false.

Sample


public class Test {

  public static void main(String args[]){
   int x = 10;

   do{
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }while( x < 20 );
  }
}

This results in


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

for loop
The
for loop is a loop control structure that effectively writes loops that need to be executed a certain number of times.

The for loop is good for knowing how many times a task will be repeated.

Grammar

The syntax for the for loop is:


for(initialization; Boolean_expression; update)
{
  //Statements
}

The following is the control flow for an for cycle:

The initialization step is performed first and only once. This step declares and initializes any loop control variables. There's no need to put a declaration here, just a semicolon.

Next, the Boolean expression evaluates. If it is true, the body of the loop is executed. If it is false, the loop body does not execute, and the flow control jumps to the next statement that passes through the for loop.

The control flow then jumps back to the update statement when the for loop executes. This statement allows you to update any loop control variables. This statement can be left blank as long as a semicolon appears after a Boolean expression.

The Boolean expression now evaluates the evaluation again. If it is true, the loop executes and repeats the process (the loop body, then the update step, then the Boolean expression). After that, the Boolean expression is false, and the loop terminates.
Sample


public class Test {

  public static void main(String args[]) {

   for(int x = 10; x < 20; x = x+1) {
     System.out.print("value of x : " + x );
     System.out.print("\n");
   }
  }
}

This results in


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

for loop in Java new feature
up to Java5 introduces the enhanced for loop. This is mainly used for arrays.

Grammar

The syntax for the enhanced for loop is:


for(declaration : expression)
{
  //Statements
}

Declaration: new declaration block variable, which is a variable that is compatible with the elements in the array you are accessing. This variable is available in the for block and its value will be the same as the current array element.

Expression: the result of this calculation needs to complete the loop array. An expression can be an array variable or a method call that returns an array.
Sample


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

0

This will produce the following results :


10,20,30,40,50,
James,Larry,Tom,Lacy,

break keyword
The
keyword break is used to stop the entire loop. The break keyword must be used in any loop or in an switch statement.

The keyword break stops the execution of the innermost loop and begins the execution of the next line of code after the block.

Grammar

The break syntax is a single statement in any loop:

break

Sample


public class Test {

  public static void main(String args[]) {
   int [] numbers = {10, 20, 30, 40, 50};

   for(int x : numbers ) {
     if( x == 30 ) {
     break;
     }
     System.out.print( x );
     System.out.print("\n");
   }
  }
}

This results in


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

3

continue keyword
The
continue keyword can be used in any loop of the control structure. It immediately jumps the loop to the next iteration of the loop.

In the for loop, the continue keyword causes the control flow to jump immediately to the update statement.
In an while loop or do/while loop, the control flow immediately jumps to a Boolean expression.
Grammar

The continue syntax is a single statement in any loop:

continue

Sample


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

4


This results in


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

5


conditional judgment
has two types of conditional judgment statements in Java:

if statement switch statement

if statement:

The if statement consists of a Boolean expression followed by one or more statements.

Grammar

The syntax of the if statement is:


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

6

If the Boolean expression value is true, the block if statement in the code will be executed. If it is not true, the first set of code after the if statement (after braces) is executed.

Sample


public class Test {

  public static void main(String args[]){
   int x = 10;

   if( x < 20 ){
     System.out.print("This is if statement");
   }
  }
}

This results in


This is if statement

if... else statement
Any
statement can be followed by an optional else statement, and when the Boolean expression is false, the statement is executed.

Grammar

if... The syntax for else is :


public class Test {

  public static void main(String args[]) {
   int x = 10;

   while( x < 20 ) {
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
   }
  }
}

9

Sample


public class Test {

  public static void main(String args[]){
   int x = 30;

   if( x < 20 ){
     System.out.print("This is if statement");
   }else{
     System.out.print("This is else statement");
   }
  }
}

This results in


This is else statement

if... else if... else statement
if can be followed by an optional else if... else statement. It is useful to test a single if statement and else if statement under different conditions.

There are a few things to keep in mind when using if, else if, else statements.

An if statement can have 0 or 1 else statement and it must be followed by an else if statement. An if statement can have 0 or more else if statements and they must precede an else statement. Once the else if statement is successful, the remaining else if statement or else statement will not be tested for execution.

Grammar

if... The syntax for else is :


if(Boolean_expression 1){
  //Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
  //Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
  //Executes when the Boolean expression 3 is true
}else {
  //Executes when the none of the above condition is true.
}

Sample


public class Test {

  public static void main(String args[]){
   int x = 30;

   if( x == 10 ){
     System.out.print("Value of X is 10");
   }else if( x == 20 ){
     System.out.print("Value of X is 20");
   }else if( x == 30 ){
     System.out.print("Value of X is 30");
   }else{
     System.out.print("This is else statement");
   }
  }
}

This will produce the following results:


Value of X is 30

nested if... else statement
it is always legal to nest if-else statements, which means you can use an if or else if statement in another if or else if statement.

Grammar

Nested if... The syntax for else is as follows:


if(Boolean_expression 1){
  //Executes when the Boolean expression 1 is true
  if(Boolean_expression 2){
   //Executes when the Boolean expression 2 is true
  }
}

Because we have nested if statements, we can nest else if in a similar way... else.

Sample


public class Test {

  public static void main(String args[]){
   int x = 30;
   int y = 10;

   if( x == 30 ){
     if( y == 10 ){
       System.out.print("X = 30 and Y = 10");
     }
    }
  }
}

This will produce the following results:


X = 30 and Y = 10

switch statement
The
switch statement allows a variable to test a set of values for equality. Each value is called an case, and the variables that are started are checked for each case.

Grammar

The syntax for the enhanced for loop is:


switch(expression){
  case value :
    //Statements
    break; //optional
  case value :
    //Statements
    break; //optional
  //You can have any number of case statements.
  default : //Optional
    //Statements
}

The following rules apply to switch statements:

Variables used in switch statements can only be one byte, short, int, or char. There can be any number of case statements in an switch statement. Each case is followed by the value to be compared and a colon. The value of case must be the same data type as the switching variable, which must be a constant or literal. When the enabled variable is equal to case, the statement after case is executed until break. When an break statement is reached, switch terminates, and the control flow jumps to the next line following the switch statement. Not every case needs to contain one break. If break is not present, the control flow will continue to case until break. The switch statement can have an optional default case, which must appear at the end of switch. When no case is true while performing a task, the default case can be used. break is not required in the default case.

Sample


public class Test {

  public static void main(String args[]){
   //char grade = args[0].charAt(0);
   char grade = 'C';

   switch(grade)
   {
     case 'A' :
      System.out.println("Excellent!"); 
      break;
     case 'B' :
     case 'C' :
      System.out.println("Well done");
      break;
     case 'D' :
      System.out.println("You passed");
     case 'F' :
      System.out.println("Better try again");
      break;
     default :
      System.out.println("Invalid grade");
   }
   System.out.println("Your grade is " + grade);
  }
}

Compile and run the program above using the various command-line arguments. This produces the following result:


$ java Test
Well done
Your grade is a C



Related articles: