Java - tutorial - 06/13 - conditionals

revision:


conditions and if statements

Java has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true.
Use else to specify a block of code to be executed, if the same condition is false.
Use else if to specify a new condition to test, if the first condition is false.
Use switch to specify many alternative blocks of code to be executed

Use the if statement to specify a block of Java code to be executed if a condition is true. "if" is in lowercase letters. Uppercase letters (If or IF) will generate an error.

syntax:

          if (condition) {
            // block of code to be executed if the condition is true
          }
    

example:

      public class Main {
        public static void main(String[] args) {
            if (20 > 18) {
              System.out.println("20 is greater than 18"); // 20 is greater than 18
            }  
        }
      }
      //--------------------------------------------------------------------------
      public class Main {
        public static void main(String[] args) {
          int x = 20;
          int y = 18;
          if (x > y) {
            System.out.println("x is greater than y"); // x is greater than y
          }  
        }
      }
    

Use the else statement to specify a block of code to be executed if the condition is false.

syntax:

      if (condition) {
        // block of code to be executed if the condition is true
      } else {
        // block of code to be executed if the condition is false
      }
    

example:

      public class Main {
        public static void main(String[] args) {
            int time = 20;
            if (time < 18) {
              System.out.println("Good day.");
            } else {
              System.out.println("Good evening.");
            }  
        }
      }
    

Use the else if statement to specify a new condition if the first condition is false.

syntax:

      if (condition1) {
        // block of code to be executed if condition1 is true
      } else if (condition2) {
        // block of code to be executed if the condition1 is false and condition2 is true
      } else {
        // block of code to be executed if the condition1 is false and condition2 is false
      }
    

example:

      public class Main {
        public static void main(String[] args) {
          int time = 22;
          if (time < 10) {
              System.out.println("Good morning.");
          } else if (time < 20) {
              System.out.println("Good day.");
          }  else {
              System.out.println("Good evening.");
          }
        }
      }
    

There is also a short-hand if else, which is known as the ternary operator, because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple "if else statements".

syntax:

      variable = (condition) ? expressionTrue :  expressionFalse;
    

example:

      public class Main {
        public static void main(String[] args) {
          int time = 20;
          String result;
          result = (time < 18) ? "Good day." : "Good evening.";
          System.out.println(result);
        }
      }
    

Use the switch statement to select one of many code blocks to be executed. The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. The break and default keywords are optional.

syntax:

      switch(expression) {
          case x:
            // code block
            break;
          case y:
            // code block
            break;
          default:
            // code block
      }
    

example:

      public class Main {
        public static void main(String[] args) {
          int day = 4;
          switch (day) {
            case 1:
              System.out.println("Monday");
              break;
            case 2:
              System.out.println("Tuesday");
              break;
            case 3:
              System.out.println("Wednesday");
              break;
            case 4:
              System.out.println("Thursday"); // Thursday
              break;
            case 5:
              System.out.println("Friday");
              break;
            case 6:
              System.out.println("Saturday");
              break;
            case 7:
              System.out.println("Sunday");
              break;
          }
        }
      }
    

When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing.

The default keyword specifies some code to run if there is no case match.:

example:

      public class Main {
        public static void main(String[] args) {
          int day = 4;
          switch (day) {
            case 6:
              System.out.println("Today is Saturday");
              break;
            case 7:
              System.out.println("Today is Sunday");
              break;
            default:
              System.out.println("Looking forward to the Weekend"); // Looking forward to the Weekend
          }    
        }
      }
    

while loop

The while loop loops through a block of code as long as a specified condition is true:

syntax:

      while (condition) {
        // code block to be executed
      }
    

example:

      public class Main {
        public static void main(String[] args) {
          int i = 0;
          while (i < 5) {
            System.out.println(i); // 0  1  2  3  4  
            i++;
          }  
        }
      }
    

the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

break and continue can also be used in while loops

example:

      public class Main {
        public static void main(String[] args) {
          int i = 0;
          while (i < 10) {
            System.out.println(i);
            i++;
            if (i == 4) {
              break;
            }
          }  
        }
      }
      //---------------------------------------------------
      public class Main {
        public static void main(String[] args) {
          int i = 0;
          while (i < 10) {
            if (i == 4) {
              i++;
              continue;
            }
            System.out.println(i);
            i++;
          }  
        }
      }
    

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

syntax:

      do {
        // code block to be executed
      }
      while (condition);
    

example:

      public class Main {
        public static void main(String[] args) {
          int i = 0;
          do {
            System.out.println(i); // 0  1  2  3  4 
            i++;
          }
          while (i < 5);  
        }
      }    
    

for loop

When you know exactly how many times you want to loop through a block of code, use thefor loop instead of a while loop.

syntax:

      for (statement 1; statement 2; statement 3) {
        // code block to be executed
      }
     

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

example:

      public class Main {
            public static void main(String[] args) {
              for (int i = 0; i < 5; i++) {
                System.out.println(i);
            }
          }   
        } 
    

Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed.

The "for-each" loop is used exclusively to loop through elements in an array:

syntax:

      for (type variableName : arrayName) {
        // code block to be executed
      }
     

example:

      public class Main {
        public static void main(String[] args) {
          String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
          for (String i : cars) {
            System.out.println(i);
          }    
        }
      }
    

break - continue

The break statement can jump out of a switch statement or to jump out of a loop.

example:

        public class Main {
          public static void main(String[] args) {
            for (int i = 0; i < 10; i++) {
              if (i == 4) {
                break;
              }
              System.out.println(i); // 0  1  2  3  
            }  
          }
        }
      

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

example:

      public class Main {
        public static void main(String[] args) {
          for (int i = 0; i < 10; i++) {
            if (i == 4) {
              continue;
            }
            System.out.println(i); // 0  1  2  3  5  6  7  8  9  
          }  
        }
      }