if-else keywords in Java

The ” if-else ” construct is used to check if the given condition is met then do something, otherwise do something else.

The syntax looks like below:

1
2
3
4
5
6
7
8
if (boolean condition) {
 
    // do something if condition is met
 
} else {
 
    // do something else if condition is not met
}
if (boolean condition) {

    // do something if condition is met

} else {

    // do something else if condition is not met
}

Example

1
2
3
4
5
6
7
8
9
10
boolean isAdmin = true;
 
if (isAdmin) {
 
    System.out.println("Welcome Admin");
 
} else {
 
    System.out.println("Welcome regular employee");
}
boolean isAdmin = true;

if (isAdmin) {

    System.out.println("Welcome Admin");

} else {

    System.out.println("Welcome regular employee");
}


We can also write multiple if else statements as below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (condition1) {
 
    // do something if condition1 is met
 
} else if (condition2) {
 
    // do something if condition2 is met
 
} else if (condition3) {
 
    // do something if condition3 is met
 
} else {
 
    // do something else if no condition is met
}
if (condition1) {

    // do something if condition1 is met

} else if (condition2) {

    // do something if condition2 is met

} else if (condition3) {

    // do something if condition3 is met

} else {

    // do something else if no condition is met
}

Example:

We can write multiple if else statements to find the greatest number in the given 2 numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int number1 = 10;
 
int number2 = 20;
 
if (number1 > number2) {
 
    System.out.println("number1 is greater than number2");
 
} else if (number1 < number2) {
 
    System.out.println("number2 is greater than number1");
 
}else {
 
    System.out.println("number1 and number2 are equal");
}
int number1 = 10;

int number2 = 20;
 
if (number1 > number2) {

    System.out.println("number1 is greater than number2");

} else if (number1 < number2) {

    System.out.println("number2 is greater than number1");

}else {

    System.out.println("number1 and number2 are equal");
}

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on