0
0
Javaprogramming~20 mins

Switch vs if comparison in Java - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of switch with fall-through
What is the output of this Java code snippet?
Java
int x = 2;
switch (x) {
  case 1:
    System.out.print("One ");
  case 2:
    System.out.print("Two ");
  case 3:
    System.out.print("Three ");
    break;
  default:
    System.out.print("Default ");
}
ATwo Three
BOne Two Three
CTwo
DDefault
Attempts:
2 left
💡 Hint
Remember that switch cases fall through unless you use break.
Predict Output
intermediate
2:00remaining
If-else equivalent output
What is the output of this if-else code equivalent to the previous switch?
Java
int x = 2;
if (x == 1) {
  System.out.print("One ");
} else if (x == 2) {
  System.out.print("Two ");
} else if (x == 3) {
  System.out.print("Three ");
} else {
  System.out.print("Default ");
}
AOne Two Three
BDefault
CTwo Three
DTwo
Attempts:
2 left
💡 Hint
If-else does not fall through cases.
🧠 Conceptual
advanced
2:00remaining
Switch expression with yield
What is the value of variable result after this Java switch expression runs?
Java
int x = 3;
String result = switch (x) {
  case 1 -> "One";
  case 2 -> "Two";
  case 3 -> {
    yield "Three";
  }
  default -> "Default";
};
System.out.print(result);
AOne
BDefault
CThree
DTwo
Attempts:
2 left
💡 Hint
Switch expressions use yield to return values from blocks.
Predict Output
advanced
2:00remaining
Switch with multiple labels output
What does this code print?
Java
int day = 5;
switch (day) {
  case 1, 2, 3 -> System.out.print("Start");
  case 4, 5, 6 -> System.out.print("Middle");
  case 7 -> System.out.print("End");
  default -> System.out.print("Unknown");
}
AMiddle
BStart
CEnd
DUnknown
Attempts:
2 left
💡 Hint
Multiple labels can be combined with commas in switch cases.
Predict Output
expert
2:00remaining
Switch vs if with null value
What happens when this code runs?
Java
String s = null;
switch (s) {
  case "a" -> System.out.print("A");
  case "b" -> System.out.print("B");
  default -> System.out.print("Default");
}

if (s == null) {
  System.out.print("Null");
} else if (s.equals("a")) {
  System.out.print("A");
} else {
  System.out.print("Other");
}
ADefaultNull
BThrows NullPointerException
CNullA
DNullDefault
Attempts:
2 left
💡 Hint
Switch on null reference causes an exception.