Java if-else statement
A Java if-else statement chooses between two blocks of code. Java evaluates a Boolean condition first. When the condition is true, the if block runs. When it is false, the else block runs.
This tutorial explains Java if-else syntax, how conditions are evaluated, practical number and String examples, else if chains, nested if-else statements, and common mistakes to avoid.
1. Java if-else syntax
The syntax of if else statement is
if(condition) {
//if code block
} else {
//else code block
}
The expression inside if(...) must evaluate to a Java boolean value: either true or false.
If the condition evaluates to true, if code block is executed.
If the condition evaluates to false, else code block is executed.
Exactly one of the two blocks is executed for a normal if-else statement. After that block finishes, execution continues with the statement that follows the if-else structure.
2. How Java evaluates an if-else condition
Conditions commonly use comparison operators such as ==, !=, >, <, >=, and <=. They can also combine Boolean expressions with && for AND, || for OR, and ! for NOT.
if (age >= 18 && hasId) {
// runs only when both conditions are true
} else {
// runs when at least one condition is false
}
Java does not treat integers such as 0 and 1 as Boolean conditions. The expression inside if must itself produce a boolean.
3. Flow diagram of the Java if-else statement
The following flow diagram depicts the execution flow of an if-else statement in Java.
The condition is checked before either branch runs. A true result follows the if path, while a false result follows the else path. Both paths then continue with the code after the statement.
4. Java if-else examples
1. Check whether a number is positive with Java if-else
In this example, the condition x > 0 checks whether x is positive. If the condition is true, the if block prints that x is positive. Otherwise, the else block runs.
Main.java
public class Main {
public static void main(String[] args) {
int x = -2;
if(x > 0){
System.out.println("x is positive.");
} else {
System.out.println("x is not positive.");
}
}
}
Output
x is not positive.
Because x is -2, the expression x > 0 evaluates to false. Therefore, Java skips the if block and executes the else block.
2. Check whether a Java String contains “World”
In this example, the condition x.contains("World") checks whether the String stored in x contains "World" as a substring. Because contains() returns a Boolean value, it can be used directly inside if.
Main.java
public class Main {
public static void main(String[] args) {
String x = "Hello World";
if(x.contains("World")) {
System.out.println("x contains \"World\".");
} else {
System.out.println("x does not contain \"World\".");
}
}
}
Output
x contains "World".
The method contains() returns a Boolean value, so it can be used directly as the condition of an if-else statement.
3. Check whether a number is odd or even using Java if-else
The remainder operator % is useful for an odd-or-even check. An integer is even when dividing it by 2 leaves a remainder of 0.
public class Main {
public static void main(String[] args) {
int number = 17;
if (number % 2 == 0) {
System.out.println("number is even.");
} else {
System.out.println("number is odd.");
}
}
}
Output
number is odd.
5. Java else-if ladder for more than two conditions
A plain if-else statement handles two alternatives. When a program must test several mutually exclusive conditions in order, place one or more else if branches between if and the final else.
if (condition1) {
// runs when condition1 is true
} else if (condition2) {
// runs when condition1 is false and condition2 is true
} else {
// runs when all previous conditions are false
}
Java evaluates the conditions from top to bottom and stops at the first branch whose condition is true. The final else is optional and acts as the fallback when none of the preceding conditions match.
public class Main {
public static void main(String[] args) {
int score = 76;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else if (score >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
}
}
Output
Grade B
6. Nested if-else statements in Java
A nested if-else statement places one conditional statement inside another. Use nesting when a second decision should be checked only after an outer condition has selected a particular branch.
In the following example, Java first checks whether a is odd. Only when that condition is true does it evaluate the nested condition that checks whether a is less than 10.
Main.java
public class Main {
public static void main(String[] args) {
int a = 3;
if(a % 2 == 1) {
System.out.println("a is odd number.");
if(a<10) {
System.out.println("a is less than 10.");
} else {
System.out.println("a is not less than 10.");
}
} else {
System.out.println("a is even number.");
}
}
}
Run the program and you will get the following output in console.
Output
a is odd number.
a is less than 10.
The inner if-else is evaluated only after the outer condition a % 2 == 1 is true. For a = 3, the number is odd, so Java then checks whether it is less than 10.
7. Comparing Java Strings inside if-else
When an if-else condition needs to compare String contents, use methods such as equals() or equalsIgnoreCase(). The == operator compares object references, so it is not the correct general-purpose test for whether two String values contain the same characters.
public class Main {
public static void main(String[] args) {
String role = "admin";
if (role.equals("admin")) {
System.out.println("Administrator access");
} else {
System.out.println("Standard access");
}
}
}
Output
Administrator access
8. Common Java if-else mistakes
- Using
=instead of==:=assigns a value;==compares values for primitive types. - Comparing String contents with
==: useequals()when you need to compare the characters stored in two String values. - Writing conditions in the wrong order: in an
else ifladder, a broad condition placed first can prevent a more specific later condition from ever being tested. - Leaving out braces in multi-line branches: Java allows braces to be omitted for a single statement, but using braces consistently makes branch boundaries clearer and reduces mistakes when code is later expanded.
- Assuming both branches run: in one if-else statement, Java runs either the
ifbranch or theelsebranch, not both.
9. When to use if, if-else, else-if, or switch in Java
Use a standalone if when code should run only when one condition is true and no alternative action is required. Use if-else when exactly two paths are needed. Use an else if ladder when several ordered conditions must be checked.
A switch statement can be easier to read when one expression is being matched against several discrete cases. If the decision depends on ranges or unrelated Boolean expressions, if-else and else-if are usually the more direct fit.
Java if-else summary
In this Java Tutorial, we learned how to write an If-Else statement, nested if-else statement, and presented some Java examples.
The key rule is simple: Java evaluates a Boolean condition and follows one branch based on the result. Use else if when more than two outcomes are needed, and use nested if-else only when a second decision truly depends on an earlier one.
TutorialKart.com