Control Statements in Java

Okay, till now we developed some programs and executed them. And we observed that these programs starts at main function and execute each and every line till main ends. But in majority of cases we need to execute some portion of code based on different conditions and some portions need to be skiped. For example we developed a program which takes user’s birth date. We have to check whether date is valid or not, like date should not be more 31 or 30 or 28 or 29 depends upon month and year. If it is not matching given condition then we need to tell user that date is he/she entered is invalid otherwise we should not show this message and proceed for further execution.

To achieve this kind of controlled execution where we are controlling which part of code to execute and what part to skip, Java provides different control statements. They are

  • if
  • ifelse
  • Nested ifs
  • ifelseif ladder
  • switch

if Statements

This is the very easiest one in control statements. Below is the syntax for if

if (condition){
    sequence of statements;
}

In the above syntax first it checks for the condition, if condition is true then statements inside if will execute. If condition is false then these statements will be skipped. Here to write condition we can use any of the relational operators we learnt in previous lessons.

/*
This is a simple Java program about if statement. Call this file KH_if.java.
*/
import java.util.*;

public class KH_if {
	// A Java program begins with a call to main().
	public static void main(String args[]) 	{
		int number;
		
		Scanner reader = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		number = reader.nextInt();
		
		if(number < 10)
		{
			System.out.println("Given number is less than 10.");
		}
		
		System.out.println("Program ended.");
	}
}

Download the code Run the code

In the above program we are reading a number from user and checking whether it is less than 10 or not. If it is less than 10 then we are printing “Given number is less than 10.” otherwise we are skipping it. Let’s see what happens if you give input as 6.

Enter a number: 6
Given number is less than 10.
Program ended.

See how our works as expected, now let’s give more than 10 as input.

Enter a number: 100
Program ended.

Nice, now our program is skipping statements inside if when condition is false. This is how we can use if statements.

ifelse

In our previous program, we are not notifying anything to user when input is greater than 10. But we want to notify that given input is greater than 10, and this should only execute when given condition false, when condition is true this part should not execute. To achieve this type of logic we use ifelse statement. Syntax,

if (condition) {
    sequence of statements;
}
else {
    sequence of statements;
}

In this ifelse statement, if works exactly same as previous section, but else part executes only when condition is false.

When if is executed else gets skipped and when if is skipped, else gets executed.

Now we can improve our previous program to include else parts.

/*
This is a simple Java program about if else statement.
Call this file KH_ifelse.java.
*/
import java.util.*;

public class KH_ifelse {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		int number;
		
		Scanner reader = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		number = reader.nextInt();
		
		if (number < 10) {
			System.out.println("Given number is less than 10.");
		}
                else {
                    System.out.println("Given number is greater than 10.");
                }		
		System.out.println("Program ended.");
	}
}

Download the code Run the code

Now lets see the output in both these cases, and it will be very clear to you.

Enter a number: 6
Given number is less than 10.
Program ended.
Enter a number: 100
Given number is greater than 10.
Program ended.

Nested ifs

We can write an if statement in another if statement. Of course we can include else with if and write if inside else also. For clear understanding on nested logic, let’s consider a guessing game, where user has to enter a number and program should check with answer prefixed in program. If it matches program should display “You won…”, else it should show two outputs based on input value they are, “Your guess is too low” or “Your guess is too high”.

You already know first if part, but for else part, we will use nested logic. See the below program:

/*
This is a simple Java program about Nested if else statement.
Call this file KH_Nestedifelse.java.
*/
import java.util.*;

public class KH_Nestedifelse {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
		int number;
		int answer = 10;
		
		Scanner reader = new Scanner(System.in);
		
		System.out.print("Enter a number: ");
		number = reader.nextInt();
		
		if(number == answer) {
			System.out.println("You won...");
		}
                else  {
			if(number < answer) {
				System.out.println("Given number is too low.");
			}
			else {
				System.out.println("Given number is too high.");
			}
                }
	}
}

Download the code Run the code

Output:

Enter a number: 10
You won...
Enter a number: 6
Given number is too low.
Enter a number: 14
Given number is too high.

ifelseif ladder

