Java if else statement Tutorial

In this section, we will learn what the if-else statements are and how to use them in Java.

Java if Statement (AKA if-then statement)

If you have that “thing” then run the plan A otherwise go for the plan B. Sounds familiar?

Well, if you think about it, in real life we faced such situations a lot of times.

For example, if I get my salary this month, I’ll buy a brand new TV otherwise (else) I need to wait for the next month.

Basically, we use the word if and else in our lives in many situations to emphasize a conditional outcome.

In the world of Java programming we have the same situation as well.

For example, there might be a block of code that we want to run, but the execution of that block depends on the value of another variable named salary! To explain more: let’s say if the value of that variable is higher than the value 30000, then the code block is allowed to be run, otherwise another block of code should run instead.

These types of conditions are called if condition and we use if else statements in Java to handle them.

Java if-else syntax:

Here’s the structure of the `if else` statements:

if (condition){
    //body of the if-statement where code is and will be run if result of the condition is true
}else{
    //the code here will only run if result of the condition is not true. 
}
  •  if: To create an if statement, we start with the keyword if.
  • (): after the if keyword comes the parentheses. This is where we set the condition or conditions to be checked.

Note: The comparison operators are very handy here.

Here we can run a condition on the value of a variable and if the result of that condition was true then the body of the if statement will run.

For example, the condition might be age == 21 which means check and see if the value of the age variable is equal to 21. If the result was true, then instructions within the body of if-statement will run. Otherwise, the body of the else statement is the one to run.

Note: the value of a variable of type boolean can also be used in the parentheses of the if statement.

In this case if the value of the variable was true, then the body of the if statement will run, otherwise if the value was false it’s the body of the else statement to run.

  • {}: The open and close braces that comes after the parentheses, declare the starting and closing point of the body of the if statement.  Any code here in this block will be run if the result of the condition set in the parentheses is true.
  • else: the else keyword comes after the closing brace } of the if-statement and is used to set the instructions that should run if only the condition’s result of the if-statement is false.

Notes:

  1. The body of else-statement is within the braces that comes after the else keyword. Also this else-statement does not have parentheses to put a new condition.
  2. The use of else is optional and we can simply skip it. In this case if the condition of the if-statement was false then the instructions that come after the block of the if-statement will run (if any).

Also remember that either the body of if OR else statement will run (depending on the result of the condition in the if-statement) but not both.

Example: using Java if-else statement

public class Simple {
    public static void main(String[] args) {
        int age = 20;
        if (age >21){
            System.out.println("Yes the age is greater than 21");
        }else{
            System.out.println("The age is less than 21");
        }
    }
}
Output: 
The age is less than 21

How Does if-else statement work?

There’s a variable named age in this example and we’ve checked its value against the value 21 in the parentheses of the if statement via the greater than > operator.

Now, because the value of the age variable is not larger than the value 21, the result of this condition is false and so the body of the if statement is skipped and instead the body of the else statement is the one to run.

Java if statement with String values

When it comes to use if statement for string values, especially if the purpose is to compare two string values, things can get a little tricky!

For example, using the == operator to see if two string values have the same set of characters will not work the way you expected!

This is explained in the Java String equals () method section but in short, using the == operator for equality check, only results true if both string values are coming from the same memory space! Again this is a deeper level of Java and because we’re not in the objects yet, explaining this topic is difficult at this stage. Check the mentioned link to learn more about this topic if you’re comfortable with objects and memory-space.

Example: if statement and String values

class Main{
	public static void main(String[] args) {
		String name = "John"; 
		String name2 = new String("John");
		if (name == name2){
			System.out.println("The name and name2 are equal");
		}else{
			System.out.println("The name and name2 are not equal!");
		}
	}
}
Output: 
The name and name2 are not equal. 

Java if-else-if (AKA ladder) statement

There are times that we have multiple conditions and want to run a different set of instructions depending on which of these conditions result true.

This is where the else if statement comes in.

The statement is an addition to the if-else statement and as a matter of fact, it will sit between if and else statements.

Java if-else-if syntax

Take a look at the structure below:

if (condition_1){
    //body of the if-statement where code is and will be run if the condition is true
}else if (condition_2){
    //body of the else-if-statement where the code is and will be run if the condition_2 is true
}else if (condition_N){
    //body of the else-if-statement where the code is and will be run if the condition_N is true
}else{
    //the code here will only run if none of the conditions in if and else if result true. 
}

else-if: if the condition of the if statement was not true, then the condition of the first else-if statement will be checked. If the first else-if condition’s result was false as well, the second one will be checked and this process will go on until one of the else if statements result true and in that case the instructions within its body will run. Otherwise it’s the instructions of the else statement to run if none of the conditions result true.

Notes:

  • The use of this statement is optional and depending on the need of the program, we can add as many as we want between the if else statements.
  • If the condition of the if statement was true, the rest of else if statements and the else statement will be skipped.

Also, the same is true for any else if statement (any else-if statement results true, the rest of else-if statements will be skipped and only the body of that else-if statement will run)

Example: Java if-else-if statement

public class Simple {
    public static void main(String[] args) {
        int value = 200;
        if (value == 100){
            System.out.println("The value is: 100");
        }else if(value == 200){
            System.out.println("The value is: 200");
        }else if(value  == 150){
            System.out.println("The value is: 150");
        }else{
            System.out.println("None of the conditions matched the value\n");
        }
    }
}
Output: 
The value is: 200 

Java else Statement Note:

The else statement always comes as the last statement and will run only if none of the conditions before the statement result true. In another word if all the conditions were false, in that case only the body of else statement will run.

Also, we can only use one else statement. 

Example: Java else statement

public class Simple {
    public static void main(String[] args) {
        int money = 1000;
        int age = 21;
        if (age >= 21 && money >5000){
            System.out.println("The person can enter to the bar\n");
        }else if(age >= 21 && money <5000){
            System.out.println("The person can legally enter to a bar but she can't come to this bar because she doesn't have enough money");
        }else if(age <21 && money >5000){
            System.out.println("The person has the money but she is under legal age.");
        }
    }
}
Output: 
The person can legally enter to a bar but she can't come to this bar because she doesn't have enough money

Java Nested if..else Statement

There’s no limit on what we can put on the body of an if or else statement! This means we can even put another if-else statement there as well.

Basically, the use of if-else statement within the body of another if-else statement is called nested if-else statement.

Example: creating nested if…else statement in Java

class Main{
	public static void main(String[] args) {
		String name = "John"; 
		String name2 = new String("John");
		if (name != name2){
			System.out.println("The name and name2 are not the same object!");
			if (name.equals(name2)){
				System.out.println("But the content of both variables are the same!");
			}else{
				System.out.println("Also the content of these two variables are not the same!");
			}
		}
	}
}
Output: 
The name and name2 are not the same object!
But the content of both variables are the same!

Note: to learn about the equals () method, please check the related section.

More to Read:

Java ternary operator

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies