Docsity

Advanced Java Programming Complete Study Guide (Java 11-21) + Concept Maps & Flashcards, Sintesi del corso di Programmazione Avanzata

Toggle sidebar
bg1
UNIVERSITY OF SALERNO
Bachelor of Science in Computer Engineering (L-8)
Department of Information Engineering, Electrical Engineering and Applied
Mathematics (DIEM)
Advanced Java Programming
Complete Study Guide & Reference Manual
For International Students, Erasmus Participants, and Java Enthusiasts
Based on the reference book Il nuovo Java by Claudio De Sio Cesari
Course Professor: Prof. Luca Greco
Author: Carmine Muollo
Student ID: 0612709530
Academic Year: 2025/2026
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c

Anteprima parziale del testo

Scarica Advanced Java Programming Complete Study Guide (Java 11-21) + Concept Maps & Flashcards e più Sintesi del corso in PDF di Programmazione Avanzata solo su Docsity!

UNIVERSITY OF SALERNO

Bachelor of Science in Computer Engineering (L-8)

Department of Information Engineering, Electrical Engineering and Applied

Mathematics (DIEM)

Advanced Java Programming

Complete Study Guide & Reference Manual

For International Students, Erasmus Participants, and Java Enthusiasts

Based on the reference book Il nuovo Java by Claudio De Sio Cesari

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:

  1. Chapter 1: Advanced Language Enhancements – In-depth analysis of local variable type inference (var), switch expressions, sealed classes/interfaces, and pattern matching.
  2. Chapter 2: Enums, Records, and Generics – Exploration of enum polymorphism, shallow immutability in records (with canonical and compact constructors), and safe management of Type Erasure using wildcards (PECS).
  3. Chapter 3: Annotation Types and Reflection – Reflection API for runtime inspection, and compile-time annotation processing for code generation.
  4. Chapter 4: Lambda Expressions and Method References – Under-the-hood analysis of lambda compilation using the invokedynamic bytecode instruction, lexical scoping of this, and standard functional interfaces.
  5. Chapter 5: Stream API – Declarative pipeline architecture, lazy evaluation, collection/reduction operations, and the use of the Optional container.
  6. Chapter 6: Concurrency, Networking, and Database Persistence – High-level concurrency with explicit locks, Virtual Threads (JDK 21), socket-based TCP client-server networking, database persistence via JDBC and the DAO pattern, JavaFX concurrency, and New I/O (NIO) concepts.

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.

  • Guided 3-Week Study Plan
  • 1 Advanced Language Enhancements
    • 1.1 Local Variable Type Inference (var)
    • 1.2 Switch Expressions and Poly-Expressions
    • 1.3 Sealed Classes and Interfaces
    • 1.4 Pattern Matching
    • 1.5 Conceptual Map
      • 1.5.1 Knowledge Assessment
  • 2 Enums, Records, and Generics
    • 2.1 Enum Types
    • 2.2 Record Types
    • 2.3 Generics and Type Erasure
    • 2.4 Conceptual Map
      • 2.4.1 Knowledge Assessment
  • 3 Annotation Types and Reflection
    • 3.1 Reflection and Introspection
    • 3.2 Annotation Types
    • 3.3 Compile-Time Annotation Processing
    • 3.4 Conceptual Map
      • 3.4.1 Knowledge Assessment
  • 4 Lambda Expressions and Method References
    • 4.1 Lambda Expressions and Functional Interfaces
    • 4.2 Checked Exception Handling in Lambdas
    • 4.3 Method References
    • 4.4 Standard Functional Interfaces
    • 4.5 Conceptual Map
      • 4.5.1 Knowledge Assessment
  • 5 Stream API
    • 5.1 Pipeline Structure
    • 5.2 The Optional Class
      • 5.2.1 Key Methods of Optional
    • 5.3 Fundamental Difference between map and flatMap
    • 5.4 Reduction and Collection
    • 5.5 Conceptual Map
      • 5.5.1 Knowledge Assessment
  • 6 Concurrency, Networking, and Database Persistence
    • 6.1 Concurrency API
      • 6.1.1 Immutable Objects and Atomic Classes
      • 6.1.2 Locks and Synchronizers
      • 6.1.3 Virtual Threads (JDK 21)
    • 6.2 Java Networking (TCP Sockets)
    • 6.3 The NIO (New Input/Output) Library
    • 6.4 JavaFX Concurrency and Animations
    • 6.5 Database Connectivity (JDBC) and the DAO Pattern
    • 6.6 Conceptual Map
      • 6.6.1 Knowledge Assessment
  • Bibliography
  • Glossary of Technical Terms