Above three ways of if are enough for all cases, but due to complexity of nested logic ifelseif ladder has been introduced. Its syntax,

if(condition1)
{
    statements_1;
}
else if(condition2)
{
    statements_2;
}
else if(condition3)
{
    statements_3;
}
....
....
else
{
    statements_x;
}

While executing our program first checks for condition1, if it true then executes statemetns_1 else it skips statemetns_1 and check for condition2. Again if condition2 is true then executes statemetns_2 else skips statemetns_2 and goes to condition3. This continues till the end of ladder, if none of conditions are true then last else will execute. Remember it is not compulsory to write last else block but it is a best practice to write.

Let’s understand more by using a program, takes a number between 1 – 7 and tells which day it is, for example for 1 – Sunday, 2 – Monday etc.

/*
This is a simple Java program about if else Ladder statement.
Call this file KH_ifelseLadder.java.
*/
import java.util.*;

public class KH_ifelseLadder {
	// A Java program begins with a call to main().
	public static void main(String args[]) {
            int number;
	    Scanner reader = new Scanner(System.in);
		
	    System.out.print("Enter a number between 1 - 7: ");
	    number = reader.nextInt();
		
	    if(number == 1){
			System.out.println("Sunday");
	    }
            else if(number == 2) {
			System.out.println("Monday");
	    }
            else if(number == 3){
			System.out.println("Tuesday");
	    }
            else if(number == 4){
			System.out.println("Wednesday");
	    }
            else if(number == 5){
		System.out.println("Thursday");
	    }
            else if(number == 6) {
		System.out.println("Friday");
	    }
            else if(number == 7){
		System.out.println("Saturday");
	    }
            else {
		System.out.println("In valid input, input should be between 1 - 7");
	    }
	}
}

Download the code Run the code

output:

Enter a number between 1 - 7: 1
Sunday
Enter a number between 1 - 7: 5
Thursday
Enter a number between 1 - 7: 8
In valid input, input should be between 1 - 7

switch Statements

Java also provides another control statement which is switch. Any logic we can write with ifelse ladder we can rewrite using switch. In some cases switch is more efficient and readable than ifelse ladder and vice versa. We need to use based on our choice.

switch( expression )
{
    case constant1:
        statements_1;
        break;
    case constant2:
        statements_2;
        break;   
    .....
    .....
    .....
    default:
        statement_x;
}

switch compares result of expression with any of constants against case, if it matches then executes corresponding statements. If it did not find any matches then default case will get executed.

Now we will rewrite above program to print week day using switch

/*
This is a simple Java program about switch statement.
Call this file KH_switch.java.
*/
import java.util.*;

public class KH_switch {
	// A Java program begins with a call to main().
	public static void main(String args[]) 
	{
		int number;
		
		Scanner reader = new Scanner(System.in);
		
		System.out.print("Enter a number between 1 - 7: ");
		number = reader.nextInt();
		
		switch(number)
		{
			case 1:
				System.out.println("Sunday");
				break;
			case 2:
				System.out.println("Monday");
				break;
			case 3:
				System.out.println("Tuesday");
				break;
			case 4:
				System.out.println("Wednesday");
				break;
			case 5:
				System.out.println("Thursday");
				break;
			case 6:
				System.out.println("Friday");
				break;
			case 7:
				System.out.println("Saturday");
				break;
			default:
				System.out.println("In valid input, input should be between 1 - 7");
				break;
                }
	}
}

Download the code Run the code

Output:

Enter a number between 1 - 7: 1
Sunday
Enter a number between 1 - 7: 5
Thursday
Enter a number between 1 - 7: 8
In valid input, input should be between 1 - 7

break

The keyword break is used in switch is to exist from switch block completely. Why? How switch works is that once it matches any case, it do not check for other cases below it, just executes all statements below it even though they are present in different case. So break forces to exist from switch block. If we execute above program with breaks, below is the output for better understanding.

Enter a number between 1 - 7: 1
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
In valid input, input should be between 1 - 7

These are different control statements present in Java. These statements are also called branching statements.

<<< Java Strings and Command Line ArgumentsJava looping statements >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .