Java if, else and else if
Programs must take decisions. The if statement runs a block of code only when a condition is true.
if
public class Main {
public static void main(String[] args) {
int marks = 72;
if (marks >= 40) {
System.out.println("You passed");
}
System.out.println("End of program");
}
}
Output
You passed
End of program
if … else
public class Else {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
}
}
Output
Minor
else if
Use else if to check many conditions. Java checks from the top and stops at the first true one.
public class Grade {
public static void main(String[] args) {
int marks = 76;
if (marks >= 90) {
System.out.println("Grade A+");
} else if (marks >= 75) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else if (marks >= 40) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}
Output
Grade A
Nested if
public class Nested {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
}
}
}
Output
You can drive
You can write this in a cleaner way with &&: if (age >= 18 && hasLicense).
Comparing text in conditions
public class Text {
public static void main(String[] args) {
String role = "admin";
if (role.equals("admin")) { // not role == "admin"
System.out.println("Welcome, admin");
}
}
}
Output
Welcome, admin
The ternary operator
public class Ternary {
public static void main(String[] args) {
int n = 7;
String type = (n % 2 == 0) ? "even" : "odd";
System.out.println(n + " is " + type);
}
}
Output
7 is odd
Common mistakes
- Using
=(assignment) instead of==(comparison). Java stops this forintvalues:if (x = 5)does not compile. - A semicolon after the condition:
if (x > 5);makes an empty if. - Leaving out the braces, then adding a second line which is not inside the if.
public class Mistake {
public static void main(String[] args) {
int x = 3;
if (x = 5) {
System.out.println("five");
}
}
}
Output
Mistake.java:4: error: incompatible types: int cannot be converted to boolean
if (x = 5) {
^
1 error
error: compilation failed
Note:
Always use curly braces, even for one line. It avoids bugs when you add more lines later. Next: Java switch.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |