In this module, we will explore the new features and enhancements introduced in Java 9 and subsequent versions. Java has evolved significantly, and understanding these changes is crucial for modern Java development. This module will cover:

  1. Java 9 Features
  2. Java 10 Features
  3. Java 11 Features
  4. Java 12 and Beyond
  5. Practical Exercises

Java 9 Features

  1. Module System (Project Jigsaw)

Java 9 introduced the module system, which allows developers to organize code into modules. This helps in better encapsulation and dependency management.

Example: Creating a Simple Module

// module-info.java
module com.example.myapp {
    requires java.base;
    exports com.example.myapp;
}

Explanation:

  • module com.example.myapp {}: Declares a module named com.example.myapp.
  • requires java.base;: Specifies that this module depends on the java.base module.
  • exports com.example.myapp;: Makes the com.example.myapp package available to other modules.

  1. JShell: The Interactive Java Shell

JShell is a REPL (Read-Eval-Print Loop) tool that allows for interactive execution of Java code.

Example: Using JShell

$ jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> int x = 10;
x ==> 10

jshell> System.out.println(x * 2);
20

  1. Collection Factory Methods

Java 9 introduced factory methods for creating immutable collections.

Example: Creating Immutable Collections

List<String> list = List.of("one", "two", "three");
Set<String> set = Set.of("a", "b", "c");
Map<String, Integer> map = Map.of("key1", 1, "key2", 2);

  1. Private Interface Methods

Java 9 allows private methods in interfaces to share common code between default methods.

Example: Private Interface Methods

interface MyInterface {
    default void method1() {
        commonMethod();
    }

    default void method2() {
        commonMethod();
    }

    private void commonMethod() {
        System.out.println("Common code");
    }
}

Java 10 Features

  1. Local-Variable Type Inference

Java 10 introduced the var keyword, which allows the compiler to infer the type of local variables.

Example: Using var

var list = List.of("one", "two", "three");
for (var item : list) {
    System.out.println(item);
}

  1. Unmodifiable Collections

Java 10 enhanced the Collections class to create unmodifiable collections more easily.

Example: Creating Unmodifiable Collections

List<String> list = List.copyOf(List.of("one", "two", "three"));

Java 11 Features

  1. New String Methods

Java 11 introduced several new methods for the String class, such as isBlank(), lines(), strip(), repeat(), etc.

Example: New String Methods

String str = "  Hello World  ";
System.out.println(str.isBlank()); // false
System.out.println(str.strip()); // "Hello World"
System.out.println(str.repeat(2)); // "  Hello World    Hello World  "

  1. Local-Variable Syntax for Lambda Parameters

Java 11 allows the use of var in lambda expressions.

Example: Using var in Lambda Expressions

List<String> list = List.of("one", "two", "three");
list.forEach((var item) -> System.out.println(item));

Java 12 and Beyond

  1. Switch Expressions (Java 12)

Java 12 introduced switch expressions, which simplify the switch statement and can return a value.

Example: Switch Expressions

int day = 3;
String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Unknown";
};
System.out.println(dayName); // Wednesday

  1. Text Blocks (Java 13)

Java 13 introduced text blocks, which allow for multi-line string literals.

Example: Text Blocks

String textBlock = """
    This is a text block.
    It spans multiple lines.
    """;
System.out.println(textBlock);

  1. Records (Java 14)

Java 14 introduced records, which are a compact syntax for declaring classes that are primarily used to store data.

Example: Using Records

public record Point(int x, int y) {}

Point point = new Point(1, 2);
System.out.println(point.x()); // 1
System.out.println(point.y()); // 2

  1. Pattern Matching for instanceof (Java 16)

Java 16 introduced pattern matching for instanceof, which simplifies type checks and casting.

Example: Pattern Matching for instanceof

Object obj = "Hello, World!";
if (obj instanceof String str) {
    System.out.println(str.toUpperCase()); // HELLO, WORLD!
}

Practical Exercises

Exercise 1: Using JShell

  1. Open JShell.
  2. Declare a variable int a = 5;.
  3. Print the square of a.

Solution:

$ jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> int a = 5;
a ==> 5

jshell> System.out.println(a * a);
25

Exercise 2: Creating a Module

  1. Create a module named com.example.helloworld.
  2. Export a package com.example.helloworld that contains a class HelloWorld with a main method that prints "Hello, World!".

Solution:

// module-info.java
module com.example.helloworld {
    exports com.example.helloworld;
}

// HelloWorld.java
package com.example.helloworld;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Exercise 3: Using var and New String Methods

  1. Create a list of strings using var.
  2. Use the strip() method to remove leading and trailing spaces from a string.

Solution:

var list = List.of("  one  ", "  two  ", "  three  ");
for (var item : list) {
    System.out.println(item.strip());
}

Conclusion

In this module, we explored the significant features introduced in Java 9 and beyond. These enhancements improve code readability, maintainability, and performance. Understanding these features will help you write modern and efficient Java code. In the next module, we will delve into Java frameworks and libraries, which are essential for building robust applications.

Java Programming Course

Module 1: Introduction to Java

Module 2: Control Flow

Module 3: Object-Oriented Programming

Module 4: Advanced Object-Oriented Programming

Module 5: Data Structures and Collections

Module 6: Exception Handling

Module 7: File I/O

Module 8: Multithreading and Concurrency

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved