×

Java Control Statements

Control Statements:

Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or build up the logic required for the program.

In Java, control statements are sub-categorized into three parts. They are:

1. Design making statements
2. Looping Statements
3. Jump statements

Decision-making statements:

With name specification, we can understand the decision-making statements easily. Decision-making statements are the single-step execution statement that is executed when the specific condition is satisfied.

These statements are divided into two types. They are:

  • if and else statements
  • Switch statements

if and else statements:

Generally, “if” and “else” statements come in pairs. An “if" statement can be executed without an else statement, but vice versa is not true.

The purpose of the "if" statement is to check whether the given condition is true or not. If the given condition is true, then the compiler proceeds with the "if" block; otherwise, it executes the "else” block.

else if” is used when there are more than one or two conditions, and else if is executed when the previous “if” condition is wrong.

"else" block is executed at last when all the conditions given in the if and else if statements are wrong.

Syntax for simple if statement:

if (condition )
{
Statement 1; // statements will be executed
Statement 2;
                      .
.
Statement n;
}

Syntax for if and else statement:

if (condition )
{
Statement 1; //statements will be executed if the condition is true
}
else 
{
             Statement 1;
}

Syntax for if and else if statement:

if (condition)
{
Statement 1; //statements will be executed if the condition is true


}
else if (condition 2)
{
             Statement 1; //statements will be executed if the condition is true


}
else 
{
Statement 1;
}

Example: consider the following code

import java.io.*;
import java.util.*;
class IfDemo
{
 public static void main (String args[])
      {
Scanner sc = new Scanner (System.in);
int a = sc.nextInt ();
if (a > 18)
{
      System.out.println (“Person is eligible for voting ”);
}
else if (age < 0)
{
System.out.println (“Age cannot be negative,
                                                                  please enter the correct age”);
}
else
{
System.out.println (“ Person is not eligible for voting”);
}
}
}

You can check the below-attached screenshots for the above code for different test cases.

Output 1:

Java Control Statements

Output 2:

Java Control Statements

Output 3:

Java Control Statements

Nested if Statement

In nested if statements, we generally tend to write if or else if statement inside the previous if block.

Syntax for nested if:

if (condition )
{
if (condition ) // block will be executed if condition is true
{
Statement 1; //statements will be executed if the condition is true
}
else 
{
              Statement 1;
}


}
else 
{
             Statement 1;
}

Example:

import java.io.*;
import java.util.*;
class NestedIfDemo
{
 public static void main (String args[])
      {

      int a = 63;
      int b = 93;


      if( a == 63 ) 
      { // executes if the condition is true 
         if( b == 93 ) 
         {// executes if the condition is true
            System.out.print("a = 63 and b = 93");
         }
      }
   }
}
Java Control Statements

Switch Statement:

Switch statements in Java are comparable to if-else-if statements. According to the variable being changed, a single case from a collection of code blocks called cases in the switch statement is executed. Instead of using if-else-if statements, use the switch statement instead. Additionally, it makes the program easier to read.

NOTE:

  • Case variables can take the form of an enumeration, byte, char, int, or short. Java version 7 now supports the string type as well.
  • Cases cannot be duplicated.
  • When any given case doesn't match the value of the expression, the default statement is carried out. It's not required.
  • When the condition is met, the switch block is terminated by a break statement.
  • If it is not used, the next case is handled.
  • We must be aware that when using switch statements, the case expression will share the same type as the variable. It will, nonetheless, have a constant value.

Syntax for nested if:

switch (expression){  
    case 1:  
     statement1;  
     break;  
     case 2:  
     statement1;  
     break;  


    .  
    .  
    .  
    case N:  
     statementN;  
     break;  
    default:  
     default statement;  
}

Example:

import java.io.*;
import java.util.*;
public class SwitchDemo
{
public static void main(String[] args) {
    Scanner sc  = new Scanner ( System.in);
    System.out.println("enter the value of number");
    int num = sc.nextInt();
    switch(num)
    {
        case 0:
            System.out.println("number is 0");
            break;
        case 1:
            System.out.println("number is 1");
            break;
        default:
            System.out.println("number is "+num);
    }
}
}

Output 1:

Java Control Statements

Output 2:

Java Control Statements

While dealing with case expression, we must notice that case expression will be the same type as the variable. And it will be a constant value.

Looping Statements:

While dealing with different problems, sometimes we require to execute or run a specific block repeatedly. In this case, we use looping statements.

Lopping statements are further divided into two types. They are

  • Entry control loops
  • Exit control loops

Entry control loops:

The test condition is checked first in an entry-controlled loop, then the body of the loop is executed. The loop body won't be executed in an entry-controlled loop if the condition is false.

Entry-controlled loops are used when a test condition must be verified before the loop body is executed.

Examples for entry control loop:

1. for loop

2. while loop

3. for-each loop

The “for” loop:

While dealing with for loop, we just write one line of code. We can initialize the loop variable, verify the condition, and increment or decrement in this line. Then the body of the loop is carried out with the main logic.

Generally, for loop is used when the number of iterations count is fixed.

