Java 17 Flashcards

1
Q

What are sealed classes? What are their key benefits?

A

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 { }

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

Switch Statement Updates

A
  1. 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 ->)
  2. Intro of kw when
  3. Guarded Pattern: if statement within case
  4. Nulls are acceptable as a match
  5. 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”;
};
};
}

  1. 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”;
};
}

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

Describe Enhanced Pseudo-Random Number Generators (PRNG) & its key benefits?

A

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.

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

Context-Specific Deserialization Filters

A

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.

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

Nullpointer Exception (NPE)

A

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)

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