Practice Questions — Conditional Statements in Java (if, else, switch)
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
int x = 10;
if (x > 5) {
System.out.println("Big");
}
System.out.println("Done");Check if 10 > 5. The last line is outside the if block.
BigDoneQuestion 2
Easy
What is the output?
int x = 3;
if (x > 5) {
System.out.println("Big");
}
System.out.println("Done");Is 3 > 5?
DoneQuestion 3
Easy
What is the output?
int num = 7;
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}What is 7 % 2?
OddQuestion 4
Easy
What is the output?
int marks = 85;
if (marks >= 90) {
System.out.println("A");
} else if (marks >= 80) {
System.out.println("B");
} else if (marks >= 70) {
System.out.println("C");
} else {
System.out.println("D");
}Check conditions top to bottom. Which is the first true condition?
BQuestion 5
Easy
What is the output?
int a = 5, b = 5;
if (a == b) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}Does 5 equal 5?
EqualQuestion 6
Medium
What is the output?
int x = 15;
if (x > 10) {
System.out.println("A");
}
if (x > 5) {
System.out.println("B");
}
if (x > 0) {
System.out.println("C");
}These are three SEPARATE if statements, not if-else if.
ABCQuestion 7
Medium
What is the output? Compare with the previous question.
int x = 15;
if (x > 10) {
System.out.println("A");
} else if (x > 5) {
System.out.println("B");
} else if (x > 0) {
System.out.println("C");
}This IS an if-else if chain. Only the first true condition's block runs.
AQuestion 8
Medium
What is the output?
int x = 10, y = 20;
if (x > 5 && y > 15) {
System.out.println("Both");
} else if (x > 5 || y > 15) {
System.out.println("At least one");
} else {
System.out.println("Neither");
}Check if BOTH conditions are true with &&.
BothQuestion 9
Medium
What is the output?
String result = (85 >= 40) ? "Pass" : "Fail";
System.out.println(result);This is a ternary operator. Check the condition.
PassQuestion 10
Medium
What is the output?
int day = 2;
switch (day) {
case 1:
System.out.println("Mon");
case 2:
System.out.println("Tue");
case 3:
System.out.println("Wed");
break;
default:
System.out.println("Other");
}There is no break after case 1 and case 2.
TueWedQuestion 11
Hard
What is the output?
int x = 5;
if (x > 3) {
if (x > 7) {
System.out.println("A");
} else {
System.out.println("B");
}
} else {
if (x > 1) {
System.out.println("C");
} else {
System.out.println("D");
}
}First check the outer if. Then the inner if within the matching block.
BQuestion 12
Hard
What is the output?
String a = new String("hello");
String b = "hello";
if (a == b) {
System.out.println("Same");
} else {
System.out.println("Different");
}
if (a.equals(b)) {
System.out.println("Equal");
}== compares references. .equals() compares content.
DifferentEqualQuestion 13
Hard
What is the output?
int x = 2;
switch (x) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
}Case 2 has no break. Fall-through continues until a break is hit.
TwoThreeFourQuestion 14
Hard
What is the output?
boolean a = true, b = false, c = true;
if (a && b || c) {
System.out.println("X");
}
if ((a && b) || c) {
System.out.println("Y");
}
if (a && (b || c)) {
System.out.println("Z");
}&& has higher precedence than ||.
XYZQuestion 15
Medium
What is the difference between using separate if statements and an if-else if chain? When would you use each?
Think about whether conditions are independent or mutually exclusive.
With separate if statements, every condition is checked independently; multiple blocks can execute. With if-else if, checking stops at the first true condition; only one block executes. Use if-else if for mutually exclusive conditions (like grade ranges). Use separate ifs when conditions are independent and multiple might apply.
Question 16
Hard
Why should you use .equals() instead of == for String comparison in Java? Can == ever give the correct result for Strings?
Think about the string pool and the new keyword.
== compares object references (memory addresses), not content. .equals() compares the actual character content. == CAN return true for string literals due to the string pool (Java interns literals), but it fails for strings created with new or obtained from methods like substring(), concat(), user input, etc. Relying on == for strings is unreliable and is a bug.Mixed & Application Questions
Question 1
Easy
Write a program that takes a number and prints whether it is positive, negative, or zero.
Use if-else if-else with comparisons to 0.
import java.util.Scanner;
public class SignCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num > 0) {
System.out.println("Positive");
} else if (num < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
sc.close();
}
}Question 2
Easy
What is the output?
int age = 16;
if (age >= 18) {
System.out.println("Can vote");
}
System.out.println("Done");16 is not >= 18. The last line is outside the if.
DoneQuestion 3
Medium
What is the output?
int x = 5;
if (x > 2) {
System.out.println("A");
if (x > 4) {
System.out.println("B");
}
System.out.println("C");
}
System.out.println("D");Trace the nesting. 'C' is inside the outer if but outside the inner if.
ABCDQuestion 4
Medium
Kavya needs a program that takes age and nationality as input. Print 'Eligible' if age >= 18 AND nationality is 'Indian'. Otherwise, print 'Not Eligible'. Use String comparison correctly.
Use && to combine conditions. Use .equals() for String comparison.
import java.util.Scanner;
public class Eligibility {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine();
System.out.print("Enter nationality: ");
String nationality = sc.nextLine();
if (age >= 18 && nationality.equals("Indian")) {
System.out.println("Eligible");
} else {
System.out.println("Not Eligible");
}
sc.close();
}
}Question 5
Medium
What is the output?
int num = 15;
if (num % 3 == 0 && num % 5 == 0) {
System.out.println("FizzBuzz");
} else if (num % 3 == 0) {
System.out.println("Fizz");
} else if (num % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(num);
}Is 15 divisible by both 3 and 5?
FizzBuzzQuestion 6
Medium
What is the output?
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
default:
System.out.println("Invalid");
}switch works with char type.
GoodQuestion 7
Hard
What is the output?
int x = 10;
if (x > 5) {
x = x - 3;
if (x > 5) {
x = x - 3;
if (x > 5) {
System.out.println("Still big");
} else {
System.out.println("Getting small");
}
} else {
System.out.println("Small");
}
}
System.out.println("x = " + x);Trace x: starts at 10, then 7, then 4.
Getting smallx = 4Question 8
Hard
What is the output?
String s = "";
if (s != null && !s.isEmpty()) {
System.out.println("Has content");
} else {
System.out.println("Empty or null");
}
String t = null;
if (t != null && t.length() > 0) {
System.out.println("Has content");
} else {
System.out.println("Empty or null");
}Short-circuit evaluation: if the left side of && is false, the right side is not evaluated.
Empty or nullEmpty or nullQuestion 9
Hard
What is the output?
int a = 10, b = 20, c = 30;
if (a > b) {
System.out.println("X");
} else if (b > c) {
System.out.println("Y");
} else if (a + b == c) {
System.out.println("Z");
} else {
System.out.println("W");
}Check each condition: 10 > 20? 20 > 30? 10 + 20 == 30?
ZQuestion 10
Medium
Write a program that reads three numbers and prints the largest using only if-else statements (no Math.max).
Compare each number with the other two using &&.
import java.util.Scanner;
public class Largest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (a >= b && a >= c) {
System.out.println("Largest: " + a);
} else if (b >= a && b >= c) {
System.out.println("Largest: " + b);
} else {
System.out.println("Largest: " + c);
}
sc.close();
}
}Question 11
Hard
What is the output?
int x = 5;
int result = (x > 10) ? 100 : (x > 3) ? 50 : 10;
System.out.println(result);Nested ternary evaluates from right to left.
50Question 12
Hard
What is the output?
String s1 = "Java";
String s2 = "Ja" + "va";
String s3 = "Ja";
s3 = s3 + "va";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));Compile-time constant expressions are interned. Runtime concatenation creates new objects.
truefalsetrueQuestion 13
Easy
What is the output?
int x = 0;
if (x != 0) {
System.out.println("Non-zero");
} else {
System.out.println("Zero");
}Is 0 not equal to 0?
ZeroQuestion 14
Medium
What is the output?
int a = 5, b = 10;
int max = (a > b) ? a : b;
int min = (a < b) ? a : b;
System.out.println("Range: " + min + "-" + max);Ternary picks the larger and smaller values.
Range: 5-10Question 15
Hard
What is the output?
int x = 5;
switch (x) {
default:
System.out.println("Default");
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
}default does not have to be at the end. Case 5 matches.
FiveQuestion 16
Hard
What is the output?
int x = 3;
switch (x) {
default:
System.out.println("Default");
case 5:
System.out.println("Five");
break;
case 10:
System.out.println("Ten");
}x = 3 does not match any case. default runs, but no break follows.
DefaultFiveMultiple Choice Questions
MCQ 1
Which keyword starts a conditional statement in Java?
Answer: C
C is correct. The
C is correct. The
if keyword starts a conditional statement in Java.MCQ 2
What must a condition in an if statement evaluate to?
Answer: C
C is correct. In Java, the condition in an
C is correct. In Java, the condition in an
if statement must be a boolean expression (true or false). Unlike C/C++, integers cannot be used as conditions in Java.MCQ 3
What is the else keyword used for?
Answer: B
B is correct. The
B is correct. The
else block executes when the preceding if (and all else if) conditions are false.MCQ 4
What is the output of: System.out.println((10 > 5) ? "Yes" : "No");
Answer: A
A is correct.
A is correct.
10 > 5 is true, so the value before : is chosen: "Yes".MCQ 5
Which data types can be used in a switch statement (pre-Java 14)?
Answer: B
B is correct. switch supports byte, short, int, char, String (Java 7+), and enum types. It does NOT support long, float, double, or boolean.
B is correct. switch supports byte, short, int, char, String (Java 7+), and enum types. It does NOT support long, float, double, or boolean.
MCQ 6
What happens if you omit break in a switch case?
Answer: C
C is correct. Without break, execution continues into the next case (fall-through) regardless of whether that case's value matches. This is often a bug but can be intentional for grouping.
C is correct. Without break, execution continues into the next case (fall-through) regardless of whether that case's value matches. This is often a bug but can be intentional for grouping.
MCQ 7
How should you compare String content in Java?
Answer: B
B is correct.
B is correct.
.equals() compares the actual character content of strings. == compares references (memory addresses) and is unreliable for strings.MCQ 8
In an if-else if-else chain, how many blocks can execute?
Answer: D
D is correct when an else block is present. With else, exactly one block executes: either the first true if/else-if, or the else. Without else, at most one block executes.
D is correct when an else block is present. With else, exactly one block executes: either the first true if/else-if, or the else. Without else, at most one block executes.
MCQ 9
What is the Java ternary operator syntax?
Answer: B
B is correct. Java's ternary syntax is
B is correct. Java's ternary syntax is
condition ? valueIfTrue : valueIfFalse. Option A is Python syntax. The others are not valid Java.MCQ 10
Can you use float or double in a switch statement?
Answer: C
C is correct. switch does not support float or double because floating-point comparison is imprecise. Only byte, short, int, char, String, and enum are allowed.
C is correct. switch does not support float or double because floating-point comparison is imprecise. Only byte, short, int, char, String, and enum are allowed.
MCQ 11
What does the enhanced switch (Java 14+) use instead of break?
Answer: B
B is correct. Enhanced switch uses arrow syntax (
B is correct. Enhanced switch uses arrow syntax (
->) which inherently prevents fall-through. No break is needed. For multi-statement blocks, use yield to return a value.MCQ 12
What is the output of: System.out.println("hello" == "hello");
Answer: A
A is correct. String literals are interned (stored in a shared string pool). Both "hello" references point to the same pool object, so
A is correct. String literals are interned (stored in a shared string pool). Both "hello" references point to the same pool object, so
== returns true. However, this should not be relied upon in production code.MCQ 13
What is short-circuit evaluation in the context of && and ||?
Answer: B
B is correct. With
B is correct. With
&&, if the left operand is false, the right is not evaluated (result is already false). With ||, if the left is true, the right is not evaluated (result is already true). This is important for null checks: s != null && s.length() > 0 is safe because s.length() is not called when s is null.MCQ 14
Which of these is a compile-time error?
Answer: B
B is correct. In Java, the condition must be a boolean.
B is correct. In Java, the condition must be a boolean.
if (1) passes an int, which is a compile-time error. In C/C++, this would be valid (non-zero is truthy), but Java is strict about boolean types.MCQ 15
What keyword is used to return a value from an enhanced switch block?
Answer: C
C is correct. In enhanced switch expressions, when a case body is a block (curly braces), the
C is correct. In enhanced switch expressions, when a case body is a block (curly braces), the
yield keyword returns the value. return would exit the enclosing method, not just the switch.MCQ 16
What is the output of: System.out.println(5 > 3);
Answer: A
A is correct.
A is correct.
5 > 3 evaluates to the boolean value true, which is printed.MCQ 17
What is the difference between & and && in Java?
Answer: B
B is correct.
B is correct.
&& is the short-circuit AND: if the left is false, the right is not evaluated. & always evaluates both operands (no short-circuit). Both can be used as logical operators with booleans, but && is preferred for conditional checks.MCQ 18
What does the default case in switch do?
Answer: B
B is correct. The
B is correct. The
default block executes when none of the case values match the switch expression. It is optional and analogous to the else in an if-else chain.Coding Challenges
Challenge 1: Voting Eligibility
EasyWrite a program that takes a user's age and prints whether they are eligible to vote (age >= 18). If not, print how many years they need to wait.
Sample Input
Enter your age: 15
Sample Output
You cannot vote yet. Wait 3 more years.
Use if-else.
import java.util.Scanner;
public class VotingAge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("You cannot vote yet. Wait " + (18 - age) + " more years.");
}
sc.close();
}
}Challenge 2: Ticket Price Calculator
EasyA cinema charges: Children (under 12): Rs 100, Teens (12-17): Rs 200, Adults (18-59): Rs 300, Seniors (60+): Rs 150. Take age as input and print the ticket price.
Sample Input
Enter age: 14
Sample Output
Ticket price: Rs 200
Use if-else if-else chain.
import java.util.Scanner;
public class TicketPrice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
int price;
if (age < 12) { price = 100; }
else if (age <= 17) { price = 200; }
else if (age <= 59) { price = 300; }
else { price = 150; }
System.out.println("Ticket price: Rs " + price);
sc.close();
}
}Challenge 3: Day of the Week (switch)
MediumRead a number (1-7) from the user and print the corresponding day of the week using a switch statement. Also print whether it is a weekday or weekend. Handle invalid input.
Sample Input
Enter day number (1-7): 6
Sample Output
Saturday
Weekend
Use switch-case. Use fall-through for weekend grouping.
import java.util.Scanner;
public class DayOfWeek {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter day number (1-7): ");
int day = sc.nextInt();
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default: dayName = "Invalid"; break;
}
System.out.println(dayName);
switch (day) {
case 1: case 2: case 3: case 4: case 5:
System.out.println("Weekday"); break;
case 6: case 7:
System.out.println("Weekend"); break;
default:
System.out.println("Invalid day number");
}
sc.close();
}
}Challenge 4: Leap Year Checker
MediumTake a year and determine if it is a leap year. Rules: divisible by 4 AND not by 100, OR divisible by 400. Test with 2024, 1900, 2000.
Sample Input
Enter year: 1900
Sample Output
1900 is NOT a leap year
Use logical operators (&&, ||, !).
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter year: ");
int year = sc.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " is NOT a leap year");
}
sc.close();
}
}Challenge 5: Simple Calculator (switch)
MediumBuild a calculator that takes two numbers and an operation (+, -, *, /) as a char. Use switch to perform the operation. Handle division by zero.
Sample Input
Enter two numbers: 20 0
Enter operation: /
Sample Output
Error: Division by zero!
Use switch-case on char type.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
sc.nextLine();
System.out.print("Enter operation (+, -, *, /): ");
char op = sc.nextLine().charAt(0);
switch (op) {
case '+': System.out.println("Result: " + (a + b)); break;
case '-': System.out.println("Result: " + (a - b)); break;
case '*': System.out.println("Result: " + (a * b)); break;
case '/':
if (b == 0) { System.out.println("Error: Division by zero!"); }
else { System.out.println("Result: " + (a / b)); }
break;
default: System.out.println("Invalid operation!");
}
sc.close();
}
}Challenge 6: Triangle Type Identifier
MediumTake three sides and determine: (1) if they form a valid triangle, (2) if valid, whether it is equilateral, isosceles, or scalene.
Sample Input
Enter three sides: 5 5 8
Sample Output
Valid triangle
Type: Isosceles
Validate with triangle inequality theorem. Use nested if for type.
import java.util.Scanner;
public class TriangleType {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three sides: ");
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
if (a + b > c && b + c > a && a + c > b) {
System.out.println("Valid triangle");
if (a == b && b == c) {
System.out.println("Type: Equilateral");
} else if (a == b || b == c || a == c) {
System.out.println("Type: Isosceles");
} else {
System.out.println("Type: Scalene");
}
} else {
System.out.println("Not a valid triangle");
}
sc.close();
}
}Challenge 7: BMI Calculator with Health Category
HardTake weight (kg) and height (m). Calculate BMI = weight / (height^2). Classify: Underweight (<18.5), Normal (18.5-24.9), Overweight (25-29.9), Obese (30+). Print BMI rounded to 1 decimal.
Sample Input
Enter weight (kg): 70
Enter height (m): 1.75
Sample Output
BMI: 22.9
Category: Normal weight
Validate positive inputs. Use printf for formatting.
import java.util.Scanner;
public class BMICalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter weight (kg): ");
double weight = sc.nextDouble();
System.out.print("Enter height (m): ");
double height = sc.nextDouble();
if (weight <= 0 || height <= 0) {
System.out.println("Invalid input.");
} else {
double bmi = weight / (height * height);
System.out.printf("BMI: %.1f%n", bmi);
if (bmi < 18.5) {
System.out.println("Category: Underweight");
} else if (bmi < 25) {
System.out.println("Category: Normal weight");
} else if (bmi < 30) {
System.out.println("Category: Overweight");
} else {
System.out.println("Category: Obese");
}
}
sc.close();
}
}Challenge 8: Electricity Bill Calculator
HardCalculate electricity bill with tiered pricing: first 100 units at Rs 5/unit, next 100 (101-200) at Rs 7/unit, next 100 (201-300) at Rs 10/unit, above 300 at Rs 15/unit. Add Rs 100 fixed charge.
Sample Input
Enter units consumed: 250
Sample Output
Units: 250
Total bill: Rs 1600
Use if-else if for slab calculation.
import java.util.Scanner;
public class ElecBill {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter units consumed: ");
int units = sc.nextInt();
int bill;
if (units <= 100) {
bill = units * 5;
} else if (units <= 200) {
bill = 100 * 5 + (units - 100) * 7;
} else if (units <= 300) {
bill = 100 * 5 + 100 * 7 + (units - 200) * 10;
} else {
bill = 100 * 5 + 100 * 7 + 100 * 10 + (units - 300) * 15;
}
int total = bill + 100;
System.out.println("Units: " + units);
System.out.println("Total bill: Rs " + total);
sc.close();
}
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Java with a live mentor?
Explore our Java Masterclass