Practice & Assessment
Test your understanding of Modern Java Features and Best Practices
Multiple Choice Questions
5What is an 'effectively final' variable in the context of Java lambdas?
Which Optional method is the safest way to retrieve a value when the Optional might be empty?
What does the Java compiler guarantee about a sealed class switch with no default case?
What is the key advantage of Java records over a regular class with the same fields?
In the Builder pattern, why does each setter in the Builder class return this?
Coding Challenges
1JSON-like config builder with validation
Implement a DatabaseConfig record with fields host (String), port (int), database (String), maxConnections (int), and timeout (int). Create a DatabaseConfig.Builder class with a fluent API. Add validation in build(): host cannot be null or blank, port must be 1-65535, maxConnections must be 1-500. Throw IllegalStateException with a descriptive message on violation. Write a main method demonstrating valid config creation and catching each validation error. Input: method calls on the Builder. Output: valid DatabaseConfig printed via toString, and error messages for invalid configs. Time estimate: 20–25 minutes.
Mini Project
Mini Expression Evaluator
Build a simple arithmetic expression evaluator using sealed classes and pattern matching. Define a sealed interface Expr permitting: Num (record with double value), Add (record with Expr left, Expr right), Sub, Mul, and Div. Implement a method double eval(Expr expr) using a pattern matching switch that handles all five types. Div should throw ArithmeticException when the right operand evaluates to 0. Implement a method String prettyPrint(Expr expr) that returns a human-readable string: '(3.0 + 4.0)' for Add(Num(3), Num(4)). Write at least 8 test expressions of varying depth — include nested expressions like Add(Mul(Num(2), Num(3)), Num(4)). Add Optional<Double> safeEval(Expr expr) that wraps eval in a try-catch and returns Optional.empty() on error. Demonstrate all methods in main.
