Definition
📌 Conditions
Java's conditional statements are almost identical to C++'s, requiring a genuine boolean expression inside if.
Syntax
syntax
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}Example
java
public class Main {
public static void main(String[] args) {
int marks = 72;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 60) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}Output
outputGrade: B
Important Points
- Conditions must evaluate to a real
boolean— Java won't accept anintdirectly. - Traditional
switchstill needsbreak;in each case to avoid fall-through. - The ternary operator works the same as in C/C++:
a > b ? a : b. - Nesting many
if/elsecan often be simplified withswitchor early returns.
Common Mistakes
- Forgetting
break;in a traditionalswitchstatement. - Trying to use a non-boolean value directly as a condition.
- Comparing objects (like
String) with==instead of.equals().
Interview Tip
🎯 Before your interview
A famous Java gotcha: comparing
String values with == compares references, not content — always use .equals() for strings.
