Java Chapter 3 Flashcards

(227 cards)

1
Q

a ChWhat is the boolean expression in an if statement?

A

The expression inside the if statement’s parentheses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the following code print if hourOfDay is 10?

```java
if (hourOfDay < 11) {
System.out.println(“Good Morning”);
}
~~~

A

“Good Morning”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the following code print if hourOfDay is 12?

```java
if (hourOfDay >= 11) {
System.out.println(“Good Afternoon”);
}
~~~

A

“Good Afternoon”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why is checking two separate if statements inefficient?

A

Because the computer checks both conditions even if the first one is already true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of an else statement?

A

It provides an alternative action that only runs if the first condition was false (“otherwise, do this instead”).
Q: How can you rewrite the given code to be more efficient using else?A:

```java
if (hourOfDay < 11) {
System.out.println(“Good Morning”);
} else {
System.out.println(“Good Afternoon”);
}
~~~

Would you like any modifications or additional questions?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is wrong with this code?

```java
if (age >= 13) {…}
else if (age >= 18) {…}
~~~

A

The second condition (age >= 18) will never run because it’s covered by the first condition (age >= 13).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How should you structure conditions to avoid overlapping issues? (In terms of if else)

A

Check the more restrictive condition first:

```java
if (age >= 18) {…}
else if (age >= 13) {…}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the mistake in this code?

```java
if (ready = true) {…}
~~~

A

It assigns true to ready instead of comparing it (should use ==).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the correct way to check if ready is true?

A

hourOfDay is an integer, but if requires a boolean expression (true/false).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can you properly check hourOfDay in an if statement?

A

Use a comparison:

```java
if (hourOfDay == 1) {…}
if (hourOfDay > 0) {…}
// Or use a boolean variable:
if (isMorning) {…}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

if (x = 5) is a valid way to check if x equals 5.

A

False – it assigns 5 to x instead of comparing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

else if conditions are checked only if the previous if was false.

A

True – else if skips checking if an earlier condition was true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Java allows any integer in an if condition (e.g., if (5)).

A

False – Java requires a boolean expression (true/false).
Would you like any adjustments or additional questions?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the disadvantage of the traditional instanceof check in Java? What were you able to do now that you couldnt do before

A

It requires an extra explicit casting step after checking the type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does this old-style code do?

```java
if (num instanceof Integer) {
Integer intNum = (Integer) num;
System.out.println(“It’s integer: “ + intNum);
}
~~~

A

Checks if num is an Integer, then manually casts and assigns it before use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does pattern matching simplify instanceof checks?

A

It combines type-checking and variable assignment in one step.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Rewrite this code using pattern matching:

