Blog

Control Statements in Java

  • (4.0)
  • | 22024 Ratings

A control statement works as a determiner for deciding the next task of the other statements whether to execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute first between the two.  In Java, the control statements are divided into three categories which are selection statements, iteration statements, and jump statements.  A program can execute from top to bottom but if we use a control statement. We can set order for executing a program based on values and logic.

Decision Making in Java

Decision making statements are statements which decides what to execute and when. They are similar to decision making in real time. Control flow statements control the flow of a program’s execution. Here flow of execution will be based on state of a program. We have 4 decision making statements available in Java.

Simple if Statement

Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code should be executed based on the condition. 

Syntax:

if (condition) { 
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false

Example:

class ifTest
{
    public static void main(String args[])
    {
       int x = 5;
        if (x > 10)
            System.out.println("Inside If");
        System.out.println("After if statement");
    }
} 
Output:

After if statement

if…else Statement

In if…else statement, if condition is true then statements in if block will be executed but if it comes out as false then else block will be executed. 

Syntax: 

if (condition) { 
Statemen 1; //if condition becomes true then this will be executed
}

Example:

class ifelseTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 9; 
        if (x > 10) 
            System.out.println("i is greater than 10"); 
        else
            System.out.println("i is less than 10"); 
        System.out.println("After if else statement"); 
    } 
}

Output:

i is less than 10
After if else statement

Nested if statement

Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside another if…else statement. 

Syntax:

if (condition1) { 
Statemen 1; //executed when condition1 is true
if (condition2) { 
Statement 2; //executed when condition2 is true
}
else {
 Statement 3; //executed when condition2 is false
}
}

Example:

class nestedifTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 25; 
  
        if (x > 10) 
        {
            if (x%2==0)
            System.out.println("i is greater than 10 and even number"); 
            else
            System.out.println("i is greater than 10 and odd number"); 
        }
        else
        {
            System.out.println("i is less than 10");
        }
        System.out.println("After nested if statement"); 
    } 
} 

Output:

i is greater than 10 and odd number 
After nested if statement

if...else if…else statement

if…else if statements will be used when we need to compare the value with more than 2 conditions. They are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last else statement will be executed.

Syntax:

if (condition2) { 
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
 <span style="white-space:pre"> </span>Statement 2; // if condition2 becomes true then this will be executed
}
.
.
else {
 Statement 3; //executed when no matching condition found
}

Example:

class ifelseifTest 
{ 
    public static void main(String args[]) 
    { 
        int x = 2; 
  
        if (x > 10) 
        {
            System.out.println("i is greater than 10"); 
        }   
        else if (x <10)
            System.out.println("i is less than 10"); 
        }
        else
        {
            System.out.println("i is 10");
        }
        System.out.println("After if else if ladder statement"); 
    } 
} 

Output:

i is less than 10 
After if else if ladder statement

Switch statement

Java switch statement compares the value and executes one of the case blocks based on the condition. It is same as if…else if ladder. Below are some points to consider while working with switch statements:

  • case value must be of the same type as expression used in switch statement
  • case value must be a constant or literal. It doesn’t allow variables
  • case values should be unique. If it is duplicate, then program will give compile time error

Let us understand it through one example.

class switchDemo{
 public static void main(String args[]){
   int i=2;
   switch(i){
     case 0:
     System.out.println("i is 0");
     break;
 
     case 1:
     System.out.println("i is 1");
     break;
 
     case 2:
     System.out.println("i is 2");
     break;
 
     case 3:
     System.out.println("i is 3");
     break;
 
     case 4:
     System.out.println("i is 4");
     break;
 
     default:
     System.out.println("i is not in the list");
     break;
 }
}
}

Looping Statements in Java

Looping statements are the statements which executes a block of code repeatedly until some condition meet to the criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.

While

While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a Boolean expression. If int or string is used instead, compile will give the error.

Syntax:

while (condition)
{
  statement1;
}

Example:

class whileLoopTest 
{ 
    public static void main(String args[]) 
    { 
        int j = 1; 
        while (j <= 10) 
        { 
            System.out.println(j); 
            j = j+2; 
        } 
    } 
} 

Output:

1
3
5
7
9

Do…while

Do…while works same as while loop. It has only one difference that in do…while, condition is checked after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of loop will be executed at least once before checking the condition

Syntax:

do{
statement1;
}while(condition);
Example: here 
class dowhileLoopTest 
{ 
    public static void main(String args[]) 
    { 
        int j = 10; 
   
        do 
        { 
            System.out.println(j); 
            j = j+1; 
        } while (j <= 10) 
    } 
} 

Output:

10

For 

It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is easy to debug structure in Java.

Syntax:

for (initialization; condition; increment/decrement)
{
    statement;
}

Example:

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

Output:

1
2
3
4
5

For-Each Loop

For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to increment the value. It returns the elements from the array or collection one by one.

Example:

class foreachDemo{
 public static void main(String args[]){
   int a[] = {10,15,20,25,30};
    for (int i : a) {
        System.out.println(i);
    }
 }

Output:

10
15
20
25
30

Branching Statements in Java

Branching statements jump from one statement to another and transfer the execution flow. There are 3 branching statements in Java.

Break

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the innermost loop.

Example:

class breakTest 
{ 
    public static void main(String args[]) 
    {        
        for (int j = 0; j < 5; j++) 
        { 
            // come out of loop when i is 4. 
            if (j == 4) 
                break;  
            System.out.println(j); 
        } 
        System.out.println("After loop"); 
    } 
} 

Output:

0
1
2
3
4
After loop

Continue

Continue statement works same as break but the difference is it only comes out of loop for that iteration and continue to execute the code for next iterations. So it only bypasses the current iteration.

Example:

class continueTest 
{ 
    public static void main(String args[]) 
    { 
        for (int j = 0; j < 10; j++) 
        { 
            // If the number is odd then bypass and continue with next value
            if (j%2 != 0) 
                continue; 
            // only even numbers will be printed
            System.out.print(j + " "); 
        } 
    } 
}     

Output:

0 2 4 6 8

Return

Return statement is used to transfer the control back to calling method. Compiler will always bypass any sentences after return statement. So, it must be at the end of any method. They can also return a value to the calling method.

Example: Here method getwebURL() returns the current URL to the caller method.

public String getwebURL()
{
    String vURL= null;
    try {
        vURL= driver.getCurrentUrl();
    }
    catch(Exception e)  {
        System.out.println("Exception occured while getting the current url : "+e.getStackTrace());
    }
    return vURL;
}

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close