The Java If Else Condition

In our last tutorial, we learned the Java Access Levels. In this article, we will learn the Java If Else Condition statements and how it alters the behavior of your program.

The If Statement

The construction of a Java If Statement is like this:

if (condition) {
     //code to be executed when the 
     //condition will result to true.
}

The program will test the condition and if it returns true, then it will go inside the bracket and execute whatever codes that are inside. For example,

int num = 20;
if (num > 10) {
     System.out.println("Above 10");
}

The num variable holds a value of 20. Next, in the if statement, the condition statement will be executed and test if it will return to true. Does the value of num is greater than 10? Since 20 > 10, then the condition will return true and will print the output of “Above 10”.

The If, Else Statement

The construction of a Java If-Else Statement is this:

if (condition) {
    //codes to be executed when the
    //condition returns to true
} else {
    //the codes to be executed when
    //the condition returns false.
}

If the condition is true, then execute the code inside the If bracket, else, if it is false, then execute else bracket. For example,

int num=10;
if (num > 10) {
    System.out.println("The number is greater than 10");
} else {
    System.out.println("The number is less than or equal to 10");
}

The num variable will be tested and if it is greater than 10, it will output “The number is greater than 10”, but if it’s not, the program will automatically fall to else statement and print “The number is less than or equal to 10”.

The If, Else If, Else Statement

The Java If, Else If, Else Statement is just a series of conditions that will test a given value and will go to else statement if no conditions return true. For example,

int num=20;
if(num==0){
     System.out.println("The number is 0");
} else if(num<10){
     System.out.println("The number is greater than 0 but less than 10");
} else {
     System.out.println("The number is greater than or equal to 10");
}

In the above codes, the num variable will be tested for conditions. If it satisfies the condition, it will execute the code inside the bracket. Take note that only one bracket of codes can be executed. For example, if num==0 returns to true, the remaining else if and else statement will be skipped and will never be called and automatically, the program will end the conditions. The else statement will only be called when all of the if conditions return false.

The next tutorial will be about Java Loop Conditions.

Share this tutorial!