Decision Controls

When you write a logic, there will be instances when the execution of the program should take different paths based on certain conditions. In such cases you will need to use a control statement which makes a decision on which path to take. In Java you have two types of controls statements:

  • if, if-else statements
  • switch statements

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements. Syntax:

if (boolean_expression)
{
  //Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement is executed. If not the first statement onwards after the end of the if statement (after the closing curly brace) will be executed. Example:

import java.util.Scanner;
public class Test {

   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Please input a number");

      int x = sc.nextInt();

      if( x % 2 == 0 ){
         System.out.println("You have input an even number");
      }

      System.out.println("Good bye!");
   }
}

Run the above code twice; first time with an even number input from console and second time with an odd number input and study how the program of execution selects statements based on the result of the boolean expression inside the if statement.

The following flowchart depicts the control flow of the program based on the result of the boolean expression

x % 2 == 0

image alt text

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

The syntax of an if...else is:

if (boolean_expression){
  //Executes when the Boolean expression is true
}else{
  //Executes when the Boolean expression is false
}

Example:

import java.util.Scanner;
public class Test {

   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Please input a number");

      int x = sc.nextInt();

      if( x % 2 == 0 ){
         System.out.println("You have input an even number");
      } else {
          System.out.println("You have input an odd number");
      }

      System.out.println("Good bye!");
   }
}

Run the above code and input an even and odd number and study how the if or else block gets executed based on boolean expression evaluation. The same execution can be visualized with the flow chart below.

image alt text

The if...else if...else Statement:

An if - else statement can be followed by an optional else if...else statement. When using if , else if , else statements there are few points to keep in mind. An if can have zero or one else and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax: The syntax of an if...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.
}

Example:

import java.util.Scanner;
public class Test {

   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Please input your score");

      int score = sc.nextInt();

      if(score > 90 ){
          System.out.println("Congratulations! You scored an 'A' grade");
      } else if (score > 80){
          System.out.println("Congratulations! You scored a 'B' grade");
      } else if (score > 70){
          System.out.println("Congratulations! You scored a 'C' grade");
      } else {
          System.out.println("Sorry, you failed.");
      }
   }
}

Run the above program by giving values ranging from 100 to 20 for the score and study the logic flow by understanding which if else block is executed for each value.

Nested if...else Statement:

It is legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

The syntax for a nested if...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 } }

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");
          }
       }
    }
}

The switch Statement:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Although it jumps to the specific case based on the value, after executing a specific case, it will move on to the next case if there is no break keyword used to come out of the case switch block. Syntax:

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


import java.util.Scanner;
public class Test {

   public static void main(String args[]){

      Scanner sc = new Scanner(System.in);
      System.out.println("Please input your score");

      String grade = sc.nextLine().toUpperCase();

      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");
            break;
         case "F" :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}

Run the above program, by inputting your grade for any subject and see what the message would be. Study the code to understand which path the program took for execution.

In the above program what happens if toUpperCase() is not added to sc.nextLine()?

If toUpperCase is not added then we do not get an input If toUpperCase() is not added, then the switch statement will jump to default case as the label for the case statements is in lowercase.

How does the program execution flow when you key in 'b'?

It jumps to case "B" and then flows to case "C" and prints out "Well done" It jumps to case "B" and since there is no other statement, nothing happens The program of execution jumps to case "B" and since there is no break, it also executes case "C" and prints out "Well done" and after that it encounters break which makes it to come out of the switch case block

The following rules apply to a switch statement:

  • The variable used in a switch statement could be a byte, short, int, char, enums or Strings.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon (:).
  • The value for a case must be the same data type as the variable in the switch.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the program of execution jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the program of execution will fall through to subsequent cases until a break is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Loops

Loops are a type of control structure that allows you to repeat a certain number of statements a certain number of times. Here are the loop types in Java.

The while Loop:

The syntax of a while loop is:

while (boolean_expression){
  //Statements
}

During executing, if the boolean_expression result is true, then the statements inside the loop will be executed. This will continue as long as the boolean expression result is true. When the boolean expression is false, the loop statements will be skipped and the first statement after the while loop will be executed.

Example:

public class WhileLoopDemo {

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

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

Check the result.

What happens if you do not add x++; statement in the above code?

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

The syntax of a do...while loop is:

do{
  //Statements
} while (boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the boolean expression is tested. If the boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the boolean expression turns to false.

Example:

public class DoWhileLoopDemo {

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

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

Check the results.

What is the difference in the execution between the while and do-while in the above example?

The for Loop:

for loops is similar to while and do while except the for construct not only takes in conditional expression but also an initialization block and update block.

The syntax of a for loop is:

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

Here is the flow of control in a for loop:

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. If you do not need an initialization block, you can skip it but should put in a semicolon anyways.
  • Next, the boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  • After completing the update statement, the boolean expression is evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then boolean expression). Once the boolean expression is false, the for loop terminates.

Example:

public class ForLoopDemo {

   public static void main(String args[]) {

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

Check the results

Enhanced for loop (a.k.a foreach loop):

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the any array sequentially, till the end, without using the initialization block or the update block.

The syntax of enhanced for loop is:

for(declaration : expression){
  //Statements
}

declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the current array element in the iteration.

expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class EnhancedForLoopDemo {

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

      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

Check the result.

The break keyword in loops:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the loop and start executing the next line of code after the loop block. In case of nested loops, break statement will stop the execution of the innermost loop where the break is present. Outer loops are unaffected.

Syntax: The syntax of a break is a single statement inside any loop:

break; Example:

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");
      }
   }
}

Check the result. What do you notice? Why are numbers 30,40 and 50 missing in the console?

The continue keyword in loops:

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop:

continue; Example:

public class Test {

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

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

Check the results. What do you notice? Why is number 30 missing in the console?

Processing arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. Iterating an array is one of the most commonly occurring code blocks in Java. Here is an example of the for and foreach loops used to print, compute sum and finding the largest element:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.0, 2.5, 4.0, 3.5};

      // Print all the array elements using for
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }

      // Summing all elements using foreach
      double total = 0;
      for (double i: myList) {
         total += i;
      }
      System.out.println("Total is " + total);

      // Finding the largest element using foreach
      double max = myList[0];
      for (double i: myList) {
         if (i > max) max = i;
      }
      System.out.println("Max is " + max);
   }
}

Run the program, examine and verify the result.

Operating System (OS) is nothing but a special type of software program which interacts with the computer hardware directly. All the other programs need to interact with the OS to access the computer hardware including the Java programs

Computer Hardware

This is the physical hardware layer that you can visually see. This consists of memory, motherboard containing CPU, Hard disk etc..

results matching ""

    No results matching ""