Condition Statements – if condition, if-else condition, nested-if, and Switch Statement

a couple of weeks ago

Also known as the Decision making statements, this allows the program to choose between the different alternatives available during the course of execution. If the expression is true, then certain line of code will be executed, otherwise some other line of code will be processed.

Java Programming language, gives an option for various kind of Control statements, and they are:

Control StatementDescription
IfAn if statement consists of a boolean expression followed by one or more statements.
If.. elseAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
Nested ifYou can use one if or else if statement inside another if or else if statement(s).
switchswitch statement allows a variable to be tested for equality against a list of values.  

The above mentioned control statements play a major role in the programming, since we are working in the sequential programming. Everything that will be executed, will be executed in the top – down approach. All the lines are processed one-by-one.

But there are instances when we don’t want all the code to be executed, we want to verify certain conditions first, then accordingly certain line of code should be processed.

Let’s take a very basic example to support my writing:

In most of countries, people are allowed to vote only if their age is greater than 18 years otherwise they need to wait till they meet up the eligibility criteria.

So, seeing the above flow diagram user will only be allowed in the polling booth if his/her age is greater than 18. All the above expressions could be written with the help of Decision-making statements. Now let us discuss them in detail:

If Statement

The if statement is a single conditional expression that executes only if the provided condition is true

Syntax-

if(condition)
{  
	//your code
}  

Below Data flow diagram could explain it:

The above flow diagram shows, that the code written inside the if condition will be executed only if the condition is true, otherwise the program control will fall to the next line after the if block.

Example 1 –

public class Test {

	public static void main(String args[]) {
		int age = 19;

		if (age > 18) {
			System.out.println("User is eligible to vote");
		}

	}
}

Output-

User is eligible to vote


Example 2 –

public class Test {

	public static void main(String args[]) {
		int age = 17;

		if (age > 18) {
			System.out.println("User is eleigible to vote");
		}

		System.out.println("It didn't enter the if block since the condition was false");
	}
}


Output –

It didn't enter the if block since the condition was false


If-else Statement

The if-else statement has two blocks to execute, depending on the nature of condition. If the condition is true, then if block executes otherwise else block executes. [The very first block]. Otherwise the block that is mentioned after the else statement.

It is to be used, when we want to perform either of the action based on the condition.

Syntax-

if(condition)
{  
	//your code for true  
}
else
{  
	//your code for false  
}  

Below Data flow diagram could explain it:

The above Data flow diagram shows that, if the condition is true then the if(true) block will be executed otherwise the else(false) block will be executed.

Example

public class Test {

	public static void main(String args[]) {
		int age = 17;

		if (age > 18) {
			System.out.println("User is eligible to vote");
		} else
		// Since the condition 17>18 is false , so the else block will be executed
		{
			System.out.println("User is not eligible to vote");
		}

	}
}

Output –

User is not eligible to vote

Nested –If Statement

Nested, as the term only suggest, something that is inside another. In Java also we are provided with the option of Nested if-else, where Nested if statement is an if statement inside another.

So you will observe multiple if block in this case. And its only when the outer if block is true then the inner if block is executed.

if(condition)
{    
     		//your code
     if(condition)
{  
    	    //your code
    }    
}

Below Data flow diagram could explain it:

The above Data flow diagram shows that, until the codition1 is declared as true, the flow will not enter the Nested if block. Nested If statements are only executed when the Outer block is true.

Example-1 (When the Outer Block is true)

public class Test {

	public static void main(String args[]) {
		int age = 19;
		String citizenStatus = "Indian";

		if (age > 18) {
			System.out.println("User is partially eligible");

			if (citizenStatus == "Indian") {
				System.out.println("User is eligible, since you match age & citizenship criteria");
			} else {
				System.out.println("You are eligible , since you are not the citizen");
			}

		}

	}
}

Output –

User is partially eligible
User is eligible, since you match age & citizenship criteria


In the above example, since Condition1 (19>18) gave the result as true, so we are able to enter the inner if block.

Now observe the below example, where the condition 1 gave the result as false, then in that case it doesn’t enter either of the if Block. It Directly goes to the outer else block

Example-2 (When the Outer Block is true)

public class Test {

	public static void main(String args[]) {
		int age = 17;
		String citizenStatus = "Indian";

		if (age > 18) {
			System.out.println("User is partially eligible");

			if (citizenStatus == "Indian") {
				System.out.println("User is eligible, since you match age & citizenship criteria");
			} else {
				System.out.println("You are eligible , since you are not the citizen");
			}

		} else {
			System.out.println("It didn't enter either of the if block");
		}

	}
}

Output –

It didn't enter either of the if block

Note: In the programming we mostly use either if-else or Nested If-else.

Switch Case:

The switch statement in Java is a multi-branch statement. It is usually used in Java when we have multiple options to select from. Based on the input or expression one of the option is selected from the switch case.

When only one expression needs to be evaluated, then instead of using if else condition, we prefer using Switch case in order to make code cleaner.

Syntax-

switch(expression){
Case :
// statements [];
Case :
// statements [];
default:
// statements [];
}

Some points to keep in mind, while working with Switch case is:

  • The expression can be of type int, short, byte, etc.
  • Duplicate case values are prohibited.
  • Switch case has a default statement that is optional to use. But personally I would recommend using the same. (Example is explained below)
  • Switch case usually works with a break statement, but it’s optional. If not provided then it will continue with the next case, even though the condition has been met, using break helps in jumping out of the switch block when a condition is successfully met. (Example is explained below)

Below Data flow diagram could explain it (without break statement)

The above Data flow diagram shows that, when the switch case is being used without the break statement. In such a scenario, wherever any case matches the expression, it will execute the statements under that case along with all the cases that are following after will be executed.

Break is an optional statement, but it’s better to avoid such scenario of printing all the results, even though expression matched a case.

Example -1 (Switch Case without break)

public class Test {

	public static void main(String[] args) {
		// The java switch statement is fall-through.
		// It means it executes all statement after first match if break statement is
		// not used with switch cases.
		int num = 100;
		switch (num) {

		case 100:// Even though this case matches the switch expression
			System.out.println("Value of Case 1 is " + num);
		case 200:// This case will be executed since the break statement is not present
			System.out.println("Value of Case 2 is " + num);
		case 300:// This case will be executed since the break statement is not present
			System.out.println("Value of Case 3 is " + num);
		default:// This case will be executed since the break statement is not present
			System.out.println("Value of default is " + num);

		}

	}
}


Output-

Value of Case 1 is 100
Value of Case 2 is 100
Value of Case 3 is 100
Value of default is 100


In the above example, all the statements are being printed after the case 100, since break statement is not present in the code. And this leads to unnecessary output which is not required. To avoid this, we will be showing the use of break statement.

Below Data flow diagram could explain it: (With break statement)

The above Data flow diagram shows that; the switch case is being used with the break statement. And in such a scenario, wherever any case matches the expression, then the control goes to the break statement, which in turn ends the switch case and moves out to next line of code after the ending brackets for the switch statement.

Using break, help in delivering good quality code.

Example -2 (Switch Case with break)

public class Test {

	public static void main(String[] args) {
		// The java switch statement is fall-through.

		int num = 100;
		switch (num) {

		case 100:// It will print only this case
			System.out.println("Value of Case 1 is " + num);
			break;// Control is taken out of the switch case
		case 200:// This case will be executed since the break statement is not present
			System.out.println("Value of Case 2 is " + num);
			break;
		case 300:// This won't be executed
			System.out.println("Value of Case 3 is " + num);
			break;
		default:// This won't be executed
			System.out.println("Value of default is " + num);

		}

	}
}

Output-

Value of Case 1 is 100

In the above example, Only the statements under case 100 is being printed, remaining all the line of code in switch case is skipped. This is happening due to the presence of break statement.

These all Conditional Statements would be helpful in your Programming career.

Tejasvi Nanda

About the Author

Tejasvi Nanda