Java 17 Flashcards
What are sealed classes? What are their key benefits?
Sealed classes allow you to restrict which classes can extend or implement a class or interface. This provides more control over inheritance and improves domain modeling.
public sealed class Vehicle permits Car, Truck { }
public final class Car extends Vehicle { }
public final class Truck extends Vehicle { }
Switch Statement Updates
- Pattern matching for switch allowing patterns in case labels not just constants
- similar to Scala’s PM tho cannot deconstruct fully; syntax diff: kw match (not switch) & => (not ->) - Intro of kw when
- Guarded Pattern: if statement within case
- Nulls are acceptable as a match
- Intro of kw yield
double getDoubleUsingSwitch(Object o) {
return switch (o) {
case Integer i -> i.doubleValue();
case Float f when f > 0 -> Double.parseDouble(s);
case String s -> if (s.length() > 0) {
yield Double.parseDouble(s);
} else {
yield 0d;
}
case Null -> 0d
default -> {
System.out.println(“The vehicle could not be found.”);
yield “Unknown Vehicle”;
};
};
}
- Also can use with sealed classes
sealed interface Vehicle permits Car, Truck, Motorcycle {}
final class Car implements Vehicle {}
final class Truck implements Vehicle {}
final class Motorcycle implements Vehicle {}
public static String sealedClass(Vehicle v) {
return switch(v) {
case Car c -> “I am a car”;
case Truck t -> “I am a truck”;
case Motorcycle m -> “I am a motorcycle”;
};
}
Describe Enhanced Pseudo-Random Number Generators (PRNG) & its key benefits?
Java 17 introduces new interfaces and implementations for random number generation.
Example:
RandomGenerator generator = RandomGeneratorFactory.of(“L64X128MixRandom”).create();
System.out.println(generator.nextInt(100)); // Generates a random number between 0–99
Key Benefits:
* Provides flexibility with different algorithms.
* Enhanced performance for simulations and gaming.
Context-Specific Deserialization Filters
Java 17 allows setting context-specific deserialization filters to improve security when deserializing objects.
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(“maxdepth=5;maxarray=100”);
This helps prevent security issues like deserialization attacks.
Nullpointer Exception (NPE)
java 17 NPE pinpoints out where & what caused the null object reference
ie:
Exception in thread “main” java.lang.NullPointerException:
Cannot assign field “i” because “a” is null
at Prog.main(Prog.java:5)