In Java, the if-else construct is used to check if a condition is met then do something, otherwise do something else. The structure looks like follows:

if (condition) {
    // do something if condition is met
} else {
    // do something else if condition is not met
}

where condition can be a variable, a method call or an expression that must be evaluated to true. The code inside if block can be any Java statements. For example:

boolean passed = false;
// try something...
if (passed) {
    System.out.println("Congratulations!");
} else {
    System.out.println("Try again next time!");
}

The construct can be extended for multiple if-else pairs:

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 none condition is met
}

For example:

int score = calculateScore();

if (score > 90) {
    System.out.println("Excellent");
} else if (score > 70) {
    System.out.println("Very good");
} else if (score > 50) {
    System.out.println("Above average");
} else {
    System.out.println("Very bad");
}

If there is only one statement after the if or else, the opening and closing curly braces can be removed. For example:

if (score < 10)
    score = score + 10;
else
    score = score - 10;

See all keywords in Java.

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment