Friday, January 31, 2014

#10 - Java Branching Statements

Hello,

Today we are going to discuss about one of the most important topics in Java - Branching Statements.
As the name suggests, Branching statements are used to transfer the control to a different branch. We have 3 branching statements in java.
  1.        break
  2.        continue
  3.        return

Each branching statement is a Java keyword. A keyword in Java is a reserved word that has a predefined meaning created by our ancestors (Java Developers). We, users, cannot use those reserved words for any other purpose. The keywords has a sole purpose that had been created by our ancestors and we are not supposed to change THAT purpose..:P

In Java, we have 50 keywords. To know more about Java keywords go through this.
So break, continue and return are Java pre-defined keywords. Let us see the purpose of each branching statement.

1. break

As the name itself says, it breaks the control flow. The below example explains you more clearly about the break keyword.

public class LearnBreak {
       public static void main(String[] args){
      
       // create an array with 10 elements
       int [] numberArr = {1,2,3,4,5,6,7,8,9,10};
      
       // using for loop for iterating the array elements
       for(int tempNumb : numberArr){
              // search for the number 5 in the array
              if(tempNumb == 5){
                     // if number 5 is found, come out of the loop
                     System.out.println("Found Number 5. So break the flow..!");
                     break;
                     }
              else{
                     // if number 5 is not found print the number and again search
                     System.out.println("Found Number --> "+tempNumb);
                     }
              }
      
       System.out.println("If you are reading me, then the control came out of for loop");
       }
}

Output :
Found Number --> 1
Found Number --> 2
Found Number --> 3
Found Number --> 4
Found Number 5. So break the flow..!
If you are reading me, then the control came out of for loop
The above program is self-explanatory.  I want to search for a number 5 in an array of elements. Once I find the number 5, then stop searching and execute the statements that are outside of for loop.
The break statement is mostly used in switch conditional statement. To know more about how break and switch statements are related, plz go through the switch conditional statement in # 9 - Java Conditional Statements

2. continue

The continue branching statement helps the control to skip the current iteration of while, do-while or for loop. The below program explains you better than me..:P
public class LearnContinue {
       public static void main(String[] args){
       
       // create an array with 10 elements
       int [] numberArr = {1,2,3,4,5,6,7,8,9,10};

       // using for loop for iterating the array elements
       for(int tempNumb : numberArr){
       
 // if the number is 5, do NOT do anything. Continue with next iteration
       if(tempNumb == 5){
            continue;
        }

       System.out.println("Current Iteration Number --> "+tempNumb);
              }
       }
}

Output:
Current Iteration Number --> 1
Current Iteration Number --> 2
Current Iteration Number --> 3
Current Iteration Number --> 4
Current Iteration Number --> 6
Current Iteration Number --> 7
Current Iteration Number --> 8
Current Iteration Number --> 9
Current Iteration Number --> 10
In the above program, I want to print the numbers 1 to 10 in which I do not want to print number 5. In this case, continue branching statement helps us to skip iteration when the code is in a loop. When the controller reaches the continue statement it will not execute the statements which exists after it. The control will be jumped to the looping statement to perform the next iteration. You can find in the output of above program where "Current Iteration Number --> 5" is missed.
To know more about Java looping statements click # 8 Java Looping Techniques

3. return

Simply this Java keyword is used to return the control from where it came. Using this return keyword, we can return a value or return nothing. Yes, using this keyword we can tell the compiler that the particular method will not return anything or will return something. See the below programs for better understanding.
public class LearnReturn {

       // the below method says that I will return "int" datatype
       int returnInteger(){
    System.out.println("I am controller. Now I am in returnInteger() method..!");
           return 20;
       }

       public static void main(String[] args){
            LearnReturn lr = new LearnReturn();
            System.out.println("I am controller. Now I am in main() method..!");
            int returnedValue = lr.returnInteger();
            System.out.println("I am controller. Now I am back to main() method with the returnedValue --> "+returnedValue);
       }
}

Output:
I am controller. Now I am in main() method..!
I am controller. Now I am in returnInteger() method..!
I am controller. Now I am back to main() method with the returnedValue --> 20
See the below program where the return keyword is used which returns nothing.
public class LearnReturn {
       
 /* to tell the compiler that the method will NOT return anything, we need to use 
         * void keyword in the method signature as shown below
         */

       void returnNothing(){
           System.out.println("I am controller. Now I am in returnNothing() method..!");

           // if the method is declared as void, the return statement is optional
           return;
    //no statements can be added after the return statement
       }

       public static void main(String[] args){
       LearnReturn lr = new LearnReturn();
       System.out.println("I am controller. Now I am in main() method..!");
       lr.returnNothing();
       System.out.println("I am controller. Now I am back to main() method returning nothing.");
       }
}

Output:
I am controller. Now I am in main() method..!
I am controller. Now I am in returnNothing() method..!
I am controller. Now I am back to main() method returning nothing.
Here you need to understand the below points regarding return keyword.
  1. If a method doesn’t return any value, then you need to add void keyword in the method signature.
  2. No statements can be added after the return keyword because the control will never reach the statements after the return statement. Hence you get Compiler error if you try to place the statements after return.
  3. If the method is declared as void, then the return; keyword in that method is optional. 

Hit Points:
  1. break statement is mostly used in looping and switch conditional statements. The control exits from the current existence flow when the break statement is executed.
  2. continue statement is mostly used in looping techniques. It helps the control to skip the loop depending on the condition we specify.
  3. return statement is used to return the control to where the method is invoked.

Thanks for taking the time to stop by! Please leave comments if you have any suggestions or questions :)

0 comments:

Post a Comment