Overview of Java Features (Java 9 - Java 17)

Java 9

1. Factory Methods for Collections

Java 9 introduces factory methods to simplify the creation of immutable collections like ListSet, and Map.

Key Points:

  • Provides static methods for initializing immutable collections.
  • No modifications (add, remove, update) allowed after initialization.
  • Simplifies code compared to traditional Arrays.asList() or Collections.unmodifiableList().

Examples:

List<String> immutableList = List.of("Abc", "Def", "Ghi");
Map<Integer, String> nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three");

2. Private Interface Methods

Java 9 allows private methods inside interfaces to eliminate redundant code in default and static methods.

Key Points:

  • Enhances code reusability inside interfaces.
  • Private methods cannot be accessed outside the interface.

Example:

public interface Person {
  private Long createID() { /* Implementation */ }
  private static void displayDetails() { /* Implementation */ }
}

Java 10

Local Variable Type Inference (var)

Java 10 introduces var for type inference in local variables, reducing boilerplate code.

Key Points:

  • var can only be used for local variables inside methods, loops, or initialization blocks.
  • Cannot be used for class fields, method parameters, or return types.
  • In JDK 10 and later, you can declare local variables with non-null initializers with the var identifier, which can help you write code that’s easier to read.
  • Note: that this feature is available only for local variables with the initializer.

Example:

Valid Uses of var:


var list = new ArrayList<String>();
var stream = list.stream();

class A {public static void main(String a[]){
   var list = new ArrayList<String>();  // infers ArrayList<String>
   var stream = list.stream();          // infers Stream<String>   // Declaration of a local variable in java 10 using LVTI
   var x = "Hi there";   // Declaring index variables in for loops using LVTI in Java
   for (var x = 0; x < 3; x++) {
     System.out.println(x);
    }
   System.out.println(x)
}
}

Invalid Uses of var:

var name; // Error: requires an initializer
var expression = (String s) -> s.length() > 10; // Error: cannot use var with lambda expressions

class A {**//Not permitted in class fields**(non-local variables**)
**public var = "hello"; // error: 'var' is not allowed here**//Not allowed as parameter for any methods**
void show(var a) /*Error:
{
}**//Not permitted in method return type
**public var show() /* Error: {
   return 1;
}
}

Java 11

New Utility Methods in String

Java 11 adds several new methods to the String class to improve usability.

  • isBlank(): Checks if a string is empty or contains only white spaces.
  • lines(): Splits a string into a stream of lines.
  • repeat(n): Repeats a string n times.
  • strip(): It is used to remove the white-spaces which are in-front and back of the string.strip() is “Unicode-aware” evolution of trim(). When trim() was introduced, Unicode wasn’t evolved. Now, the new strip() removes all kinds of whitespaces leading and trailing(check the method Character.isWhitespace(c) to know if a unicode is whitespace or not)
  • stripTrailing(): It is used to remove the white-space which is in back of the string
  • stripLeading(): It is used to remove the white-space which is in-front of the string

Example:


String str = "  hello  ";
System.out.println(str.strip()); // "hello"

String str = "1".repeat(5);
String str = "Hi\nHello\nNamaste";
  System.out.println(str.lines().collect(Collectors.toList()));

public class HelloWorld {
 public static void main(String[] args)
 {
    System.out.println("   hi  ".strip());
    System.out.println("   hi  ".stripLeading());
    System.out.println("   hi  ".stripTrailing());
}
}

Output:
"hi"
"hi  "
"   hi"

New File Methods

Java 11 introduces Files.readString() and Files.writeString() to simplify file handling.

Example:

Path filePath = Files.writeString(Files.createTempFile("demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);

New Not Predicate Method

A static not method has been added to the Predicate interface. We can use it to negate an existing predicate, much like the negate method:

Example:

List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");List withoutBlanks = sampleList.stream()
  .filter(Predicate.not(String::isBlank))
  .collect(Collectors.toList());assertThat(withoutBlanks).containsExactly("Java", "Kotlin");

Java 12

Enhanced switch Expressions

Java 12 introduces an improved switch statement that allows using expressions.

Key Points:

  • Removes the need for break.
  • Can return values directly.
Switch expressions will now be used as a statement as well as expressions. This makes code simplification and pattern matching possible for the switch.

Now, the new Arrow syntax for switch introduced as

case X -> {}

Firstly, let’s look and at the old syntax:

Example:

DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();String typeOfDay = "";
switch (dayOfWeek) {
    case MONDAY:
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
    case FRIDAY:
        typeOfDay = "Working Day";
        break;
    case SATURDAY:
    case SUNDAY:
        typeOfDay = "Day Off";
}
String typeOfDay = switch (dayOfWeek) {
 case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
 case SATURDAY, SUNDAY -> "Day Off";
};

Java 14

1. Records

Records provide a concise way to declare immutable data classes, automatically generating toString()equals(), and hashCode().
A record is a data class that stores pure data. The idea behind introducing records is to quickly create simple and concise classes devoid of boilerplate code in the model POJOs.
The important difference between class and record is that a record aims to eliminate all the boilerplate code needed to set and get the data from instance. Records transfer this responsibility to java compiler which generates the constructor, field getters, hashCode() and equals() as well toString() methods.

Example:

public record PersonRecord(String name, int age) {}
PersonRecord person = new PersonRecord("Abc", 25);
System.out.println(person.age());

2. Helpful NullPointerExceptions

Java 14 improves error messages when NullPointerException occurs.

Example:

int[] arr = null;
arr[0] = 1; // Shows "Cannot store to int array because 'arr' is null"

3. Pattern Matching for instanceof

Simplifies instanceof by eliminating redundant casting.

Example:

Before Java 14:
if (obj instanceof Journaldev) {
   Journaldev jd = (Journaldev) obj;
   System.out.println(jd.getAuthor());
}
After Java 14:
if (obj instanceof Journaldev jd) {
  System.out.println(jd.getAuthor());
}

Java 15

Text Blocks

Multi-line string literals improve readability and reduce the need for escape sequences.

Text blocks are finally a standard feature in Java 15. A text block is a multi-line string literal.

While using text blocks, we do not need to provide explicit line terminators, string concatenations, and delimiters otherwise used for writing the normal string literals.

Text blocks start with a “”” (three double-quote marks) followed by optional whitespaces and a newline

Example:

String json = """
  {
    "name": "abc",
    "age": 2
  }
""";

Java 16

Stream.toList() Method

Java 16 introduces Stream.toList() to simplify stream collection operations.

Example:

List<String> integersAsString = Arrays.asList("1", "2", "3");
//Old Way
List<Integer> ints = integersAsString.stream().map(Integer::parseInt).collect(Collectors.
toList());
//From java16 onwords
List<Integer> intsEquivalent = integersAsString.stream().map(Integer::parseInt).toList();

Java 17

Sealed Classes

Sealed classes restrict which classes can extend them, providing better control over class hierarchies.
Note: Only final,sealed or non-sealed class can extend sealclass

Example:

class sealed abstract Write permits FileWrite
final class FileWrite extends Write {}
class non-sealed HDDrive implements Drive {}

These Java versions introduce powerful features that simplify development, improve performance, and enhance code readability.

Post a Comment

Previous Post Next Post