```java
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s);
}
~~~

A

```java
if (obj instanceof String s) {
System.out.println(s);
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Is this check necessary? Why or why not?

```java
if (obj instanceof String s && s != null) {…}
~~~

A

No! instanceof already returns false for null, so the s != null check is redundant.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does instanceof return if the object is null?

A

false (no NullPointerException is thrown).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Pattern matching in Java allows using the matched variable outside its if block.

A

False – The variable is scoped only to the block where it’s declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

instanceof throws a NullPointerException if the object is null.

A

False – It safely returns false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Pattern matching eliminates the need for explicit casting after instanceof.

A

True – The variable is auto-cast to the matched type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Why does this code fail?

```java
Object obj = “Hello”;
if (obj instanceof String s) {
System.out.println(s);
}
System.out.println(s.length()); // Error?
~~~

A

s is out of scope outside the if block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the output of this code?

```java
Object obj = null;
if (obj instanceof String s) {
System.out.println(s);
} else {
System.out.println(“Not a String or null”);
}
~~~

A

“Not a String or null” (because instanceof returns false for null).
Would you like more examples or refinements?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Why does this code fail to compile? ```java String s = "hello"; if (obj instanceof String s) { System.out.println(s); } ```
Because s is already defined in the outer scope, and pattern variables cannot shadow existing variables.
26
How can you fix this variable name conflict? ```java String s = “hello”; if (obj instanceof String s) { System.out.println(s); } ~~~
Use a different variable name for the pattern match: ```java String s = "hello"; if (obj instanceof String str) { // OK System.out.println(str); } ```
27
What's wrong with this code? ```java if (number instanceof Integer data) { data = 10; System.out.println(data); } ```
It's confusing because: data was meant to represent the matched Integer from number Reassigning it breaks the expected behavior Makes the code harder to understand/maintain
28
Why is reassigning pattern variables considered bad practice?
Because it violates the principle that pattern variables should represent the matched object, not be reused as general variables.
29
How can you prevent accidental modification of pattern variables?
Declare them as final: ```java if (number instanceof final Integer data) { data = 10; // COMPILE ERROR - good! } ```
30
What benefit does final provide in pattern matching?
It enforces immutability, making the code's intent clearer and preventing bugs from accidental reassignment.
31
Pattern variables can reuse names from existing variables in the same scope. It would mean this is ok : Object obj = "you are cool"; if (obj instanceof String obj){}
False - They must have unique names to avoid shadowing conflicts.
32
Reassigning pattern variables is a recommended practice for flexibility.
False - It's considered confusing and should be avoided.
33
The final keyword can be used with pattern variables to prevent modification.
True - This is a best practice for pattern matching.
34
What's wrong with this code? How would you fix it? ```java Integer x = 5; if (x instanceof Integer x) { x = x + 1; } ```
Problem: Variable name conflict and unsafe reassignment.Fixed version: ```java Integer x = 5; if (x instanceof final Integer matchedX) { int result = matchedX + 1; } ```
35
Which of these pattern matches will compile for Number bearHeight = Integer.valueOf(123)? ```java a) if (bearHeight instanceof Integer i) {} b) if (bearHeight instanceof Number n) {} c) if (bearHeight instanceof Object o) {} d) if (bearHeight instanceof String s) {} ```
a, b, and c will compile. d fails because String is incompatible with Number/Integer.
36
Why does bearHeight instanceof String s fail to compile? Number bearHeight = 12; if (bearHeight instanceof String s)
Because bearHeight is a Number (specifically an Integer), which is in a completely different type hierarchy than String.
37
Show the valid type progression for pattern matching from most to least specific: ```java Integer → ? → ? → Object ```
Integer → Number → Object (all valid in pattern matching)
38
Which supertype relationships make pattern matching work? This is talking about Integer
Pattern matching works when: Testing the exact type (Integer) Testing a direct supertype (Number) Testing any ancestor type (Object)
39
What determines whether a pattern match will compile? in terms of type
The compiler checks if the tested type is in the same type hierarchy as the variable's declared type.
40
Why is this invalid even though Integer extends Number? ```java String s = "hello"; if (s instanceof Number n) {} ```
Because String and Number are in completely unrelated inheritance hierarchies.
41
instanceof pattern matching works with any type in the same inheritance chain.
True - Both supertypes and exact types work.
42
You can pattern match against unrelated interfaces.
False - The types must be in the same inheritance hierarchy.
43
Object is always a valid pattern match type.
True - Since everything extends Object.
44
Which of these will fail to compile and why? ```java Double price = 19.99; 1. if (price instanceof Double d) {} 2. if (price instanceof Number n) {} 3. if (price instanceof String s) {} 4. if (price instanceof Object o) {} ```
#3 will fail because Double and String are unrelated types.
45
Could this ever compile? Why/why not? ```java Object obj = "Hello"; if (obj instanceof Integer i) {} ```
It compiles (because obj is Object), but will always evaluate to false at runtime since a String can't be an Integer.
46
What is flow scoping in Java pattern matching?
A special scope rule where pattern variables only exist where Java can guarantee their type matches.
47
Why does this code fail to compile? ```java if (number instanceof Integer data || data.compareTo(5) > 0) { System.out.print(data); } ```
Because with ||, data might be used when it doesn't exist (if the first condition fails).
48
Why does && work with pattern variables but || doesn't?
Either: Use && instead of || if logically possible Split into nested if statements (what essentially happens in the dumbed down sense is that the compiler would prefer the && operator because it would mean that both have to be true because if one side is false then the next part wont execute, when compared to the || operator it can still check both sides even if the left side was false)
49
Why is this pattern matching example safe? ```java if (num instanceof Integer i && i > 100) {...} ```
i only exists when the first condition passes due to && short-circuiting.
50
What's the output here if obj is null? ```java if (obj instanceof String s && s.length() > 5) { System.out.println(s); } ```
No output (entire condition fails safely without NPE).
51
Does this compile? Why/why not? ```java if (x instanceof ArrayList list || list.isEmpty()) {...} ```
❌ Compile error - list isn't guaranteed to exist for the right-side check.
52
How would you rewrite this using proper flow scoping? ```java if (!(x instanceof String s) || s.isEmpty()) {...} ```
Better as: ```java if (x instanceof String s) { if (s.isEmpty()) {...} } // or if (!(x instanceof String s)) return; if (s.isEmpty()) {...} ```
53
What's wrong with this logical flow? ```java if (obj instanceof Number n || n.intValue() > 0) {...} ```
Dangerous! The right-side n.intValue() could execute when n doesn't exist.
54
True/False: Pattern variables behave exactly like regular local variables. (What patterns do each match)
❌ False - They have flow-scoped visibility, not block-scoped.
55
What are two ways to safely handle OR conditions with pattern variables?
Use Nested If statements or use early return gaurd clases
56
What changed in Java 21 regarding pattern matching with instanceof? (In terms of types)
You can now match the same type (e.g., Number n for a Number variable), not just strict subtypes.
57
Would this compile in Java 21? ```java Number num = 5; if (num instanceof Number n) {...} ```
✅ Yes - Java 21+ allows matching the declared type (Number).
58
(in terms of pattern matching) Why was it previously restricted in older Java versions?
Originally, pattern matching required the tested type to be a strict subtype for practical utility.
59
What is flow scoping?
Flow scoping is the compilers way of ensuring values that are being pattern matched exist and can be pattern matched
60
Why does this fail? ```java if (number instanceof Integer data) System.out.print(data); System.out.print(data); // Error ```
❌ The second data usage is outside the if block - Java can't ensure data exists there.
61
Why does this work despite no explicit if block? ```java if (!(number instanceof Integer data)) return; System.out.print(data); // Compiles! ```
Because the method returns early if number isn't an Integer, so data is guaranteed to exist afterward.
62
(in terms of how java works with lexical logic and flow scoping) What principle does this demonstrate? like: Object s = "hello"; if (!(s instanceof String str)) return; System.out.println(str);
Java tracks control flow to determine variable existence, not just lexical scope.
63
Contrast these two approaches: ```java // A if (obj instanceof String s) { System.out.print(s); } // B if (!(obj instanceof String s)) { return; } System.out.print(s); ```
Both work, but: A limits s to the if block B makes s available for the entire remainder of the method
64
When should you prefer using the early-return (fail-fast) pattern with pattern variables in java 21
When you need the pattern variable to be abailable in multple statements and you want to fail early if the pattern doesnt match
65
In Java 21, Object o = ""; if (o instanceof Object oo) {...} compiles.
✅ True - Same-type matching is now allowed.
66
Flow scoping applies to regular local variables too.
❌ False - Only for pattern variables.
67
This is valid flow scoping: ```java if (x instanceof String s || s.isEmpty()) {...} ```
❌ False - || doesn't guarantee s exists.
68
Fix this code: ```java void process(Object obj) { if (obj instanceof Number n) System.out.print(n); n.floatValue(); // Error } ```
Solutions: Move n.floatValue() inside the if Or use early return: ```java if (!(obj instanceof Number n)) return; n.floatValue(); ```
69
List three rules for flow scoping:
1. Pattern variables only exist if the condition that defines them is true. → Example: if (x instanceof String s) → s only exists if the condition passes. 2. Pattern variables are only usable in the code paths where Java can guarantee they were initialized. → Java uses control flow, not just where you write the variable, to decide if it’s valid. 3. Pattern variables cannot be used in the right side of an OR (||) condition. → Because the left side might be false, and the variable might not exist yet. ⸻ Bonus Rule (optional to remember for the exam): ❗ Pattern variables can shadow outer variables, but only if the names don’t conflict in the same scope
70
How is this early-return version: ```java if (!(number instanceof Integer data)) return; System.out.print(data); ``` equivalent to an if-else structure?
It behaves identically to: ```java if (number instanceof Integer data) { System.out.print(data); } else { return; } ``` Key Insight: Both guarantee data only exists when the type matches.
71
How does flow scoping differ from regular block scoping?
The throw ensures subsequent code only runs if s exists → safe by flow scoping.
72
What's special about this switch expression? (In terms of case labels what were you able to do now) ```java String result = switch (input) { case 1 -> "Dog"; case 2, 3 -> "Alligator"; // Multi-case default -> "Cat"; }; ```
Older versions required constants in case labels (fixed with JEP 441).
73
Flow scoping applies to all local variables, not just pattern matches.
❌ False - Only pattern variables.
74
This is valid flow scoping: ```java if (x == null || !(x instanceof String s)) return; s.isEmpty(); // Safe? ```
❌ False - || breaks flow scoping guarantees.
75
Switch expressions can return values directly.
✅ True - No temporary variable needed.
76
Fix this flow scoping error: ```java if (obj instanceof Double d) { System.out.println(d); } d.compareTo(1.0); // Error ```
Solutions: Move operation inside if block Use early return: ```java if (!(obj instanceof Double d)) return; d.compareTo(1.0); ```
77
List three flow scoping principles:
Type test binding - if (obj instanceof String s) allows both check and cast. Scope restriction - the bound variable is only accesible inside the block where the type test is true definite assignment control - compilerensures the variable is initialized and only usable where its gauranteed to be safe
78
When can you omit default in a switch expression?
When all possible cases are covered: With enums (all values listed) With sealed classes (all permitted types handled) When every case returns/throws
79
Why does this enum switch compile without default? ```java enum Color { RED, GREEN, BLUE } switch (c) { case RED -> "R"; case GREEN -> "G"; case BLUE -> "B"; } ```
The compiler knows all Color values are covered → no default needed.
80
What makes this switch exhaustive? ```java sealed class Shape permits Circle, Square {} switch (s) { case Circle c -> "○"; case Square q -> "□"; } ```
All permitted subtypes (Circle, Square) are handled → no default.
81
If a sealed class shape permits only Circle and Square and a switch expression handles both, would adding a new subclass Triangle cause a compile error ?
Yes unless its handled. True the compiler enforces exhaustiveness for sealed class hierarcheis sealed interface Shape permits Circle, Square {} final class Circle implements Shape {} final class Square implements Shape {} static String handleShape(Shape shape) { return switch(shape) { case Circle c -> "Its a circle"; case Square s -> "its a square"; }}
82
Why might you still add default even when it's technically unnecessary?
For future-proofing (e.g., if enum/sealed class gets new values later).
83
This switch compiles without default. Why? ```java switch (s) { case "One" -> 1; case "Two" -> 2; case "Three" -> 3; } ```
All paths return a value → technically exhaustive.⚠️ But risky! Unhandled strings will throw IncompatibleClassChangeError.
84
Why does this fail? ```java int y = 2; switch (x) { case y -> "Two"; // Error } ```
case labels must be compile-time constants (non-final variables aren't constants).
85
Fix this code to use valid case labels: ```java int y = 2; String s = "Hi"; switch (x) { case y -> "Two"; case s -> "Hi"; } ```
use literals final String y = "2"; String x = "Two"; final String s = "Hi"; switch (x) { case "Two" -> System.out.println("asdf"); case "Hi" -> System.out.println("yoyoyo"); default -> System.out.println("idontknow"); } Constants final int y = 2; switch (x) { case y -> System.out.println("asdf"); }
86
case labels can use any final variable.
✅ True - As long as it's a compile-time constant.
87
Sealed classes enforce exhaustive pattern matching at compile-time.
✅ True - The compiler checks all permitted subtypes.
88
What's wrong here? ```java enum Direction { UP, DOWN } String command = switch (d) { case UP -> "Forward"; }; ```
Non-exhaustive switch (missing case DOWN or default).
89
Fix this invalid case label: ```java int threshold = 10; switch (score) { case threshold -> "Pass"; // Error } ```
Make threshold constant: ```java final int threshold = 10; // or use literal: case 10 -> "Pass"; ```
90
List three scenarios where default is unnecessary:
Either: A literal (1, "Hi") A final constant variable exhaustive enum switching sealed classes
91
What are the two switch syntax styles in Java?
Traditional switch statement switch (variable) { case 1: System.out.println("one"); break; case 2: System.out.println("o2"); break; case 3: System.out.println("onffe"); break } enhanved switch expression switch(variable) { case 1 -> System.out.println("one"); case 2 -> System.out.println("2"); default -> System.out.println("oneff"); }
92
What's required in every case with traditional syntax?
break (or return/throw) to prevent fall-through.
93
Convert this to traditional syntax: ```java case "Java" -> System.out.println("Modern"); ```
case "java": System.out.println("modern"); break;
94
True/False: Arrow syntax allows multiple statements per case.
✅ True (use braces {} for multi-line blocks).
95
Which Java version introduced pattern matching for switch?
Java 21 (finalized).
96
Fix this illegal mix: ```java switch (obj) { case String s: break; // Traditional case Integer i -> {} // Arrow } ```
Pick one style: ```java // All traditional case String s: break; case Integer i: break; // OR all arrow case String s -> {} case Integer i -> {} ```
97
What does when do in this case? ```java case String s when s.length() > 5 -> "Long"; ```
Adds a guard condition (extra boolean check).
98
How does switch handle null in Java 21+?
You can explicitly match it: ```java case null -> "Null!"; ```
99
When should you prefer arrow syntax?
For all new code (cleaner, safer).
100
Why might legacy code still use traditional syntax?
Backward compatibility with pre-Java 14 versions.
101
What's wrong here? ```java switch (x) { case 1: System.out.println("One"); case 2 -> System.out.println("Two"); } ```
Illegal mix of : and ->.
102
Convert this to arrow syntax: ```java case 'A': System.out.println("Alpha"); break; ```
case 'A' -> System.out.println("Alpha");
103
What's wrong with this traditional switch? ```java case "Sancha": System.out.print(1); case "Panccha": System.out.print(2); ```
Fall-through bug! If input is "Sancha", it prints both 1 and 2.
104
how do you fix a switch case that is missing a break statement or has invalid fallthrough logic in java 21
you can fix it in two ways: add a break statement to prevent fallthrough ```java case "Sancha": System.out.println("hello"); break; ``` or use the arrow syntax ```java case "Sancha" -> System.out.print(1); ```
105
Why does this fail? ```java case "A" -> 1; case "B": 2; // Error ```
Illegal mix of arrow (->) and colon (:) syntax in the same switch.
106
Correct versions: ```java // All arrow case "A" -> 1; case "B" -> 2; // OR all traditional case "A": 1; break; case "B": 2; break; ``` What risk does this switch have? ```java switch (x) { case 1 -> "One"; } ```
Silent failure if x isn't 1 (throws IncompatibleClassChangeError at runtime).
107
When can you safely omit default?
When all cases are covered (enums/sealed classes) or all paths return/throw.
108
Spot 5 errors in this code: ```java static String getGrade(Number score) { return switch (score) { case Integer s when s >= 90 → "A"; case Integer s when s >= 8 0 → > "B"; // 1. Space in 80, 2. Stray > case Integer s when s >= 70 > "C"; // 3. Missing → case Integer s when s >= 60 → > "D"; // 4. Stray > default → > "F"; // 5. Stray > }; } ```
Corrected version: ```java return switch (score) { case Integer s when s >= 90 -> "A"; case Integer s when s >= 80 -> "B"; case Integer s when s >= 70 -> "C"; case Integer s when s >= 60 -> "D"; default -> "F"; }; ```
109
Convert this traditional switch to arrow syntax: ```java switch (type) { case 0: System.out.print("Lion"); break; case 1: System.out.print("Elephant"); break; default: System.out.print("Unknown"); } ```
Arrow version: ```java switch (type) { case 0 -> System.out.print("Lion"); case 1 -> System.out.print("Elephant"); default -> System.out.print("Unknown"); } ```
110
Arrow syntax requires break statements.
❌ False - Arrow syntax never falls through.
111
default is optional for exhaustive enum switches.
✅ True (but recommended for maintenance).
112
Pattern variables in switch follow block scoping.
❌ False - They use flow scoping.
113
Fix this code: ```java switch (x) { case 1: System.out.print("One"); case 2 -> System.out.print("Two"); } ```
Pick one style: ```java // All traditional case 1: System.out.print("One"); break; case 2: System.out.print("Two"); break; // OR all arrow case 1 -> System.out.print("One"); case 2 -> System.out.print("Two"); ```
114
List three common switch mistakes:
Missiing break in traditional syntax, mixing arrow and colon, not handling all possible cases in witch expressions
115
What distinguishes a switch expression from a switch statement?
Arrow syntax (->) for both expressions and statements.
116
Correct this switch expression: ```java String result = switch(x) { case 1 -> "One" default -> "Other" } ```
corrected version ```java String result = switch(x) { case 1 -> "One"; // Missing semicolon default -> "Other"; }; // Missing semicolon ```
117
Why does this fail? ```java int y = switch(x) { case 1 -> 10; }; ```
Missing default for non-exhaustive cases.
118
True/False: default can appear anywhere in the switch.
✅ True (but convention places it last).
119
What's wrong here? ```java String s = switch(x) { case 1 -> "One" default -> "Two" } ```
Missing semicolons after cases and after the switch block.
120
Why avoid fall-through in modern Java?
Arrow syntax eliminates accidental fall-through bugs.
121
How does Java 21 improve pattern matching in switches?
Allows: case null -> handling Guarded patterns (when clauses) Exhaustiveness checks for sealed classes
122
What makes this switch exhaustive? ```java sealed class Animal permits Dog, Cat {} switch(a) { case Dog d -> "Woof"; case Cat c -> "Meow"; } ```
All permitted subtypes (Dog, Cat) are covered.
123
List three advantages of switch expressions:
more concise syntax with arrow notation, no accidental fall through, can return aa value directly
124
Fix this mixed-syntax error: ```java switch(x) { case 1: System.out.println("One"); break; case 2 -> System.out.println("Two"); } ```
Stick to one style: ```java // All arrow case 1 -> System.out.println("One"); case 2 -> System.out.println("Two"); // OR all traditional case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; ``` This set covers:✅ Expression vs. statement differences✅ Syntax requirements✅ Exhaustiveness rules✅ Modern best practices Need more examples with yield or complex patterns?
125
Which of these work in switch? ```java a) int b) Long c) String d) boolean e) enum f) float ```
✅ a, c, e❌ b (use long), d, f
126
Why can't you switch on a boolean?
It's redundant - just use if (condition) instead.
127
When are braces {} required in case blocks?
For multi-line blocks (optional for single statements).
128
Convert this to use braces properly: ```java case 1: log("Processing"); process(); break; ```
case 1 -> { log ("processing"); process(); };
129
What are the key differences between a traditional switch statement and a switch expression
```java // Traditional switch (weather) { case 1: System.out.print("Sunny"); break; } ``` ```java // Expression String desc = switch (weather) { case 1 -> "Sunny"; }; ```
130
Fix this error: ```java String s = switch (x) { case 1 -> "One"; case 2 -> { "Two"; } }; ```
```java String s = switch (x) { case 1 -> "One"; case 2 -> { yield "Two"; } // Missing yield }; ```
131
What's the workaround for switching on double?
Use if-else chains with tolerance checks: ```java if (Math.abs(x - 1.0) < 0.001) {...} ```
132
Convert this to a switch expression: ```java String season; switch (month) { case 12, 1, 2: season = "Winter"; break; default: season = "Unknown"; } ```
String season = switch(month) { case 12, 1, 2 -> "Winter"; default -> "Unknwon"; };
133
What's the difference between: ```java case 1 -> "One"; ``` and ```java case 1: yield "One"; break; ```
First is expression syntax, second is statement syntax with yield. This set covers:✅ Allowed types✅ Brace rules✅ yield usage✅ Type limitations✅ Practical conversions Need more examples with var or sealed classes?
134
What types of case values are allowed?
byte, short, char, int including the wrapper class String Enum types and sealed types and null
135
Why do these fail? ```java int y = 2; final int z = getValue(); switch (x) { case y: case z: } ```
Method calls (getTemperature()) can't be evaluated at compile time.
136
Which of these compile? ```java final int A = 1; int B = 2; final int C = getCount(); switch (input) { case
// 1 case B: // 2 case C: // 3 case 4: // 4 } ``` A: ✅ 1, 4❌ 2 (non-final), 3 (method-dependent)
137
Fix this code: ```java int threshold = 90; switch (score) { case threshold -> "Pass"; } ```
Make threshold a compile-time constant: ```java final int threshold = 90; // OR use literal: case 90 -> "Pass"; ```
138
Why can't enums use dynamic values? ```java enum Level { LOW, HIGH } Level l = Level.HIGH; switch (l) { case Level.LOW: break; case l: } ```
case must use enum constants directly, not variables.
139
Does this work? Why? ```java final int x; x = 10; switch (y) { case x: } ```
❌ No - final variables must be initialized at declaration to be compile-time constants.
140
What about String literals? ```java final String name = "Alice"; switch (input) { case name: // Valid? } ```
✅ Yes - Strings can be constants if final + literal.
141
List three rules for valid case labels:
Must be compile-time constant, must match the type of the switch selector, must be unique no dups
142
143
In Java, if a switch case has no break and matches the input, what happens to all subsequent cases (including default) until a break is encountered?
All subsequent cases will execute (fall-through), including default, until a break or the end of the switch block is reached.
144
If a default case is placed before other cases and there’s no break, can later cases still execute?
Yes, if the default case is triggered and lacks a break, execution will fall through to cases below it.
145
What is the output of this code? ```java int x = 1; switch (x) { case 1: case 2: System.out.print("A"); case 3: System.out.print("B"); break; default: System.out.print("C"); } ```
AB (Case 1 falls through to case 2, printing "A", then falls to case 3, printing "B" before breaking.)
146
What does this code print if x = 4? ```java int x = 4; switch (x) { case 1: System.out.print("X"); default: System.out.print("Y"); case 2: System.out.print("Z"); } ```
YZ (No matching case → default runs, then falls through to case 2.)
147
If a switch has no default and no cases match, what happens?
The entire switch block is skipped, and no code inside executes.
148
Can variables be declared inside a case without braces? What’s the risk?
Yes, but without braces ({}), fall-through into the same scope can cause "duplicate variable" errors. Example: ```java switch (x) { case 1: int y = 5; break; // OK case 2: y = 10; // Error if fall-through from case 1 } ```
149
Why is omitting break in the last case technically safe but still discouraged?
While the switch ends anyway, adding a break prevents bugs if new cases are added later.
150
How can you intentionally use fall-through to group multiple cases?
Stack cases without break to share logic: ```java switch (day) { case 1: case 2: case 3: System.out.print("Weekday"); break; case 6: case 7: System.out.print("Weekend"); } ```
151
A developer writes a switch where default runs unexpectedly even when a case matches. What’s the likely cause?
A missing break in a prior case causes fall-through into default.
152
What’s wrong with this switch? ```java switch (x) { case 1: System.out.print("A"); case 2: System.out.print("B"); break; int y = 10; // Compile error } ```
Statements (like int y = 10;) can’t appear between cases without a label (e.g., case 3:). For self-testing, cover the answers and quiz yourself. For study groups, take turns asking/explaining the logic. For flashcards, put the question on one side and the answer on the back. These questions force deep understanding of fall-through, scope, and edge cases—key for exams or technical interviews. Want even harder questions? Try adding nested switches or enums!
153
In this switch expression, why do Integer, short, and int work, but String, long, and null cause errors? ```java int size = switch (measurement) { case 5 -> Integer.valueOf(1); case 10 -> (short)2; default -> 3; case 20 -> "4"; case 40 -> 5L; case 50 -> null; }; ```
In this switch expression, why do Integer, short, and int work, but String, long, and null cause errors? ```java int size = switch (measurement) { case 5 -> Integer.valueOf(1); // OK (unboxes to int) case 10 -> (short)2; // OK (widens to int) default -> 3; // OK (int literal) case 20 -> "4"; // ERROR (String) case 40 -> 5L; // ERROR (long) case 50 -> null; // ERROR (null) }; ``` Runtime NullPointerException (unboxing fails). Example: ```java int size = switch (x) { case 1 -> Integer.valueOf(10); // OK (unboxes) case 2 -> null; // 💥 NPE at runtime }; ```
154
Can a switch expression return a subtype of the target type (e.g., Number for an int assignment)?
No. The type must exactly match (or be convertible via unboxing/widening). Example: ```java int size = switch (x) { case 1 -> (Number) 10; // ❌ Compile error (Number ≠ int) default -> 0; }; ``` Flashcard Side 1: Show the code snippet with errors. Flashcard Side 2: Explain why each case passes/fails. For Exams: Focus on: Type compatibility (unboxing/widening). Exhaustiveness rules for enum. Runtime vs. compile-time failures. Want harder questions? Try mixing generics with switch or pattern matching (Java 17+).
155
Why is default -> "Warm" better than explicitly handling FALL in this Season enum switch? ```java return switch (value) { case WINTER -> "Cold"; case SPRING -> "Rainy"; case SUMMER -> "Hot"; default -> "Warm"; }; ```
Why is default -> "Warm" better than explicitly handling FALL in this Season enum switch? ```java return switch (value) { case WINTER -> "Cold"; case SPRING -> "Rainy"; case SUMMER -> "Hot"; default -> "Warm"; // Catches FALL and any future additions }; ``` Using default is better because it: * Catches any values not explicitly handled — like FALL. * Future-proofs your code — if new constants are added to the Season enum (e.g., MONSOON), the switch won’t break or miss them. * Keeps the code shorter and simpler, without listing every possible case. So, default -> "Warm" ensures the switch expression is exhaustive and maintainable, especially in evolving codebases.
156
does the compiler force all blocks to end with yield (or throw an exception)? Fix: ```java case 1 -> { System.out.println("One"); "One"; } ```
In Java’s switch expressions (not statements), every case must return a value. If you use block syntax { ... } instead of the arrow ->, you must explicitly yield a value:case 1 -> { System.out.println("One"); yield "One"; // ✅ Required for switch expression }If you forget yield, the compiler throws an error because the expression would be missing a result. This rule ensures the switch expression always evaluates to a value, just like a regular expression (e.g., int x = 5 + 3;).
157
Can yield be used in a traditional switch statement (not an expression)?
No. yield is only for switch expressions (introduced in Java 14+). Example: ```java // ❌ Traditional switch (statement): switch (x) { case 1: System.out.println("One"); yield 1; // ERROR: Not an expression } ```
158
What if a block throws an exception instead of yielding?
Allowed (no yield needed if block throws): ```java case 1 -> { throw new RuntimeException("Error"); // ✅ Compiles } ```
159
Why does case 2 -> 2; cause an error in this switch? ```java switch (x) { case 1 -> "One"; case 2 -> 2; } ```
Switch expressions must return a consistent type (here, String). 2 is an int, which can't be implicitly converted to String. Fix: ```java case 2 -> "Two"; // Now returns String // OR force type consistency: String result = switch (x) { ... }; // All cases must return String. ```
160
What are the key differences between simple cases (->) and block cases (-> { })? Example: ```java case 1 -> "Goldfish"; // Simple case 2 -> { // Block String type = "Trout"; yield type + " (large)"; } // No semicolon here ``` How does yield work with conditionals inside a block? ```java case 3 -> { if (length > 10) { yield "Bloofish"; // ✅ } else { yield "Green"; // ✅ } // yield MUST cover all paths! } ```
Every execution path in the block must end with a yield (or throw an exception). The compiler enforces this. 💡 Pitfall: ```java case 3 -> { if (length > 10) { yield "Bloofish"; } // ❌ Missing else → compile error! } ```
161
Can a block end with an exception instead of yield? ```java case 4 -> { throw new IllegalArgumentException(); // ✅ Valid } ```
Yes! If a block always throws, no yield is needed. Edge Case: ```java case 4 -> { if (invalid) throw new Exception(); // ❌ Not all paths throw/yield yield "Valid"; // Required for else path } ```
162
Can yield be used in nested switches? ```java case 5 -> { int nested = switch (y) { case 1 -> 10; case 2 -> { yield 20; } }; yield "Nested: " + nested; } ```
Yes! Each switch expression manages its own yield scope.
163
When is a semicolon required after a switch case?
Only after expression cases (-> value;), not blocks (-> { ... }).
164
What happens if a block case misses a yield?
Compile error (all paths must yield or throw).
165
How does pattern matching improve switches? (what can it do with types)
Allows type-based branching with exhaustiveness checks.
166
When should you use default in pattern matching?
When not all possible types are covered by cases.
167
What’s wrong here? ```java case x -> { if (x > 0) yield "Positive"; } ```
Missing else yield for negative values. This structure ensures conceptual clarity while highlighting practical usage and common pitfalls. Ready for deeper dives into specific areas?
168
Why must case Integer i come before case Number n in Java pattern matching?
Because Integer is a subtype of Number. In pattern matching, more specific cases must come before more general ones. If case Number n appears first, it will match all numbers (including Integers), so case Integer i will never be reached (unreachable code). Object obj = 42; switch (obj) { case Number n -> System.out.println("Matched Number: " + n); case Integer i -> System.out.println("Matched Integer: " + i); // ❌ Unreachable } 🧨 This causes a compile-time error: “Label is dominated by a preceding case label.” Object obj = 42; switch (obj) { case Integer i -> System.out.println("Matched Integer: " + i); case Number n -> System.out.println("Matched Number: " + n); } 🟢 This compiles and works as expected, because it goes from specific to general.
169
How to handle null in pattern matching switches?
Add an explicit case null -> ....
170
When is default optional in pattern matching?
With sealed hierarchies (all subtypes covered).
171
What’s wrong here? ```java case Integer i -> ...; case Integer i when i > 10 -> ...; ```
General case dominates guarded case—reverse the order.
172
Why use sealed interfaces with switches?
Compiler enforces exhaustiveness, making code future-proof. This approach ensures deep understanding while avoiding common pitfalls. Ready to tackle nested patterns or record deconstruction?
173
Where should null be placed in a pattern-matching switch?
First (if explicitly handled).
174
Why does case Number block case Integer?
Number is a supertype—order must be specific → general.
175
What’s wrong here? ```java switch (obj) { default -> "Other"; case String s -> "String"; } ```
default is too early and dominates String. Move it last.
176
When can you omit default?
With sealed types where all subtypes are covered.
177
Which case is unreachable? ```java case Object o -> ...; case String s -> ...; ```
String (because Object matches everything). Think of pattern-matching switches like if-else ladders: Order matters for correctness. Compiler warnings are your friend—they catch dominance issues. Test edge cases: null, subtypes, and guards. Ready to master nested patterns or deconstruct records?
178
Why does switch on Number fail with just Integer?
Number has other subtypes (e.g., Double), making the switch non-exhaustive.
179
What’s the simplest fix?
Narrow the variable to Integer if possible.
180
How to handle all Number subtypes concisely?
Use default.
181
What’s missing here? ```java switch (obj) { case String s -> ... } ```
null handling (case null).
182
When to list all subtypes explicitly?
When each subtype needs unique logic. For sealed hierarchies (e.g., sealed interface Number permits Integer, Double), the compiler ensures exhaustiveness without default. Use this for domain models! Example: ```java sealed interface Pet permits Dog, Cat {} record Dog() implements Pet {} record Cat() implements Pet {} switch (pet) { // ✅ Exhaustive (no default needed) case Dog d -> "Woof"; case Cat c -> "Meow"; } ``` This gives you compile-time safety while keeping code clean. Want to dive deeper into sealed classes or null-handling strategies?
183
Why does a switch on null throw NPE without case null?
Traditional switch internally calls hashCode()/equals(), which fail on null.
184
How to fix NPE in a switch with strings?
Add case null (Java 17+) or pre-check with if (older Java).
185
Where should case null be placed? (not in terms of pattern matching)
Conventionally before default but after specific cases.
186
Does default catch null?
❌ No! null needs its own case in pattern-matching switches.
187
What’s the output here? ```java switch ((String) null) { case null -> "A"; default -> "B"; } ```
"A" (explicit null case matches first). Java 17+: Use case null for safe null handling. Legacy Java: Pre-check with if (x == null). Order Matters: null case → default for clarity. This ensures null-safe switches without surprises. Want to explore how this works with enums or sealed classes?
188
Which loop always executes at least once?
do-while.
189
What’s missing here? ```java while (x < 5) { ... } ```
No x++ (risk of infinite loop).
190
How to exit nested loops early?
Use labeled break (e.g., break outer;).
191
Why add a safety counter in while loops?
Prevents infinite loops if the condition never becomes false.
192
What’s the output? ```java for (int i = 0; i < 0; i++) { System.out.print(i); } ```
Nothing (0 iterations, condition fails immediately). for: Predictable iterations (e.g., arrays). while: Condition-first, unknown iterations. do-while: Execute-then-check (e.g., menus). Always plan exit conditions to avoid infinite loops! Ready to tackle loop optimizations or iterator patterns?
193
Why does for (int x=0, String y="a"; ...) fail?
Mixed types in declaration (int vs String).
194
How to safely remove items during iteration?
Use Iterator.remove() or a traditional for loop.
195
What’s wrong here? ```java int x = 0; for (int x = 1; x < 2; x++) {...} ```
Variable shadowing (inner x conflicts with outer x).
196
How to get the index in an enhanced for loop?
You can’t—use a standard for loop instead.
197
Which loop allows comma-separated updates?
Traditional for loop (e.g., for (; i++, j--)). Multi-variable for: Same-type declarations only. Enhanced for: Read-only, no index/modification. Scope: Avoid shadowing variables in nested loops. Empty loops: Use for (;;) sparingly (prefer while (true)). Need advanced scenarios? Try nested loops with labeled breaks or stream-based iteration.
198
Why can’t you use for (int x : List.of("a"))?
Type mismatch (String vs int).
199
How to safely remove items during iteration?
Use Iterator.remove() or iterate over a copy.
200
How to loop through a Map?
Use map.entrySet(), keySet(), or values(). Need more depth on Iterable implementation or parallel iteration?
201
What’s the correct syntax for a loop label?
LABEL_NAME: for (...) { ... } (ends with colon).
202
How to exit a nested loop from an inner loop?
Use break LABEL_NAME on the outer loop’s label.
203
Why avoid labeling if statements?
Labels are for loop control; non-loop use is confusing and unconventional.
204
What does continue OUTER_LOOP do?
Skips to the next iteration of the outer loop (not just the inner one).
205
Is while (true) { break LABEL; } valid if LABEL isn’t defined?
❌ No—labels must reference an enclosing loop/block. Limit Nesting: If you need labels, consider refactoring to reduce loop depth. Document: Add comments explaining why a label is needed. Alternatives: Sometimes methods or flags can replace complex labeled loops. Example Refactor: ```java // Before (labeled loops) OUTER: for (...) { for (...) { if (...) break OUTER; } } // After (extracted method) void processMatrix() { for (...) { if (shouldStop(...)) return; // Cleaner exit } } ``` Use labels sparingly (only for nested loops). Follow conventions (UPPER_SNAKE_CASE + colons). Avoid non-loop labels—they’re legal but harmful to readability. Ready for advanced topics like labeled blocks in switch expressions (Java 17+)?
206
Q: What will this code output, and what changes if break PARENT_LOOP; is replaced with just break;? PARENT_LOOP: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if ((i + j) == 2) { System.out.println("(" + i + ", " + j + ")"); break PARENT_LOOP; } } }
✅ Output: (0, 2) — because break PARENT_LOOP; exits both loops immediately after the first match. 🛑 If you replace it with just break;, only the inner loop exits. The program keeps looping and eventually prints: (2, 0), the last match found.
207
How to exit a 3-level nested loop immediately?
Use a labeled break on the outermost loop.
208
Why avoid labels in shallow loops?
Overkill—unlabeled break is clearer for simple cases.
209
What’s a cleaner alternative to labeled breaks?
Extract nested loops into a separate method and use return.
210
Which is faster: labeled or unlabeled break?
Labeled (exits earlier if the goal is first-match-only). Labeled break: Nuclear option for deep exits. Unlabeled break: Surgical exit from current loop. Prefer methods over labels when possible. Need to handle edge cases like continue with labels? Ask away!
211
Why does if (false) { ... } fail compilation?
The compiler statically detects unreachable code.
212
When should you prefer return over labeled break?
For reusable logic or clear "find" operations.
213
What’s wrong here? ```java while (true) { break; System.out.println("Hi"); } ```
Unreachable code after break.
214
How does the compiler treat continue vs break for unreachable code?
Identically—both make subsequent code unreachable.
215
Can if (1 == 2) { ... } contain unreachable code?
✅ Yes, because the compiler evaluates the condition statically. Unreachable Code: Fails compilation if after break/continue/return or in dead branches. Method Returns: Cleaner than labels for most early exits. Labeled Breaks: Reserve for complex nested loops with performance constraints. Compiler: Only checks code structure, not runtime logic. Final Tip: Use IDE inspections to automatically detect unreachable code during development.
216
Can you use continue in a switch?
❌ No—only in loops.
217
What’s the difference between break and yield?
break exits a switch statement; yield returns a value in a switch expression.
218
Where is when allowed?
Only in switch cases with pattern matching (e.g., case String s when s.length() > 0).
219
Which structures support labels?
All loops (for, while, do-while) and switch.
220
Is this valid? ```java do { yield 1; } while (false); ```
❌ No—yield is switch-only. Prefer yield in Switches: ```java int x = switch (y) { case 1 -> { yield 10; } // Block-style default -> 0; // Expression-style (no yield) }; ``` Avoid Overusing Labels:Refactor deep nests into methods instead of: ```java LOOP: for (...) { ... break LOOP; } ``` Combine when with null Checks: ```java case String s when s != null -> ... // Safer than separate null case ``` Final Advice: Use yield/when for modern switches, and reserve labels for rare multi-loop exits.
221
Q: What are three rules for using pattern variables properly?
A:
Use unique names that don’t conflict with existing variables
Avoid reassigning pattern variables
Consider making them final for safety
Would you like any additional examples or different question formats?
222
Q: What’s the difference between compile-time and runtime behavior for pattern matching?
A: Compile-time: Checks type hierarchy validity Runtime: Checks actual object type
223
Why use default in enum switches?
Future-proofing + safety against missing cases.
224
When must you use yield?
In switch expression blocks ({}) to return a value.
225
Front: What’s wrong with this? ```java case 1 -> { System.out.println("One"); } ```
Missing yield (compile error).
226
Can return replace yield in switches?
No—return exits the method; yield returns to the switch. For enum switches: Prefer listing all cases (exhaustive) unless you explicitly need default for future values. For yield: Remember it’s block-scoped to the switch expression. Mixing it with return is a common exam pitfall!
227