Syntax for “for” loop:

for (initialization; condition; updation)
 {    
       //Executable block of statements
}    
 

Example: program to print 1 to n numbers

import java.io.*;
import java.util.*;
public class ForDemo
{
public static void main(String[] args) {
    Scanner sc  = new Scanner ( System.in);
    System.out.println("enter the value of number");
    int num = sc.nextInt();
    for(int i=0; i <= num; i++)
    {
        System.out.println("The number is "+i);
        
    }
}
}
Java Control Statements

While Loop:

The while loop is also used to repeatedly loop through the number of statements. However, it is advised to use a while loop if we are unsure of the number of iterations. In contrast to for loop, while loop's initialization and increment/decrement operations do not happen inside the loop statement.

Since the condition is verified at the beginning of the loop, it is also referred to as the entry-controlled loop. If the condition is satisfied, the body of the loop will be run; otherwise, the statements following the loop will be run.

Syntax for “While” loop:

Datatype variable; //initialization
while(condition)
{
    Statements;
    Updating;
}
import java.io.*;
import java.util.*;
public class WhileDemo
{
public static void main(String[] args) {
    Scanner sc  = new Scanner ( System.in);
    System.out.println("enter the value of number");
    int num = sc.nextInt();
    int i=0;
    
    while(i<=num)
    {
        System.out.println("The number is "+i);
        i++;
        
    }
}
}
Java Control Statements

for-each loop:

Java offers an improved for loop for iterating through data structures like collections and arrays. We don't need to update the loop variable during the for-each loop.

Syntax for “for-each” loop:

for (datatype variable: array_name / collection_name)
{    
/ /statements    
}    

Example:

import java.io.*;
import java.util.*;




public class ForEachDemo
{
public static void main (String[] args) 
{
    String [] months = {"Jan","Feb","Mar","Apr","May"};    
        System.out.println("Printing the array months:\n");    
        for(String month: months)
        {    
            System.out.println(month);    
        }    
    }    
}    
Java Control Statements

Exit control loop:

If the test condition is false, the loop body will only be executed once in an exit-controlled loop. It starts with the loop body and ends with the condition. When the test condition must be verified after execution, an exit-controlled loop is used.

The best example for exit controlled loop is a do-while loop.

do-while loop:

The do-while loop executes the loop statements before checking the condition at the end of the loop. Use a do-while loop if the number of iterations is unknown, but the loop must be run at least once.

Syntax for “do-while” loop:

do
{
// executable block of statements 
} while (condition);   

Example:

import java.io.*;
import java.util.*;




public class DoWhileDemo
{
public static void main (String [] args) 
{
   Scanner sc = new Scanner (System.in);
   System.out.println("enter the value of number");
   int num = sc.nextInt();
   int i = 0;
   do
   {
       System.out.println ("The number is "+i);
       i++;
   } while (i < num);
    }    
}    
Java Control Statements

Jump Statements:

A jump statement can be used to alter the program's execution flow. They are also referred to as branching statements because they cause a different branch in the execution flow.

Jump statements are further divided into the following types. They are:

1. Break Statements

2. Continue Statements

Break Statements:

Break Statements are used with looping statements like for loop, while loop, or do while loop.

When a break statement is used inside a loop of a program, the loop is terminated immediately, and the execution proceeds with the next blocks of the program.

Generally, the break statement is either used with loops or a switch statement. It breaks the flow of the program under specific conditions. If it is used in nested loops, then it will break the loop in which it is mentioned. Let us understand the break statement with the following program.

Example program:

import java.io.*;
import java.util.*;


//consider the following program
//Java Program to demonstrate the use of break statement    
 
class BreakExample {  
    public static void main(String[] args) { 
        Scanner sc = new Scanner (System.in);
        System.out.println("enter the value");
        int n = sc.nextInt();
    
        //using for loop  
        for(int i=1;i<=n;i++)
        {
            if(i==n/2) // stopping condition or break condition
            {
                break;//jump statement 
                //the given condition prints the statements
                //from 1 to n values
            }
        
            System.out.println(i);  
        }  
    }  
}  
Java Control Statements

Continue Statement

Continue statement is a part of jumping statements in Java. It is used to skip a particular part of code.

It skips some part of the code when the continue statement is passed in that block of code.

It can be used with for loop or while loop. When the continue statement is used, it will be evaluated, the remaining code is skipped at the required condition, and the program's current flow is continued. It only continues the inner loop when there is one.

Example program:

import java.io.*;
import java.util.*;


//consider the following program
//Java Program to demonstrate the use of continue statement    
 
class ContinueExample {  
    public static void main(String[] args) { 
        Scanner sc = new Scanner (System.in);
        System.out.println("enter the value");
        int n = sc.nextInt();
    
        //using for loop  
        for(int i=1;i<=n;i++)
        {
            if(i==n/2) // skiping condition or continue condition
            {
                continue;//jump statement 
                //the given condition prints the statements
                //from 1 to n values
            }
        
            System.out.println(i);  
        }  
    }  
}  
Java Control Statements

Related Topics

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.