Guided 3-Week Study Plan

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

  • Days 1-2 : Chapter 1 – Local variable type inference (var) and its limitations. Switch Expressions and poly-expressions.
  • Days 3-4 : Chapter 1 – Sealed Classes and Interfaces. Inheritance rules. Pattern Matching (JDK 16-21) and record deconstruction.
  • Days 5-6 : Chapter 2 – Enum Types (polymorphism and complex methods) and Record Types (canonical, compact, and non-canonical constructors).
  • Day 7 : General review and self-assessment using the flashcards from Chapters 1 and 2.

Week 2: Meta-Programming and Functional Programming

  • Days 8-9 : Chapter 2 – Generics. Invariance, Type Erasure, wildcard bounds (PECS), and solving wildcard capture using helper methods.
  • Days 10-11 : Chapter 3 – Reflection (inspecting fields/methods, setAccessible) and Annotation Types. Compile-time Annotation Processing.
  • Days 12-13 : Chapter 4 – Lambda Expressions, bytecode compilation (invokedynamic), lexical scoping of this, and checked exception wrapping. Method references and standard functional interfaces.
  • Day 14 : Hands-on coding session. Implement practical examples combining reflection and lambdas.

Week 3: Streams, Concurrency, and Persistence

  • Days 15-16 : Chapter 5 – Stream API. Source, intermediate (lazy), and terminal (eager) operations. Advanced use of Optional and reduction/collection methods.
  • Days 17-18 : Chapter 6 – Concurrency API. Immutability, atomic classes (CAS), explicit locks (ReentrantLock), semaphores, and the Executor framework.
  • Day 19 : Chapter 6 – Virtual Threads (JDK 21), TCP socket networking, and NIO foundations.
  • Day 20 : Chapter 6 – JDBC database connections, transaction isolation levels, Savepoints, and the DAO pattern. JavaFX concurrency integration.
  • Day 21 : Full simulation of the oral exam using the questions at the end of each chapter.

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 ->:

  • The arrow operator -> guarantees an implicit break, preventing fall-through.
  • If a case requires a multi-line block, the yield keyword is used to return the value from that case.
  • Exhaustiveness is strictly enforced: every possible value of the evaluated type must be covered by a case label or a default clause.

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:

  1. It must be located in the same package (or in the same module) as the sealed class.
  2. It must directly extend or implement the sealed class.
  3. It must explicitly declare one of three mutually exclusive modifiers:
  • final: The subclass cannot be further extended.
  • sealed: The subclass restricts inheritance to its own permitted subclasses.
  • non-sealed: The subclass reopens the hierarchy, allowing any class to extend it without restrictions.

Key differences between Sealed Classes and Sealed Interfaces:

  • Sealed Class: Can contain instance fields (state) and constructors. Its subclasses can be declared final, sealed, or non-sealed.
  • Sealed Interface: Cannot contain mutable instance state or constructors. Subinterfaces cannot be declared final (since interfaces cannot be instantiated and are meant to be implemented). Therefore, permitted subinterfaces can only be declared sealed or non-sealed. Concrete classes implementing the interface can, however, be declared final, sealed, or non-sealed.

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:

  • Dominance: Case labels must be ordered from the most specific to the most general to prevent unreachable code.
  • Guarded Patterns (when): Allow developers to append boolean conditions directly to a case: 1 case String s when s.length () > 5 -> System.out. println ("Long string ");
  • Null Management: Allows handling null values explicitly using case null, which prevents the switch from throwing a NullPointerException.
  • Record Patterns (Deconstruction): Allows deconstructing record instances to extract their components directly: 1 case Point( int x, int y) -> System.out. println ("X: " + x);

