Java If Statement Tutorial With Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

Java If also known as the if-then statement is the simplest form of decision-making statement. Learn about all variations of If else in Java:

We will explore how Java uses if-statement to perform a conditional check. This conditional check is also known as decision making in Java.

Thus Java – if construct helps in writing decision-driven statements and allows us to execute some specific set of codes that are based on some specific condition.

This tutorial includes programming examples, syntax, and real-world examples that will help you understand the if-construct better.

=> Take A Look At The Java Beginners Guide Here.

Java if statement

In this tutorial, we will cover the following variations of the if statement in detail.

  • Simple if statement
  • If-else statement
  • Nested if statement
  • If-else-if ladder
  • Ternary operator

Java If Statement

The Java “if statement” (also known as “if-then statement”) is the most simple form of decision-making statement. This if-statement helps us to lay down certain conditions. Based on these conditions, we specify some lines of code to execute.

Syntax:

if (specify condition here) {

// specify code to be executed here

}

If the condition of the if-statement is true only then the code inside the parenthesis will execute.

Java if flowchart

If Condition Example

In the below example, we have initialized a variable with the value 10. Then we started the if-statement and specified the condition. If the condition is satisfied, then the print statement (inside if) will execute.

public class example {

	public static void main(String[] args) {
		
		int a=10;
		
		// specified condition inside if statement
		if (a>=5){
			
			/*
			 *  if the condition is satisfied then
			 *  print the below statement
			 */ 
			
			System.out.println("a is 10");
		}

	}

}

Output:

If condition Example

Java If-else

This is also known as if-then-else. Here, we specify the condition not only in the if-statement but we also have the else block where we specify the condition. This is the most commonly used decision-making statement.

If the condition specified in the “if-statement” is false then the condition of the “else statement” will be executed.

Syntax:

if (specify condition here) {

// specify code to be executed here

} else {

// specify code to be executed here

}

Java if else flowchart

If-else Example

In the below example, we have specified both the if and else condition. The print statement of the if block will execute only when the condition of the if block matches. Otherwise, the print statement of the else block will execute.

public class example {

	public static void main(String[] args) {
		
		int a=10;
		
		// specified condition inside if statement
		if (a<=5){
			
			/*
			 *  if the condition is satisfied then
			 *  print the below statement
			 */ 
			
			System.out.println("a is less than 5");
			
		} else{
			
			// otherwise print the below statement
			System.out.println("a is greater than 5");
		}

	}

}

Output:

If-else Example

Given below is the Java program to check the voting eligibility. Initially, we have taken the input age through the console using the Scanner class. Then we have added a conditional check for the age criteria using the if-else statement.

If the input age is 18 or greater than 18 then the voter is eligible to vote, else not.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		int voter_age;
		System.out.println("Enter the age: ");
		
		// Taking input from the console
		
		Scanner in = new Scanner(System.in);
		voter_age = in.nextInt();
		
		// conditional check for age criteria
		if(voter_age >= 18){
			System.out.println("Voter is eligible to vote");
		}
		
		else{
			System.out.println("Voter is not eligible to vote");
		}
	     
	}

}

Output:

if else example output

Now, let’s guess the output of the following program and write the explanation.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		int a,b;
		System.out.println("Enter the numbers: ");
		
		// Taking input from the console
		
		Scanner in = new Scanner(System.in);
		a = in.nextInt();
		b = in.nextInt();
		
		// conditional check for age criteria
		
		if(a == b){
			System.out.println("a is equal to b");
		}
		
		else if(b == a){
			System.out.println("b is equal to a");
		}
	     
	}

}

If you notice both the conditions, then you could realize that they the same. In both conditions, a and b are equal. However, in such programs, the outermost if-statement holds the highest priority. This is the reason why the output of this program would be “a is equal to b”.

Now, if you add another if-statement where you specify the same condition i.e. (a == b), then also the first/outermost if-statement will be executed.

Example 2

Nested If Statement

Nested if statement means the occurrence of one if-block inside another if-block. In such a statement, the outer if-block will be executed and only then the inner if-block will execute.

Syntax:

if (specify condition here) {

// specify code to be executed here

if (specify condition here) {

// specify code to be executed here

}
}

Nested if statement flowchart

Nested If Statement Example

In the below example, we have made use of multiple if-statement (one inside other). When the outer if block condition matches then the inner if block condition will be checked.

When all the specified if block conditions are true then the print statement will be executed.

public class example {

	public static void main(String[] args) {
		
		int a=10;
		int b=15;
		
		// specified condition inside if statement
		if (a>9){
			
			// specified condition inside another if statement
			if(b>=10){
				
				// print this only if both conditions are true
				System.out.println("This is nested if example");
			}
		}

	}

}

Output:

Nested if statement example - output

Java If-else-if Ladder

This ladder is used to specify new conditions after the previous condition fails. This is used to check multiple conditions in a single program. The statement starts with an if-block where we specify some conditions. It is followed by multiple else if statements.

This means if the first “if condition” fails, then we can check the conditions mentioned in the forthcoming “else-if conditions”.

Syntax:

if (condition1) {

// specify code to be executed here

} else if (condition2) {

// specify code to be executed here

}

....

else {

// specify default code when all conditions are false

}

Java if-else-if ladder flowchart

Java If-else-if ladder example

In the below example we have initialized a variable age with a certain number or integer. Then with the help of the Java if-else-if ladder, we tried to categorize the age. Each category has one print statement that will execute only when the condition is satisfied or true.

Lastly, there is one default statement that will be executed when all the conditions are false.

public class example {

	public static void main(String[] args) {
		
		int age= 92;
		
		// specified condition inside if statement
		if (age < 10){
			System.out.println("Kid");
		}
		
		// specified another condition
		else if (age >= 13 && age < 20){
			System.out.println("Teenager");
		}

		// specified another condition
		else if (age >= 25 && age < 50){
			System.out.println("Adult");
		}
		
		// specified another condition
		else if (age >= 50 && age < 100){
			System.out.println("Old age");
		}
		
		// default statement
		else {
			System.out.println("Uncategorized");
		}
	}
}

Output:

Java if-else-if ladder example

Below is the Java program to check whether a number is positive or negative. Initially, we have taken a number through the console using the Scanner class. Then, we have checked the condition for the positive and negative scenarios using the if-else statement.

Finally, we have added a default condition where we have mentioned that the number must be zero if it does not match the above-specified conditions.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		System.out.println("Enter the number: ");
		
		// Taking input from the console
		
		int num;
		Scanner in = new Scanner(System.in);
		num = in.nextInt();
		
		// conditional check for age criteria
		if(num < 0){
			System.out.println("Negative number");
		}
		
		else if(num > 0){
			System.out.println("Positive number");
		}
		
		else{
			System.out.println("Number is zero");
		}
	     
	}

}

Output:

if else ladder example

Below is the Java program. Initially, we have taken the ages of three different people through the console using the Scanner class. Then, we have implemented the conditional check using the if construct where we have compared the first-person’s age with the other two.

We have repeated this step using the if-else statement and compared all three of them with all other.

Finally, we have added a default statement where we have taken the equal age of all three into consideration. This will be executed if none of the above mentioned condition is met.

import java.util.Scanner;

public class example {

	public static void main(String[] args) {
		
		System.out.println("Enter the ages of John, Smith, and Federer: ");
		
		// Taking input from the console
		
		int John, Smith, Federer;
		Scanner in = new Scanner(System.in);
		John = in.nextInt();
		Smith = in.nextInt();
		Federer = in.nextInt();
		
		// conditional check for age criteria
		
		if((John > Smith)&& (John> Federer)){
			System.out.println("John is oldest");
		}
		
		else if((Smith > John)&& (Smith> Federer)){
			System.out.println("Smith is oldest");
		}
		
		else if((Federer > John)&& (Federer> Smith)){
			System.out.println("Federer is oldest");
		}
		else{
			System.out.println("They are of same age");
		}
	     
	}

}

Output:

If ladder example 2

Ternary Operator

Java supports the ternary operator which can be an alternative to if-then-else statements. Using this operator, we can perform the same task that we perform through the if-else statement.

It is represented by “?:”. If the condition is true then the result of the “?” condition is returned. Otherwise, the result of “:” is returned.

Let’s see the below example where we have taken an input year along with the variable result. In this variable, we have put the condition inside “?” to check whether the input year is divisible by 4 & 400, or not and the remainder should not be zero when divided by 100.

If the condition inside the “?” operator is met then it’s a leap year, otherwise, it’s not a leap year.

Note: For more details on the ternary operator, click here

public class example {

	public static void main(String[] args) {
		
		int yy=2020;    
	    String result=((yy%4==0)&&(yy % 100 !=0)) || (yy % 400==0)?"leap":"not leap";    
	    System.out.println("The year is: " + result + " year");  
 

	}

}

Output:

Java ternary operator

Java if-else Equivalent Example

In the above example, we saw how to check whether a year is a leap year or not. In this section, we are going to put up an equivalent program that will do the same thing through the Java if-else statement.

public class example {

	public static void main(String[] args) {
		
		int yy=2020;    
	    if(((yy%4==0)&&(yy % 100 !=0)) || (yy % 400==0)){
	    	    System.out.println("The year is leap year");
	    }
	    else{
	    	System.out.println("The year is not leap year");
	    }
	     
	}

}

Output:

Java if else equivalent example

Frequently Asked Questions

Q #1) What is Elif in Java?

Answer: Elif is neither a function nor a keyword. Also, it is not available in Java. In Java, Elif is nothing but an abbreviated form of the else-if statement. The if-statement can be used without an else but the Elif can never be used without an else statement.

The Elif statement is a conditional statement where we have one if-statement with a condition that is followed by the else-if statements with the conditions specified for each else-if.

Q #2) What is the difference between if/then and if/then else statement?

Answer: The simple if-statement is also known as if/then statement where we have conditions specified under the if-statement. If the condition is true then the code inside if-statement executes.

Java if-else statement is known as if/then else statement where we have conditions specified under the if-statement. This is followed by an else statement. If the condition of the if-statement is true then the code inside the if-statement executes, otherwise, the else statement is executed.

Q #3) What does == mean in Java?

Answer: It is a relational operator that has the boolean return type. If the value of the variables (which are being compared with each other) matches, then it returns true, otherwise false.

Q #4) Can you put two conditions in an if statement?

Answer: Yes, we can specify any number of conditions inside an if statement. This is done using the logical and relational operators like “&&”, “||”, “==” and so on.

Q #5) Can you have multiple if statements in Java?

Answer: Yes, we can have multiple if statements in Java where we can specify different conditions to test in each if statement.

Conclusion

In this tutorial, we have explained the different variations of the Java if-construct that includes simple if condition, if-else condition, nested if condition, if-else-if ladder, and ternary operator with if-else equivalent example. Each of them is explained with a proper example, syntax, and description of what it does and how it operates.

Each variation is explained with the help of a flowchart diagram as well as programming examples that will help you in understanding the topic better.

This is the most common way of performing a conditional-check or decision-making in Java apart from some other techniques like switch-statement and loops which will be discussed later.

=> Read Through The Easy Java Training Series.

Was this helpful?

Thanks for your feedback!

Leave a Comment