1. What is an if-else statement?
It is a decision-making statement used to execute code based on a condition (true/false).
2. What is the syntax of if-else?
if (condition) {
// executes if true
} else {
// executes if false
}
3. Can we use if without else?
Yes, else is optional.
4. Difference between if-else and switch?
if-else → works with ranges, conditions
switch → works with fixed values (int, String, enum)
5. What is an else if ladder?
if (marks > 90) {
System.out.println("A");
} else if (marks > 75) {
System.out.println("B");
} else {
System.out.println("C");
}
6.What is nested if?
if (age > 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}
7. What happens if you miss curly braces {}?
if (true)
System.out.println("Hello");
System.out.println("World");
Output:
Hello
World
8. Can we write multiple conditions in if?
Yes
if (age > 18 && country.equals("USA")) {
System.out.println("Eligible");
}
9. What is the ternary operator (shortcut for if-else)?
int result = (a > b) ? a : b;
10.Can if condition be non-boolean in Java?
❌ No — must return boolean (true/false)
11.What will this output?
int x = 10;
if (x = 5) {
System.out.println("Hello");
}
❌ Compile-time error (condition must be boolean)
= is assignment not relational operator like ==
12.Floating Point Comparison Trap
Version1
double a = 0.1 + 0.2;
if (a == 0.3) {
System.out.println("Equal");
} else {
System.out.println("Not Equal");
}
Output:
Not Equal
value of a is value of a 0.30000000000000004
Due to precision issues in floating-point arithmetic
Version2:
package module3;
public class Sample {
public static void main(String[] args) {
float a = 0.1f + 0.2f;
System.out.println("value of a " + a);
System.out.printf("To print the actual value of a in memory with 10 precision values is %.10f ", a);
System.out.println();
if (a == 0.3) {
System.out.println("Equal");
} else {
System.out.println("Not Equal " + a);
}
}
}
output:
value of a 0.3
To print the actual value of a in memory with 10 precision values is 0.3000000119
Not Equal 0.3
Behind the scenes:
Why does System.out.println(a) show 0.3?
- System.out.println() uses formatted output, not raw memory value.
- It converts the float to a string
- While converting, it rounds to a reasonable number of digits
- So small precision errors are hidden.
- Memory value ≠ Printed value
- Java rounds for readability
- Comparison (==) uses actual value, not printed value
13.OR (||) Short Circuit
int a = 5;
if (a < 10 || ++a < 20) {
System.out.println(a);
}
Behind the scene:
First condition is true → second NOT executed
Output: 5
14.AND (&&) Short Circuit
int a = 5;
if (a > 10 && ++a < 20) {
System.out.println(a);
}
System.out.println(a);
Answer:
First condition is false → second is NOT executed
Output: 5
Tips:What is short-circuit evaluation?
In &&, if first condition is false → second is NOT checked
In ||, if first condition is true → second is NOT checked
Top comments (0)