1.5 Conceptual Map

Advanced Language Enhancements

var (Type Inference)

  • Only initialized local variables.
  • No fields, parameters, or return types.
  • Retains static typing at compile-time.

Switch Expressions

  • Arrow syntax (->) and implicit break.
  • yield keyword for multi-line blocks.
  • Exhaustiveness checked by compiler.

Sealed Classes • •^ Restricted inheritance via permits.Subclasses must be final, sealed, or non-sealed.

Pattern Matching

  • Predicate combined with cast pattern variable.
  • Scope limited to logical truth.
  • Record deconstruction support.

1.5.1 Knowledge Assessment

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).

Chapter 2

Enums, Records, and Generics

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:

  • Private final fields for each component declared in the record header.
  • Public getter methods matching the name of each component (e.g., student.name() instead of getName()).
  • Component-based implementations of equals(), hashCode(), and toString().
  • A canonical constructor matching all components in the header.

Records are subject to several strict limitations:

  1. They are implicitly final and cannot be subclassed.
  2. They cannot extend any class (since they already extend java.lang.Record), but they can implement interfaces.
  3. They cannot declare additional instance fields; only static fields are allowed.
  4. Shallow Immutability: If a record contains a reference to a mutable object (like a List), the reference itself is final, but the internal state of the referenced object can still be modified at runtime.

A record can define three styles of constructors:

  1. Canonical Constructor : Manually initializes all fields. It must match the order and types of the record header components exactly.
  2. Compact Canonical Constructor : Omits parameter list declarations in parentheses. It is ideal for parameter validation and normalization. The header parameters are automatically assigned to the final fields at the end of the constructor’s execution.
  3. Non-Canonical Constructor : Must delegate to the canonical constructor using this(...) as its very first statement.

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

  • public static final constants.
  • Complex methods and private constructors.
  • Constant-specific polymorphic behavior.

Record Types

  • final classes with shallow immutability.
  • Implicit getters without ”get” prefix.
  • Compact and canonical constructors. Generics and Wildcards
  • Compile-time Type Erasure.
  • PECS rule for covariance and contravariance.
  • Wildcard capture resolution via helper methods.

2.4.1 Knowledge Assessment

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).

Chapter 3

Annotation Types and Reflection

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:

  1. Via type literals: String.class
  2. Via object instances: obj.getClass()
  3. Via dynamic loading: Class.forName("java.lang.String")

When retrieving class members, there is a fundamental difference between methods:

  • getFields(): Returns only public fields of the class, including those inherited from superclasses and implemented interfaces.
  • getDeclaredFields(): Returns all fields declared explicitly within the class itself (including private, protected, and package-private fields), but completely excludes inherited fields.

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:

  1. Marker Annotations : Contain no elements (e.g., @Override).
  2. Single Value Annotations : Contain a single element named value() (which allows omitting the element name when applying the annotation).
  3. Full Annotations : Contain multiple elements, optionally with default values.

Meta-annotations are annotations applied to the declaration of other annotations to define their behavior:

  • @Target : Restricts the types of code elements (fields, methods, classes, parameters) to which the annotation can be applied, using the ElementType enum.
  • @Retention : Configures how long the annotation is preserved, using the RetentionPolicy enum: - SOURCE: Retained only in source files and discarded by the compiler. - CLASS: Stored in the compiled .class files but not loaded into memory by the JVM (default behavior). - RUNTIME: Loaded into memory by the JVM and accessible at runtime via reflection.
  • @Inherited : Specifies that the annotation applied to a class is automatically inherited by its subclasses.
  • @Repeatable: Allows the same annotation to be applied multiple times to a single code element. It requires a container annotation type.

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 ,