If-else construct

Java supports two selection statements:

  1. If

  2. switch.

If - statement

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

An if construct enables you to execute code based on certain conditions.Output of these conditions should be a boolean value.

Flavors of If:

Example 1: Check whether a number is even or odd using if...else statement

public class EvenOdd {
    public static void main(String[] args) {
        int num = 12;
        if(num % 2 == 0)
            {
                 System.out.println(num + " is even");
            } 
        else
            {
                 System.out.println(num + " is odd");
            }
    }
}

When you run the program, the output will be:

Enter a number: 12
12 is even

Example 2: Assign a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on:

public class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

The output from this program is:

Grade = C

Working:

If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.

In no case will both statements be executed.

int a, b;
//...
if(a < b)
a = 0;
else
b = 0; 

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero

A) II. Nested ifs:

A nested if is an if statement that is the target of another if or else.

When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else.

package com.gs.ilp.corejava.flowcontrol;

public class NestedIf {
	public static void main(String[] args) {
		int i = 10;
		int j = 20;
		int a = 0;
		int b = 0;
		int c = 0;
		int d = 0;
		int k = 0;
		if (i == 10) {
			if (j < 20)
				a = b;
			if (k > 100)
				c = d; // this if is
			else
				a = c; // associated with this else
		} else
			a = d; // this else refers to if(i == 10)
	}
}

Here, as the comments indicate, the final else is not associated with if(j<20) because it is not in the same block (even though it is the nearest if without an else).

Rather, the final else is associated with if(i==10).

The inner else refers to if(k>100) because it is the closest if within the same block.

A) III. if-else-if Ladder:

A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.

Syntax:

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

else statement;

Here 'if' statements are executed from top to down.

As soon as one of the conditions controlling the 'if' is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.

If none of the conditions is true, then the final else statement will be executed.

The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed.

If there is no final else and all other conditions are false, then no action will take place.

Example: Demonstrate if-else-if statements.

package com.gs.ilp.corejava.flowcontrol;

public class TestIf {
	public static void main(String[] args) {
		String season = null;
		int month = 4; // April String season;
		if (month == 12 || month == 1 || month == 2)
			season = "Winter";
		else if (month == 3 || month == 4 || month == 5)
			season = "Spring";
		else if (month == 6 || month == 7 || month == 8)
			season = "Summer";
		else if (month == 9 || month == 10 || month == 11)
			season = "Autumn";
		else
			season = "Bogus Month";
		System.out.println("April is in the " + season + ".");
	}

}

Output:

April is in the Spring.

Problem: Find largest of 3 numbers using if else.

Last updated