CHP3 - Making Decisions Flashcards
Hierarchy of Number Class
java.lang.Object
↳ java.lang.Number
↳ java.lang.Integer
↳ java.lang.Double
↳ java.lang.Float
↳ java.lang.Long
↳ java.lang.Short
↳ java.lang.Byte
↳ java.util.concurrent.atomic.AtomicInteger
↳ java.util.concurrent.atomic.AtomicLong
Pattern Matching
Technique of controlling program flow that only executes a section of code that meets certain criteria.
Supported Types of Pattern Matching
The type of the pattern variable must be a compatible type, which includes the same type, a subtype, or a supertype of the reference variable.
Shadowing
Shadowing occurs when a variable declared within an inner scope has the same name as a variable in an outer scope. The inner variable “shadows” or hides the outer variable within that block.
int value = 50;
{
int value = 100; // This ‘value’ shadows the outer ‘value’
System.out.println(value); // prints 100
}
System.out.println(value); // prints 50
switch variable types
int and Integer
byte and Byte
short and Short
char and Character
String
enum values
All object types (pattern matching)
var (if the type resolves to one of the preceding types)
switch (month) {}
Is this valid?
A switch statement is not required to contain any case clauses. This is perfectly valid.
Ways to write exhaustive switch
- Add a default clause.
- If the switch takes an enum, add a case clause for every possible enum value.
- Cover all possible types of the switch variable with pattern matching
What is yield?
yield keyword is return statement for switch
switch and pattern matching
One of the simplest rules when working with switch and pattern matching is that the type cannot be unrelated.
It must be the same type as the switch variable or a subtype.
What does it mean switch statement must be exhaustive?
✔ Exhaustiveness means handling all possible values in a switch.
✔ For enums and sealed types, if all cases are covered, default is not needed.
✔ For open types (like Object or Number), a default case is required.
continue in switch?
It cannot be used inside of switch
private DayOfWeek getWeekDay(int day, final int thursday);
In this method signature, is thursday compile time constant?
No, it is not since any int value can be passed as parameter.
case 2. 10: break;
Is it legal in Java?
✔ Valid switch syntax: case 2, 10: is legal in Java 21+ (but not in Java 20 or earlier).
Is it valid in case?
case !(Number n) -˃ 3 + n.intValue();
The code does not compile because case clause uses the logical complement operator (!), which is not permitted with pattern matching.
do {
5: meters–;
6: if (meters==8) keepGoing = false;
7: result -= 2;
8: } while keepGoing;
Is it valid?
No it is not valid.
Because while condition must be inside of braces.
yield attention
Be carefull with:
-semicolon after yield closing brace
-without yield
default vs null in switch
default dominates the null
Method vs field access
Method calls are resolved at runtime, while field access is resolved at compile time.