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. if (boolean condition) {
  2.  
  3.     // do something if condition is met
  4.  
  5. } else {
  6.  
  7.     // do something else if condition is not met
  8. }
if (boolean condition) {

    // do something if condition is met

} else {

    // do something else if condition is not met
}

Example

  1. boolean isAdmin = true;
  2.  
  3. if (isAdmin) {
  4.  
  5.     System.out.println("Welcome Admin");
  6.  
  7. } else {
  8.  
  9.     System.out.println("Welcome regular employee");
  10. }
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. if (condition1) {
  2.  
  3.     // do something if condition1 is met
  4.  
  5. } else if (condition2) {
  6.  
  7.     // do something if condition2 is met
  8.  
  9. } else if (condition3) {
  10.  
  11.     // do something if condition3 is met
  12.  
  13. } else {
  14.  
  15.     // do something else if no condition is met
  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
}

Example:

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

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

About the Author

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