control statement in java

Control Statement In Java, Easy Explanation Ever

In this post, we are going to explain to you the control statement in java. The control statement in java is the same as in C++, but the way we are using it in C++ is not the same.

Control statements are also called a Decision statement. These statements are related to our daily life activities, such as want to play or not, if play then go to the park otherwise stay home.

Same way, Control statement in java or any programming language works.

All programming language uses the control statements to control the flow of execution of the program based on many different conditions. These are used to maintain the flow of the program in a specific way to solve the problem.

Control Statements In Java

  • if
  • if-else
  • nested-if
  • if-else-if
  • switch-case
  • jump – break, continue, return

These are the statements that allow you to control the flow of your program’s execution based upon conditions known only during the run time.

Now we are going to discuss each of the Statements in detail.

Decision Control Statement
Decision Control and Jump Statement

Property of Control Statement:

  • They are easy to use
  • Easy to create flow chart of control statement
  • Makes big problem easier.

If Statement:

This is one of the most used decision control statement in java and also very simple. This statement is used whenever you need to execute a set of code if a certain condition meets.

Syntax:

if(condition) 
{
// Statements to execute if
// condition is true
}

The syntax is very easy, It checks whether the condition is true or not, If true then execute statements in his body otherwise continue to the next block of code.

If We did not provide the curly braces after the If statement then it automatically takes one line within its body.

Example


// Java program to illustrate If statement
class GeeksToCode
{
    public static void main(String args[])
    {
        int a = 12;
        if(a==12)
        {
            System.out.println("True");
            
            System.out.println("a is equal to 12");
        }
        
        if(a == 12)                    // Takes One line in his body
        System.out.println("Again! a is equal to 12");
        
        if(a==13)
        {
            System.out.println("A is equal to 13");
        }
        
        System.out.println("A is no 13");
        
    }
}

Output:

True
a is equal to 12
Again! a is equal to 12
A is no 13

check your output

Now, what to do when we need to execute another set of code when the condition is false. That’s why we have If else statements that take care of this problem in a very simple manner.

If-else:

If-else statement is mostly used after the normal If statement because It provides you a way to execute another set of code when the condition of the If statement is wrong.

Syntax

if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
    
}

If -else statement is simply add on of else If statement. Same as in if statement, If We did not provide the curly braces after the If-else statement then it automatically takes one line within its body.

Example:

// Java program to illustrate if-else statement
class Geekstocode
{
public static void main(String args[])
{
int i = 12;    

if (i < 10) // condition false
        System.out.println("i is smaller than 15");
    else
        System.out.println("i is greater than 15");

          if (i > 10) // condition true
        System.out.println("i is smaller than 15");
    else
        System.out.println("i is greater than 15");
}
}

Output:

i is greater than 15
i is smaller than 15

Now, what happens if you have 2 condition’s to check. You can write three 2 if-else statement but it is not a good way of writing code. That’s why we have If else if statement java that holds more than 2 conditions in an efficient way.

If else If

If else If the statement is very helpful when you are dealing with more than 2 conditions. Here you can write multiple conditions in If in a ladder wise and in last write else if none of the above if the condition is true.

Syntax

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

JVM starts from the top to check true condition. If any Condition is true than it stops checking after that condition and if no condition is true than it will execute else statement.

Example


// Java program to illustrate if-else-if ladder
class GeeksToCode
{
    public static void main(String args[])
    {
        int i = 20;

        if (i == 10)
            System.out.println("i is 10");
        else if (i == 15)
            System.out.println("i is 15");
        else if (i == 20)
            System.out.println("i is 20");
        else
            System.out.println("i is not present");
            
            i = 10; //UPdated
            
            System.out.println("===================================");
            
             if (i == 10) //True condition
            System.out.println("i is 10");
        else if (i == 10) // Also True Condition but only first will execute
            System.out.println("i is again 10");
        else if (i == 20)
            System.out.println("i is 20");
        else
            System.out.println("i is not present");
            
            System.out.println("===================================");
            
            i = 50; // Updated
            
              if (i == 10) //False condition
            System.out.println("i is 10");
        else if (i == 10) // False Condition
            System.out.println("i is again 10");
        else if (i == 20) //False
            System.out.println("i is 20");
        else
            System.out.println("i is not present");
            
            
    }
}

Output

i is 20

is 10

i is not present

As you can see when we update the value of i from 1 to 20, Second if the condition is not executed even it is true.

Switch Case

the switch statement is a multiple branch statement. It is somehow the same as if-else if statement. Switch statement works with almost all data types except float and double.

Syntax

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Example


// Java program to illustrate switch-case
class Geekstocode
{
    public static void main(String args[])
    {
        int i = 9;
        switch (i)
        {
        case 0:
            System.out.println("i is zero.");
            break;
        case 1:
            System.out.println("i is one.");
            break;
        case 2:
            System.out.println("i is two.");
            break;
        default:
            System.out.println("i is greater than 2.");
        }
    }
}

Output

i is greater than 2.

Switch statement check the value of i with each case and execute only if matches.

Check the run code here

Note:

  • You can have N number of cases.
  • The Case data type must be the same as the switch
  • The case does not have variables
  • No duplicate case is allowed in Java
  • Each case may or may not have a break statement.

Switch Vs nested If

  • Switch Statement is more efficient than If else
  • If else is not better for multi-way branching while Switch is best for multi-way branching
  • Nested if are better for boolean values
  • In speed, switch are faster than If else
  • Code readability is good in the switch statements.

Jump Statement

Java support three types of Jump statements that are break, return, and continue. These are responsible for transferring the control from one part of the program to another part of the program.

Break Statement

The break statement is used whenever we want to break the execution of the program to move it on another part.

  • We use a break inside the switch.
  • Inside the loop to break the loop
  • we can not use break outside the loop, switch.

Syntax

break;

Example

In the below program, whenever if the condition is true break statement executed and nothing is printed on the screen

class Test
{
public static void main(String[] args)
{
int i=5;
if(i==5)
{
break; // error: break outside switch or loop
System.out.println(“In If);
}
}
}

Continue Statement

As the name suggest, Continue statement is used to continue the loop. Mostly, continue statement is used in the loop when you want to jump to next iteration of the loop directly without processing the rest of the code.

Continue statement are also used with for loop, switch, while, if condition.

Syntax:

continue;

Example

// continue in an if statement
class GeeksToCode
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it System.out.print(i + " "); } }
}

Output

1 3 5 7 9

Whenever in above program, number encountered is even, continue statement executed and it complete that particular iteration and move to the next iteration.

Return Statement

return statement is used to explicitly return from a method. It makes program control transfer back to the method from where it is called.

Syntax:

return;

Example:

class Return
{
public static void check(int a)
{
if(a!=3)
System.out.println("A is not 3");
if(a==5)
return; // after return no statement is executed.
System.out.println("A is 5");
}
public static void main(String args[]) { Return.check(5); }
}

Output

A is not 3

Predict The Output

Question 1:

public class GeeksToCode{
public static void main(String[] args){
int a = 15;
a +=15;
switch(a){
case 5: System.out.println("5");break;
case 30: System.out.println("30");break;
default: System.out.println("0");
}
}
}
  • 30
  • 5
  • 0
  • Error

Answer is 30.

Question 2:

Explanation: You first assign 15 to variable a and then add again 15 to variable a.

import java.util.Scanner;
public class GeeksToCode{
public static void main(String[] args){
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name : ");
name = sc.nextLine(); //assume if user enters 'Geekstocode'
switch(name.length()){
case 5: 
case 6: 
case 7: 
case 8: 
case 9: 
case 10: 
System.out.print("Length is 5-10"); break;
 default: System.out.print("Length not in 5-10");
}
}
}
  • Compile time Error
  • Length is 5-10
  • Length not in 5-10
  • Run Time error.

Output

Enter your name :
Length not in 5-10

You take the input “GeeksToCode” and it’s length is 11 that’s why default case is printed.

Question 3:

…………………….. statement provides an easy way to transfer the execution to different parts of your code based on the value of an expression.

  • If
  • while
  • switch
  • if else

Switch

Question 4:

Read the given two statements carefully and tell which is true and false
i) No two case constants in the same switch can have identical values.
ii) A switch statement is usually more efficient than a set of nested ifs.

  • T, F
  • F, T
  • T, T
  • F, F

T, T

Question 5:

The control expressions that are valid for an if statement is?

  • Integer
  • Boolean

Boolean

Question 6:

By using …………………….., you can force immediate termination of the loop, all other statements are not executed after using this statement.

  • Switch
  • Break
  • continue
  • return

break

Question 7:

If you need to select among a large group of conditions, a switch statement will run much faster than the equivalent logic coded using ……………….. statement.

  • If
  • nested If else
  • while
  • do-while

nested If else

Question 8:

The ………………. is an optional case when it will be executed if the value of the expression does not match with any of the case values.

A) switch
B) break
C) continue
D) default

Leave a Comment

Your email address will not be published. Required fields are marked *