




































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





































Complete Study Guide & Reference Manual
Course Professor: Prof. Luca Greco Author: Carmine Muollo Student ID: 0612709530
Academic Year: 2025/
Abstract
This reference manual is a comprehensive study guide designed to prepare students for the oral examination of the Advanced Java Programming (PJA) course in the Computer Engineering curriculum at the University of Salerno. It is specifically tailored to support domestic, international, and Erasmus students, as well as Java developers wishing to deepen their understanding of modern JDK features. The guide adopts a formal, academic tone, modeled after the authoritative writing style of Claudio De Sio Cesari, focusing on both syntactical rules and the low-level behavior of the compiler and the Java Virtual Machine (JVM). The contents are structured into 6 chapters corresponding to the official Educational Units of the course:
Each chapter includes VsCode-styled code snippets, TikZ block diagrams for visual review, real-world analogies, 5 quick-review flashcards, and 2 open-ended oral exam questions. A formal bibliography and an interactive, hyperlinked technical glossary are provided at the end of the document.
Succeeding in the oral examination requires not only knowledge of syntax, but the ability to articulate the ”why” behind Java’s features (such as memory management, backward compatibility, and performance optimization). This study plan is designed for a 21-day (3-week) period, with a daily commitment of approximately 3-4 hours:
Week 1: Modern Syntax and Data Modeling
Week 2: Meta-Programming and Functional Programming
Week 3: Streams, Concurrency, and Persistence
Listing 1.1: Correct usage and common compilation errors with var
1.2 Switch Expressions and Poly-Expressions
The traditional switch statement acted only as a control flow mechanism, requiring the break keyword to prevent fall-through. Java 14 introduced the switch expression , which evaluates to and returns a single value directly. Switch expressions introduce the arrow syntax case Label ->:
A switch expression is a key example of a poly-expression: an expression whose type is not determined solely by its own structure, but is inferred based on its target context (the type of the variable it is being assigned to). 1 public class SwitchDemo { 2 public static void main(String [] args) { 3 String day = "MONDAY "; 4 int dayType = switch (day) { 5 case "MONDAY ", " TUESDAY ", " WEDNESDAY " -> 1; 6 case " SATURDAY ", "SUNDAY " -> 2; 7 default -> { 8 System.out. println (" Generic weekday "); 9 yield 0; 10 } 11 }; 12 } 13 }
Listing 1.2: Example of a Switch Expression using arrows and yield
1.3 Sealed Classes and Interfaces
Sealed classes and interfaces (stabilized in Java 17) restrict inheritance declaratively. A sealed class or interface explicitly defines which subclasses or subinterfaces are allowed to extend or implement it using the permits clause. Any subclass permitted in the declaration must satisfy three strict rules:
Key differences between Sealed Classes and Sealed Interfaces:
1 public sealed interface Vehicle permits Car , Motorcycle {} 2 3 // A concrete class must specify final , sealed , or non -sealed 4 public final class Car implements Vehicle {} 5 public non - sealed class Motorcycle implements Vehicle {}
Listing 1.3: Sealed hierarchy with sealed interface and implementing classes
1.4 Pattern Matching
Pattern matching combines a type check predicate with one or more pattern variables that automatically hold the cast value upon successful matching. Pattern Matching for instanceof (Java 16) removes the need for redundant manual casting:
1 if (obj instanceof String s) { 2 System .out. println (s.length ()); // 's' is visible and is already of type String 3 }
The visibility of the pattern variable s is governed by ”flow scoping”: it is only in scope where the compiler can guarantee the type check has succeeded. For example, if (obj instanceof String s && s.length() > 0) is valid, whereas if (obj instanceof String s || s.length() > 0) triggers a compilation error. Pattern Matching for switch (Java 21) allows switching directly on the types of objects:
1.5 Conceptual Map
Advanced Language Enhancements
var (Type Inference)
Switch Expressions
Sealed Classes • •^ Restricted inheritance via permits.Subclasses must be final, sealed, or non-sealed.
Pattern Matching
Flashcard 1. Question: Is it possible to use var to declare an instance field in a class? Answer: No. The use of var is strictly limited to local variables declared inside methods, static initializers, or loops. It cannot be used for instance or static fields because the compiler needs explicit type information to define the class structure.
Flashcard 1. Question: What is the main difference between a switch expression and a switch statement regarding returned values? Answer: A switch expression must return a value (which can be assigned to a vari- able or evaluated inline) and requires all possible cases to be covered. A switch state- ment simply executes blocks of code, does not return a value, and does not enforce exhaustiveness (except in very rare configurations).
Flashcard 1.
Question: How does the compiler behave if the default clause is omitted in a switch expression evaluating a String? Answer: The compiler will throw a compilation error for lack of exhaustiveness. Strings have an infinite number of possible values, making a default clause manda- tory to handle cases that are not explicitly defined.
Flashcard 1.
Question: What are the three mandatory modifiers for subclasses extending a sealed class? Answer: Subclasses must be explicitly declared as either final (cannot be ex- tended further), sealed (restricting inheritance to its own permitted subclasses), or non-sealed (opening the hierarchy to any future subclass).
Flashcard 1.
Question: What is ”flow scoping” for a pattern variable introduced by instanceof? Answer: It is the section of code where the pattern variable is in scope. The variable is only accessible in blocks where the compiler can logically guarantee that the type check was successful (e.g., inside the if block or to the right of the && operator).
Structuring data safely and avoiding runtime type errors are critical aspects of Java design. This chapter examines the polymorphic capabilities of enum types, the shallow immutability of records, and the compile-time type safety rules enforced by generics.
2.1 Enum Types
Enums in Java are specialized classes that implicitly extend java.lang.Enum. Consequently, enums cannot extend other classes, but they are permitted to implement interfaces. Each constant defined in an enum represents a public static final instance of the enum class. Enums can declare instance fields, regular methods, and constructors. An important limitation is that enum constructors are implicitly private; declaring them as public or protected will trigger a compilation error. Enums support polymorphism through constant-specific class bodies. By declaring an abstract method in the enum body, every constant is forced to provide its own implementation. This allows constants to exhibit polymorphic behavior without using conditional statements (like if or switch). 1 public enum Operation { 2 ADDITION { 3 @Override 4 public double calculate ( double a, double b) { return a + b; } 5 }, 6 SUBTRACTION { 7 @Override 8 public double calculate ( double a, double b) { return a - b; } 9 }; 10 11 public abstract double calculate ( double a, double b); 12 }
Listing 2.1: Polymorphism in Enum Types
2.2 Record Types
Introduced in Java 16, record types are specialized classes designed to act as simple carriers of immutable data (Data Transfer Objects). When declaring a record, the compiler automatically generates:
Records are subject to several strict limitations:
A record can define three styles of constructors:
1 public record Student (String studentId , String name) { 2 // Compact constructor for validation 3 public Student { 4 if ( studentId == null || studentId. isBlank ()) { 5 throw new IllegalArgumentException (" Invalid Student ID"); 6 } 7 name = name.trim (); // Parameter normalization 8 } 9 10 // Non - canonical constructor 11 public Student (String studentId ) { 12 this (studentId , " Anonymous "); // Mandatory delegation 13 } 14 }
Listing 2.2: Record with compact and non-canonical constructors
2.3 Generics and Type Erasure
Generics ensure compile-time type safety by restricting the types of objects that collections and classes can manipulate. At runtime, the JVM has no knowledge of generic types. The compiler applies a process known as Type Erasure :
2.4 Conceptual Map
Enums, Records and Generics
Enum Types
Record Types
Flashcard 2. Question: Is it possible to extend a record type? Answer: No. Record types are implicitly declared as final by the compiler and can- not be extended. Furthermore, records cannot extend other classes because they al- ready inherit from their common superclass java.lang.Record.
Flashcard 2.
Question: What is the main syntactical difference of a compact constructor in a record? Answer: A compact constructor does not declare any parameters in parentheses next to the record name. It is used to validate and normalize header parameters before they are automatically assigned to the final fields.
Flashcard 2.
Question: What is ”Type Erasure” in generics? Answer: It is the mechanism by which the Java compiler removes all generic type parameter information (such as ) during compilation, replacing them with Object or their defined bounds, to maintain backward compatibility with pre-Java 5 versions.
Flashcard 2.
Question: What does the PECS rule establish in generics? Answer: It establishes that if a parameterized data structure acts as a data producer (reading), you should use the? extends T covariance syntax; if it acts as a data con- sumer (writing), you should use the? super T contravariance syntax.
Flashcard 2.
Question: Can we add elements other than null to a List? Answer: No. Because the wildcard indicates an unknown concrete subclass of Number, the compiler blocks all write attempts to prevent heap pollution (such as in- serting a Double into a list that at runtime contains only Integer instances).
Reflection and annotation types are the foundation of declarative programming and meta-programming in Java. They enable inspection of code structures at runtime and compile-time code generation.
3.1 Reflection and Introspection
The Reflection API allows an executing Java program to inspect and modify its own logical structure (classes, fields, methods, and constructors) at runtime. The primary entry point is the java.lang.Class class. An instance of Class can be obtained in three ways:
When retrieving class members, there is a fundamental difference between methods:
Reflection allows developers to bypass standard access control by calling setAccessible(true) on private Field, Method, or Constructor objects. Security Note : Starting from Java 9, the module system blocks deep reflection on internal system API packages unless specific JVM command-line flags (such as --add-opens) are provided. Furthermore, method parameter names are discarded during compilation by default to save space. To access parameter names at runtime via reflection (Parameter.getName()), the source code must be compiled with the -parameters compiler flag.
3.2 Annotation Types
Annotations are metadata associated with code declarations. They are defined using the @interface keyword. Annotations are categorized structurally as:
Meta-annotations are annotations applied to the declaration of other annotations to define their behavior:
3.3 Compile-Time Annotation Processing
Annotation processing allows scanning and processing annotations at compile-time to generate new source files or resources. It is implemented by extending javax.annotation.processing.AbstractProcessor. Compilation proceeds in successive rounds. In each round, the compiler scans the source code for annotations, invokes the process() method of registered processors, and feeds any generated files into the next round, repeating this cycle until no new files are created. 1 import javax. annotation. processing .*; 2 import javax.lang.model. SourceVersion ; 3 import javax.lang.model. element. Element ; 4 import javax.lang.model. element. TypeElement ; 5 import javax.tools. Diagnostic ; 6 import java.util.Set; 7 8 @SupportedAnnotationTypes (" Constraint ") 9 @SupportedSourceVersion ( SourceVersion. RELEASE_17 ) 10 public class ConstraintProcessor extends AbstractProcessor { 11 12 @Override 13 public boolean process (Set annotations , RoundEnvironment roundEnv ) { 14 for ( Element elem : roundEnv. getElementsAnnotatedWith ( Constraint. class )) { 15 Constraint c = elem. getAnnotation ( Constraint. class ); 16 if (c.min () < 0) { 17 processingEnv. getMessager (). printMessage ( 18 Diagnostic .Kind.ERROR ,