Java 8 Features with Examples

Last Updated : 27 Jun 2026

Oracle released Java 8 in March 18, 2014. It was a revolutionary release of Java for the software development platform. It includes various upgrades to the Java programming, JVM, tools and libraries.

Java 8 Features

The following feature enhanced in Java ersion 8:

Lambda Expressions

Lambda expression helps us to write our code in a functional style. It provides a clear and concise way to implement the SAM interface (Single Abstract Method) by using an expression. It is very useful in a collection library in which it helps to iterate, filter, and extract data.

To read more Java Lambda Expression

Syntax:

  • argument-list: It can be empty or non-empty as well. It represents the parameters used by the expression.
  • arrow-token (->): It links the arguments to the body of the expression.
  • body: It contains expressions and statements for the lambda expression.

Example

In this example, we use a lambda expression with a Predicate to filter and display the list of languages that start with the letter "C".

Java

import java.util.Arrays;  
import java.util.List;  
import java.util.function.Predicate;  
public class Main {  
    public static void main(String[] args) {  
        List languages = Arrays.asList("C", "C#", "Java", "Python", "JavaScript", "C++");  
        System.out.println("Languages that start with 'C':");  
        filter(languages, (str) -> str.startsWith("C"));  
    }  
    public static void filter(List names, Predicate condition) {  
        for(String name: names)  {  
            if(condition.test(name)) {  
                System.out.println(name + " ");  
            }  
        }  
    }  
}  
Compile and Run

Output:

Languages that start with 'C':
C 
C# 
C++

Method References

Java 8 Method reference is used to refer method of a functional interface. It is a compact and easy form of a lambda expression. Each time when you are using a lambda expression to just referring a method, we can replace our lambda expression with a method reference.

To read more Java 8 Method Reference

Types of Method References

There are the following four types of method references:

1. Static Method References: It reference methods that are static within classes.

Syntax:

Example: The max method of the Math class is Math::max.

2. Instance Method References of a Particular Object: It reference methods of a specific instance of a class.

Syntax:

It has the following syntax:

Example:  Suppose str is an instance of the String class, str::length references the length() method of str.

3. Instance Method References of an Arbitrary Object of a Particular Type: It reference methods of an instance that will be supplied at the time of calling.

Syntax:

Example: String::toLowerCase references the toLowerCase() method on an instance of String that will be determined at runtime.

4. Constructor References:It reference constructors of classes.

Syntax:

Example: ArrayList::new references the constructor of ArrayList.

Example

In this example, different types of method references in Java are demonstrated, including static method references (String::toUpperCase), instance method references (System.out::println), and constructor references (ArrayList::new and Integer::new).

Java

import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
import java.util.function.Function;  
import java.util.function.Supplier;  
import java.util.stream.Collectors;  
public class Main {  
    public static void main(String[] args) {  
        List words = Arrays.asList("Java", "Stream", "Method", "References");  
        // Static Method Reference: Converting all strings to uppercase  
        List upperCaseWords = words.stream()  
                                           .map(String::toUpperCase) // static method reference  
                                           .collect(Collectors.toList());  
        System.out.println("Uppercase Words: " + upperCaseWords);  
        // Instance Method Reference of an Arbitrary Object of a Particular Type  
        System.out.println("Printing each word:");  
        words.forEach(System.out::println); // instance method reference  
        // Constructor Reference: Creating new instances  
        Supplier> listSupplier = ArrayList::new; // constructor reference  
        List newList = listSupplier.get();  
        newList.addAll(words);  
        System.out.println("New List: " + newList);  
        // Additional Example: Using Function Interface for Constructor Reference  
        Function stringToInteger = Integer::new; // constructor reference
        Integer number = stringToInteger.apply("100");  
   System.out.println("String to Integer: " + number);  
    }  
}  
Compile and Run

Output:


 
Uppercase Words: [JAVA, STREAM, METHOD, REFERENCES] Printing each word:Java Stream Method References New List: [Java, Stream, Method, References] String to Integer: 100

Functional Interface

An Interface that contains only one abstract method is known as a functional interface. It can have any number of default and static methods. It can also declare methods of an object class.

Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).

To read more Java 8 Functional Interface

Example

In this example, a custom functional interface is implemented using method references (Integer::valueOf and String::toUpperCase) to perform operations like converting a string to an integer and changing a string to uppercase in a concise and readable way.

Java

@FunctionalInterface  
interface Converter {  
    T convert(F from);  
}  
public class Main {  
    public static void main(String[] args) {  
        // Using the Converter functional interface with a lambda expression  
        Converter stringToInteger = Integer::valueOf;  
        // Applying the converter to convert a string to an integer  
        int convertedValue = stringToInteger.convert("123");  
        System.out.println("Converted Value: " + convertedValue);  
        // Another example, converting case of a string  
        Converter upperCaseConverter = String::toUpperCase;  
        String convertedString = upperCaseConverter.convert("java");  
        System.out.println("Converted String: " + convertedString);  
    }  
}  
Compile and Run

Output:

Converted Value: 123
Converted String: JAVA

Optional Class

In Java 8, a new class was introduced name Optional. It belongs to the java.util package. It is public and final class that is handy in dealing with the NullPointerException in applications of Java. It gives methods for checking the presence of a value for the specific variable.

To read more Optional Class

Example

In this example, the Optional class is used to safely handle a potentially null value by checking its presence with isPresent() and avoiding a NullPointerException.

Java

import java.util.Optional;  
public class Main {  
    public static void main(String[] args) {  
     String[] str = new String[10]; // Initialize an array of strings with default null values.
        str[5] = "Hello, Optional!"; // Uncomment this line to test with a non-null value.  
        // Create an Optional object from the value of str[5].  
        Optional checkNull = Optional.ofNullable(str[5]);  
        // Check if the Optional object contains a value.  
        if (checkNull.isPresent()) {  
            // Convert the string to lowercase if it's not null.  
            String word = str[5].toLowerCase();  
            System.out.println(word); // Print the lowercase string.  
        } else {  
            System.out.println("string is null"); // Indicate that the string is null.  
        }  
    }  
}  
Compile and Run

Output:

Hello, optional!

forEach() Method

In order to iterate over the elements, Java provides a new method forEach(). Its is defined in Stream and Iterable interfaces.

In the Iterable interface, it is defined as the default method. Those classes in Collection which implements Iterable interface may use the forEach() method for the iteration of elements.

This method takes a single parameter, which is a functional interface, so that a lambda expression as an argument can be passed.

To read more Java 8 for each

Example

In this example, the forEach() method is used with a lambda expression to iterate over a Map and print each key-value pair in a concise and readable way.

Java

import java.util.Map;  
import java.util.HashMap;  
public class Main {  
    public static void main(String[] args) {  
        // Create a map of Integer keys and String values  
        Map map = new HashMap<>();  
        map.put(1, "One");  
        map.put(2, "Two");  
        map.put(3, "Three");  
        map.put(4, "Four");  
        // Use forEach to iterate over the map and print each key-value pair  
        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));  
    }  
} 
Compile and Run

Output:

Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four

Date/Time API

Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date and Time classes.

To read more Java Date and Time

API Specification

  • java.time: Core classes for dates, times, combined date and time, instants, durations, periods, and clocks using the ISO-8601 system.
  • java.time.chrono: Supports non-ISO calendar systems with predefined and custom chronologies.
  • java.time.format: For formatting and parsing date-time objects.
  • java.time.temporal: Advanced features for date-time manipulation, aimed at library developers.
  • java.time.zone: Handles time zones, offsets, and rules.

Example

In this example, the Java Date and Time API is used to get the current date, perform date operations like adding days, format a date, and parse a string into a LocalDate object.

Java

import java.time.LocalDate;  
import java.time.format.DateTimeFormatter;  
public class Main {  
    public static void main(String[] args) {  
        // Current Date  
        LocalDate today = LocalDate.now();  
        System.out.println("Today: " + today);  
        // Adding 5 days  
        LocalDate futureDate = today.plusDays(5);  
        System.out.println("Future Date: " + futureDate);  
        // Formatting the future date  
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");  
        String formattedDate = futureDate.format(formatter);  
        System.out.println("Formatted Future Date: " + formattedDate);  
        // Parsing a date string  
        String dateString = "25-12-2024";  
        LocalDate parsedDate = LocalDate.parse(dateString, formatter);  
        System.out.println("Parsed Date: " + parsedDate);  
    }  
}  
Compile and Run

Output:

Today: 2026-06-16
Future Date: 2026-06-21
Formatted Future Date: 21-06-2026
Parsed Date: 2024-12-25

Static Method in Interface

Static methods in interfaces are similar to static methods in classes. They are defined with the static keyword and can be called without an instance of the class that implements the interface. These methods are part of the interface and not the objects that implement the interface. Thus, they provide a convenient place for utility methods related to the interface.

Example

In this example, an interface defines a static method and an abstract method, where the static method is called directly using the interface name, and the abstract method is implemented by a class to perform a custom action.

Java

// Define an interface for displaying messages.  
interface MessageDisplay {  
    // Static method to display a static greeting message.  
    static void showStaticMessage() {  
        // Print a static greeting message to the console.  
        System.out.println("Static Greeting: Welcome!");  
    }  
    // Abstract method to be implemented by classes for executing a custom action with a string input.  
    void executeCustomAction(String input);  
}  
// Class that implements the MessageDisplay interface to execute actions.  
public class Main implements MessageDisplay {  
    // Main method - the entry point of the program.  
    public static void main(String[] args) {  
        // Create an instance of the Main class.  
        Main executor = new Main();  
        // Call the static method from the MessageDisplay interface to show the static message.  
        MessageDisplay.showStaticMessage();  
        // Call the implemented abstract method with a custom message.  
        executor.executeCustomAction("Overridden Message: Action Completed.");  
    }  
    // Implementation of the abstract method from the MessageDisplay interface.  
    @Override  
    public void executeCustomAction(String inputData) {  
        // Print the input data to the console.  
        System.out.println(inputData);  
    }  
}  
Compile and Run

Output:

Static Greeting: Welcome!
Overridden Message: Action Completed.

IO Enhancements

Java 8 introduced several enhancements to the Input/Output (IO) and New Input/Output (NIO) frameworks, focusing primarily on improving the ease of use and efficiency of file and stream handling. These enhancements are part of the java.nio package and include the following notable features:

Stream API Enhancements for IO

  • list(Path dir): This method returns a lazily filled stream of Path objects, where each element represents a directory entry in the specified directory (dir).
  • lines(Path path): This method reads all lines from a file specified by the path parameter and returns them as a Stream<String>. Each element of the stream represents a line of text from the file.
  • find(): This method is used to search for files in the file tree rooted at a provided starting file. It returns a stream filled with Path objects representing the files found during the search. However, you haven't provided the complete method signature, so it's unclear how this method is used.
  • lines(): This method returns a stream containing all of the lines from the BufferedReader's input source. Each element of the stream represents a line of text from the input source. This method is useful for processing text data in a file or from any other input source.

Type and Repeating Annotations

Type Annotations

Type Annotations augment Java's type system by allowing annotations to be used in any context where a type is used. This enhancement enables developers to convey more information to the compiler, aiding in error detection and prevention at compile time. For example, to safeguard against NullPointerException, a variable declaration can be annotated to ensure that it never holds a null value:

Some other examples of type annotations are:

Ensuring a list does not contain null elements:

Specifying that elements of a list must not be null:

Declaring that an array should only contain non-negative integers:

Marking a file as encrypted for security purposes:

Indicating that a connection is open and should be managed accordingly:

Specifying an exception thrown under a particular condition, such as division by zero:

Repeating Annotations

Java 8 introduced the concept of Repeating Annotations, allowing you to apply the same annotation multiple times to a single element in your code. This feature is particularly useful for situations where you need to repeatedly annotate an element with the same annotation to convey multiple pieces of information or apply multiple settings.

To use Repeating Annotations, Java requires two key pieces:

1. Declare a Repeatable Annotation Type

First, we declare the @Review annotation and mark it as repeatable using the @Repeatable meta-annotation. The value of @Repeatable is set to the container annotation type, which in this case is Reviews.

Syntax:

In this example, @Review annotations can include the reviewer's name, the date of the review, and a comment.

2. Declare the Containing Annotation Type

We define the Reviews container annotation. It must have a value element that returns an array of the repeatable annotation type (Review[]). This container is used to hold all the @Review annotations applied to the same element.

Syntax:

Example

In this example, repeatable annotations are defined and applied multiple times to a class, and then accessed at runtime using a container annotation to retrieve and display all assigned roles.

Java

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
import java.lang.annotation.Repeatable;  
// Define the repeatable annotation type  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.TYPE) // Apply to class level  
@Repeatable(Roles.class)  
@interface Role {  
    String value();  
}  
// Define the container annotation for the repeatable annotation  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.TYPE) // Apply to class level  
@interface Roles {  
    Role[] value();  
}   
// Use the repeating annotation on a class  
@Role("Developer")  
@Role("Lead")  
@Role("Manager")  
public class Main {  
    public static void main(String[] args) throws NoSuchMethodException {  
        // Access and print the repeated annotations  
        if (Main.class.isAnnotationPresent(Roles.class)) {  
            Roles rolesAnnotation = Main.class.getAnnotation(Roles.class);  
            for (Role role : rolesAnnotation.value()) {  
                System.out.println("Role: " + role.value());  
            }  
        } else {  
            System.out.println("No Roles Annotation present.");  
        }  
    }  
}  
Compile and Run

Output:

Role: Developer
Role: Lead
Role: Manager

Default Methods

Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with the default keyword are known as default methods. These methods are non-abstract methods and can have a method body.

To read more Default Methods

Example

In this example, default methods in an interface are demonstrated, where a class overrides one default method while inheriting and using another without modification.

Java

interface Vehicle {  
    // Abstract method  
    String getBrand();  
    // Default method  
    default void turnAlarmOn() {  
        System.out.println("The vehicle alarm is now on.");  
    }  
    // Another default method  
    default void turnAlarmOff() {  
        System.out.println("The vehicle alarm is now off.");  
    }  
}  
class Car implements Vehicle {  
    private String brand;  
    Car(String brand) {  
        this.brand = brand;  
    }  
    @Override  
    public String getBrand() {  
        return brand;  
    }  
    // The class can choose to override a default method  
    @Override  
    public void turnAlarmOn() {  
        System.out.println("The car alarm is now on.");  
    }  
}  
public class Main {  
    public static void main(String[] args) {  
        Vehicle myCar = new Car("Tesla");  
        System.out.println("Brand: " + myCar.getBrand());  
        myCar.turnAlarmOn(); // Overridden method  
        myCar.turnAlarmOff(); // Inherited default method  
    }  
}  
Compile and Run

Output:

Brand: Tesla
The car alarm is now on.
The vehicle alarm is now off

Nashorn JavaScript Engine

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs that is used to execute JavaScript code.

We can execute JavaScript code by two ways:

  1. By Using jjs command-line tool, and
  2. By embedding into Java source code.

Example

In this example, the Nashorn JavaScript engine is used to execute JavaScript code within a Java program, including evaluating expressions and calling JavaScript functions.

Java

import javax.script.ScriptEngine;  
import javax.script.ScriptEngineManager;  
import javax.script.ScriptException;  
public class Main {  
    public static void main(String[] args) {  
        // Create a script engine manager  
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();  
        // Obtain a Nashorn script engine instance  
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");  
        try {  
            // Evaluate JavaScript code from String  
            nashorn.eval("print('Hello, Nashorn');");  
            // Evaluate JavaScript code that returns a value  
            Object result = nashorn.eval("10 + 2");  
            System.out.println("Result of 10 + 2: " + result);  
            // Define a JavaScript function and call it from Java  
            nashorn.eval("function sum(a, b) { return a + b; }");  
            Object sumResult = nashorn.eval("sum(10, 15);");  
            System.out.println("Result of sum(10, 15): " + sumResult);  
        } catch (ScriptException e) {  
            System.err.println("ScriptException: " + e.getMessage());  
        }  
    }  
}  
Compile and Run

Output:

Hello, Nashorn
Result of 10 + 2: 12
Result of sum(10, 15): 25

StringJoiner Class

Java added a new final class, StringJoiner, in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, we can create a string by passing delimiters like a comma(,), hyphen(-), etc.

To read more StringJoiner Class

Example

Java

import java.util.StringJoiner;  
public class Main {  
    public static void main(String[] args) {  
        // Create a StringJoiner with a delimiter, prefix, and suffix  
        StringJoiner joiner = new StringJoiner(", ", "[", "]");  
        // Add strings to the StringJoiner  
        joiner.add("Apple");  
        joiner.add("Banana");  
        joiner.add("Cherry");  
        joiner.add("Date");  
        // Convert the StringJoiner to String and print the result  
        String result = joiner.toString();  
        System.out.println(result);  
    }  
}  
Compile and Run

Output:

[Apple, Banana, Cherry, Date]

Collectors Class

Collectors is a final class that extends the Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

To read more Collectors Class

Example

In this example, the Collectors class is used with the Stream API to perform operations like collecting elements into a list, grouping data, joining strings, and counting distinct values.

Java

import java.util.Arrays;  
import java.util.List;  
import java.util.Map;  
import java.util.stream.Collectors;  
public class Main {  
    public static void main(String[] args) {  
        // Example list of people's names  
        List names = Arrays.asList("John", "Sara", "Mark", "Sara", "Chris", "Paula");  
        // Collecting into a List  
        List nameList = names.stream().collect(Collectors.toList());  
        System.out.println("Names List: " + nameList);  
        // Grouping names by the first letter  
        Map> namesByFirstLetter = names.stream()  
            .collect(Collectors.groupingBy(name -> name.charAt(0)));  
        System.out.println("Names Grouped by First Letter: " + namesByFirstLetter);  
        // Joining names into a single string separated by commas  
        String allNames = names.stream().collect(Collectors.joining(", "));  
        System.out.println("All Names Joined: " + allNames);  
        // Counting the distinct names  
        long distinctNameCount = names.stream().distinct().count();  
        System.out.println("Distinct Names Count: " + distinctNameCount);  
    }  
}  
Compile and Run

Output:

Names List: [John, Sara, Mark, Sara, Chris, Paula]
Names Grouped by First Letter: {J=[John], S=[Sara, Sara], M=[Mark], C=[Chris], P=[Paula]}
All Names Joined: John, Sara, Mark, Sara, Chris, Paula
Distinct Names Count: 5

Stream API

Java 8 java.util.stream package consists of classes, interfaces, and an enum to allow functional-style operations on the elements. It performs lazy computation. So, it executes only when it is required.

To read more Stream API

Example

In this example, the Stream API is used to process a list by filtering even numbers, transforming them into their squares, and collecting the results into a new list.

Java

import java.util.Arrays;  
import java.util.List;  
import java.util.stream.Collectors;  
public class Main {  
    public static void main(String[] args) {  
        // A list of integers  
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  
        // Use Stream API to filter, map, and collect operations  
        List evenSquares = numbers.stream()  
                                           .filter(n -> n % 2 == 0) // Filter even numbers  
                                           .map(n -> n * n) // Map to their squares  
                                           .collect(Collectors.toList()); // Collect results into a list  
        // Print the resulting list  
        System.out.println(evenSquares);  
    }  
}  
Compile and Run

Output:

[4, 16, 36, 64, 100]

Stream filter() Method

Java stream provides a method filter() to filter stream elements on the basis of a given predicate. Suppose we want to get only even elements of your list, we can do this easily with the help of the filter() method.

This method takes a predicate as an argument and returns a stream of resulting elements.

Syntax:

The filter method accepts a Predicate<T> as its argument. A Predicate<T> is a functional interface specifying a single boolean-valued method with one argument of type T.

To read more Stream Filter

Example

In this example, the Stream API is used to filter a list of names and collect only those that start with the letter "J" into a new list.

Java

import java.util.Arrays;  
import java.util.List;  
import java.util.stream.Collectors;  
public class Main {  
    public static void main(String[] args) {  
        // A list of names  
        List names = Arrays.asList("John", "Sara", "Mark", "Jennifer", "Paul", "Jane");  
        // Use Stream API to filter names that start with "J"  
        List namesStartingWithJ = names.stream()  
                                               .filter(name -> name.startsWith("J")) // Filter names starting with "J"  
                                               .collect(Collectors.toList()); // Collect results into a list  
        // Print the filtered list  
        System.out.println(namesStartingWithJ);  
    }  
}  
Compile and Run

Output:

[John, Jennifer, Jane]

Java Base64 Encoding and Decoding

Java provides a class Base64 to deal with encryption and decryption. You need to import java.util.Base64 class in your source file to use its methods.

This class provides three different encoders and decoders to encrypt information at each level.

To read more Base64 Encoding and Decoding

Example

In this example, the Base64 class is used to encode and decode a string in different formats, including basic, URL-safe, and MIME encoding.

Java

import java.util.Base64;  
public class Main {  
    public static void main(String[] args) {  
        // Original String  
        String originalString = "Hello, World!";  
        // Encode using basic encoder  
        String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());  
        System.out.println("Encoded String (Basic) : " + encodedString);  
        // Decode the base64 encoded string  
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);  
        String decodedString = new String(decodedBytes);  
        System.out.println("Decoded String : " + decodedString);  
        // URL and Filename safe encoding  
        String urlEncodedString = Base64.getUrlEncoder().encodeToString(originalString.getBytes());  
        System.out.println("Encoded String (URL) : " + urlEncodedString);  
        // MIME encoder example  
        String mimeEncodedString = Base64.getMimeEncoder().encodeToString(originalString.getBytes());  
        System.out.println("Encoded String (MIME) : " + mimeEncodedString);  
    }  
}  
Compile and Run

Output:

Encoded String (Basic) : SGVsbG8sIFdvcmxkIQ==
Decoded String : Hello, World!
Encoded String (URL) : SGVsbG8sIFdvcmxkIQ==
Encoded String (MIME) : SGVsbG8sIFdvcmxkIQ==

Java Parallel Array Sorting

Java provides a new additional feature in the Arrays class, which is used to sort array elements in parallel. The parallelSort() method has been added to java.util.Arrays class that uses the JSR 166 Fork/Join parallelism common pool to provide sorting of arrays. It is an overloaded method.

To read more Parallel Array Sorting

Example

In this example, Arrays.parallelSort() is used to efficiently sort both primitive and object arrays, including sorting with a custom comparator for reverse order.

Java

import java.util.Arrays;  
import java.util.Comparator;  
public class Main {  
    public static void main(String[] args) {  
        // Parallel sorting for an array of primitives  
        int[] numbers = {9, 3, 1, 5, 13, 12, 7, 4, 11, 6};  
        System.out.println("Original array: " + Arrays.toString(numbers));  
        Arrays.parallelSort(numbers);  
        System.out.println("Sorted array: " + Arrays.toString(numbers));  
        // Parallel sorting for an array of objects with a custom comparator  
        String[] fruits = {"Peach", "Apple", "Orange", "Banana", "Grape", "Pear"};  
        System.out.println("\nOriginal array: " + Arrays.toString(fruits));  
        // Using a lambda expression for the comparator to sort in reverse alphabetical order  
        Arrays.parallelSort(fruits, Comparator.reverseOrder());  
        System.out.println("Sorted array in reverse order: " + Arrays.toString(fruits));  
    }  
}
Compile and Run

Output:

Original array: [9, 3, 1, 5, 13, 12, 7, 4, 11, 6]
Sorted array: [1, 3, 4, 5, 6, 7, 9, 11, 12, 13]
Original array: [Peach, Apple, Orange, Banana, Grape, Pear]
Sorted array in reverse order: [Pear, Peach, Orange, Grape, Banana, Apple]

JDBC Enhancements

Java Database Connectivity (JDBC) is a Java API that manages connecting to a database, executing queries and commands, and handling result sets obtained from the database.

JDBC Improvements

1) Removal of the JDBC-ODBC Bridge

Starting with Java 8, the JDBC-ODBC Bridge, which enabled JDBC applications to access databases via ODBC drivers, has been removed. This decision encourages the use of pure JDBC drivers for improved performance, reliability, and access to modern database features.

2) New Features in JDBC 4.2

Java 8 introduced JDBC 4.2, bringing several significant enhancements to the JDBC API, aimed at making database interaction more flexible, powerful, and secure. Here's a brief overview of the key additions:

1. Addition of REF_CURSOR Support

JDBC 4.2 added support for the SQL REF CURSOR type. This allows JDBC to handle cursor types returned by database stored procedures and functions, facilitating easier retrieval of complex data structures.

2. Addition of java.sql.DriverAction Interface

This interface provides a mechanism for JDBC drivers to perform cleanup actions when the driver is deregistered. It enhances the driver management, especially in scenarios involving dynamic loading and unloading of JDBC drivers.

3. Security Check on deregisterDriver Method in DriverManager Class

JDBC 4.2 introduced a security check within the DriverManager.deregisterDriver(Driver driver) method. This ensures that only the caller who registered a driver can deregister it, preventing unauthorized deregistration and enhancing security.

4. Addition of the java.sql.SQLType Interface

This interface serves as the base for JDBC types, providing a standard way to identify SQL types by name and to map them to JDBC Types. It's a move towards a more object-oriented approach in handling SQL types.

5. Addition of the java.sql.JDBCType Enum

Accompanying the SQLType interface, the JDBCType enum implements this interface, providing a convenient enumeration of JDBC types. This facilitates clearer and more type-safe handling of SQL data types in JDBC operations.

6. Support for Large Update Counts

JDBC 4.2 extends the API to support large update counts, accommodating SQL operations that affect a large number of rows, beyond what can be represented by an int. Methods like Statement.getLargeUpdateCount and Statement.executeLargeUpdate are examples.

7. Changes to Existing Interfaces

Several interfaces received updates to accommodate new features, such as the support for large update counts and the new Date and Time API. These changes ensure that JDBC remains compatible with the latest SQL standards and Java features.

8. RowSet 1.2 Enhancements

JDBC RowSet 1.2 received enhancements that improve its functionality and integration with the JDBC 4.2 features. These include better support for the java.sql.SQLType and the new Date and Time API, among others.

Java JDBC DriverAction

The java.sql.DriverAction interface in Java 8's JDBC 4.2 provides a way for JDBC drivers to define cleanup actions upon deregistration, enhancing resource management and security.

DriverAction Method

MethodDescription
void deregister()Called by DriverManager.deregisterDriver(Driver) to notify the JDBC driver that it has been de-registered. This method should contain the necessary clean-up logic to release resources and perform any finalization needed by the driver upon deregistration.

Java JDBC SQLType

MethodDescription
String getName()Returns the SQL type name as a String, typically corresponding to the SQL type name used in databases.
String getVendor()*Returns the name of the vendor for the custom SQL type, applicable for types that are specific to a particular database vendor.
Integer getVendorTypeNumber()Returns an integer value representing the vendor-specific SQL type code, useful for handling database-specific types.

Java JDBCType

`JDBCType` is an enumeration that specifies constants for identifying generic SQL types, known as JDBC types. This enumeration extends `java.lang.Enum` and implements the `java.sql.SQLType` interface.

JDBCType Fields

The following table listed the JDBCType enumeration constants along with their descriptions, providing insights into the generic SQL types they represent:

Enum ConstantDescription
ARRAYRepresents an array of values in a SQL database.
BIGINTRepresents a large integer value, typically mapping to a 64-bit integer.
BINARYRepresents an array of bytes, for binary values.
BITRepresents a single bit value, often used for boolean values in SQL databases.
BLOBRepresents a Binary Large Object stored as a collection of binary data.
BOOLEANRepresents a boolean value, for true/false data.
CHARRepresents a fixed-length character string.
CLOBRepresents a Character Large Object, for large text data.
DATALINKRepresents a link to data outside of a SQL database.
DATERepresents a date value (year, month, day).
DECIMALRepresents a numeric value with fixed precision and scale.
DISTINCTRepresents a distinct type, a unique data type defined in SQL.
DOUBLERepresents a double precision floating point number.
FLOATRepresents a floating point number.
INTEGERRepresents an integer value, typically mapping to a 32-bit integer.
JAVA_OBJECTRepresents an object in the Java programming language that is stored in the database.
LONGNVARCHARRepresents a long string value in the National character set.
LONGVARBINARYRepresents a long array of bytes for binary values.
LONGVARCHARRepresents a long string of characters.
NCHARRepresents a fixed-length string that uses the National character set.
NCLOBRepresents a Large Object of National characters.
NULLSpecial type representing a NULL SQL type.
NUMERICRepresents a numeric value with precision and scale.
NVARCHARRepresents a variable-length string that uses the National character set.
OTHERRepresents a type that is database-specific and not defined by JDBC.
REALRepresents a single precision floating point number.
REFRepresents a reference to an SQL structured type instance in the database.
REF_CURSORRepresents a cursor or a reference to a cursor.
ROWIDRepresents a row id used by SQL databases.
SMALLINTRepresents a small integer value.
SQLXMLRepresents SQL XML values.
STRUCTRepresents an SQL structured type.
TIMERepresents a time value (hour, minute, second).
TIME_WITH_TIMEZONERepresents a time value with timezone information.
TIMESTAMPRepresents a timestamp (date and time).
TIMESTAMP_WITH_TIMEZONERepresents a timestamp with timezone information.
TINYINTRepresents a very small integer value.
VARBINARYRepresents a variable array of bytes for binary values.
VARCHARRepresents a variable-length character string.

JDBCType Methods

MethodDescriptionReturn Type
getName()Returns the SQLType name that represents a SQL data type.String
getVendor()Returns the name of the vendor that supports this data type.String
getVendorTypeNumber()Returns the vendor-specific type number for the data type.Integer
valueOf(int type)Returns the JDBCType that corresponds to the specified java.sql.Types value. Throws IllegalArgumentException if this enum type has no constant with the specified Types value.JDBCType
valueOf(String name)Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. Throws IllegalArgumentException if no constant with the specified name, and NullPointerException if the argument is null.JDBCType
values()Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants.JDBCType[]

Java 8 Security Enhancements

1) The Java Secure Socket Extension(JSSE) provider enables the protocols Transport Layer Security (TLS) 1.1 and TLS 1.2 by default on the client side.

2) A improved method AccessController.doPrivileged has been added which enables code to assert a subset of its privileges, without preventing the full traversal of the stack to check for other permissions.

3) Advanced Encryption Standard (AES) and Password-Based Encryption (PBE) algorithms, such as PBEWithSHA256AndAES_128 and PBEWithSHA512AndAES_256 has been added to the SunJCE provider.

4) Java Secure Socket Extension (SunJSSE) has enabled Server Name Indication (SNI) extension for client applications by default in JDK 7 and JDK 8 supports the SNI extension for server applications. The SNI extension is a feature that extends the SSL/TLS protocols to indicate what server name the client is attempting to connect to during handshaking.

5) The SunJSSE is enhanced to support Authenticated Encryption with Associated Data (AEAD) algorithms. The Java Cryptography Extension (SunJCE) provider is enhanced to support AES/GCM/NoPadding cipher implementation as well as Galois/Counter Mode (GCM) algorithm parameters.

6) A new command flag -importpassword is added to the keytool utility. It is used to accept a password and store it securely as a secret key. Classes such as java.security.DomainLoadStoreParameter and java.security.PKCS12Attribute is added to support DKS keystore type.

7) In JDK 8, the cryptographic algorithms have been enhanced with the SHA-224 variant of the SHA-2 family of message-digest implementations.

8) Enhanced support for NSA Suite B Cryptography, which includes:

  • OID registration for NSA Suite B cryptography algorithms
  • Support for 2048-bit DSA key pair generation and additional signature algorithms for 2048-bit DSA keys, such as SHA224withDSA and SHA256withDSA.
  • Lifting of the key size restriction from 1024 to 2048 for the Diffie-Hellman (DH) algorithm.

9) SecureRandom class provides the generation of cryptographically strong random numbers which is used for private or public keys, ciphers and signed messages. The getInstanceStrong() method was introduced in JDK 8, which returns an instance of the strongest SecureRandom. It should be used when you need to create RSA private and public key. SecureRandom includes following other changes:

  • Two new implementations has introduced for UNIX platforms, which provide blocking and non-blocking behavior.

10) A new PKIXRevocationChecker class is included, which checks the revocation status of certificates with the PKIX algorithm. It supports best effort checking, end-entity certificate checking, and mechanism-specific options.

11) The Public Key Cryptography Standards 11 (PKCS) has been expanded to include 64-bit support for Windows.

12) Two new rcache types are added to Kerberos 5. Type none means no rcache at all, and type dfl means the DFL style file-based rcache. Also, the acceptor requested subkey is now supported. They are configured using the sun.security.krb5.rcache and sun.security.krb5.acceptor.subkey system properties.

13) In JDK 8, Kerberos 5 protocol transition and constrained delegation are supported within the same realm.

14) Java 8 has disabled weak encryption by default. The DES-related Kerberos 5 encryption types are not supported by default. These encryption types can be enabled by adding allow_weak_crypto=true in the krb5.conf file.

15) You can set the server name to null to denote an unbound server. It means a client can request the service using any server name. After a context is established, the server can retrieve the name as a negotiated property with the key name SASL.BOUND_SERVER_NAME.

16) Java Native Interface (JNI) bridge to native Java Generic Security Service (JGSS) is now supported on Mac OS X. You can set the system property sun.security.jgss.native to true to enable it.

17) A new system property, jdk.tls.ephemeralDHKeySize is defined to customize the ephemeral DH key sizes. The minimum acceptable DH key size is 1024 bits, except for exportable cipher suites or legacy mode (jdk.tls.ephemeralDHKeySize=legacy).

18) Java Secure Socket Extension (JSSE) provider honors the client's cipher suite preference by default. However, the behavior can be changed to respect the server's cipher suite preference by calling SSLParameters.setUseCipherSuitesOrder(true) over the server.

Java 8 Tools Enhancements

1) A jjs command is introduced, which invokes the Nashorn engine either in interactive shell mode or to interpret script files.

2) The java command is capable of launching JavaFX applications, provided that the JavaFX application is packaged correctly.

3) The java command man page (both nroff and HTML) has been completely reworked. The advanced options are now divided into Runtime, Compiler, Garbage Collection, and Serviceability, according to the area that they affect. Several previously missing options are now described. There is also a section for options that were deprecated or removed since the previous release.

4) The new jdeps command-line tool allows the developer to analyze class files to determine package-level or class-level dependencies.

5) You can access diagnostic commands remotely, which were previously accessible only locally via the jcmd tool. Remote access is provided using the Java Management Extensions (JMX), so diagnostic commands are exposed to a platform MBean registered to the platform MBean server. The MBean is the com.sun.management.DiagnosticCommandMBean interface.

6) A new option -tsapolicyid is included in the jarsigner tool, which enables you to request a signed time stamp from a Time Stamping Authority and attach it to a signed JAR file.

7) The names of formal parameters of methods and constructors are accessed through a new method added to `java.lang.reflect.Executable` called `getParameters`. Though, by default, the wrapped file corresponds to a `.class` file without these parameters’ names. In order to include them and to be able to do retrieval via the Reflection API, you can compile the code using the `javac` compiler option `-parameters`.

8) The type rules for binary comparisons in the Java Language Specification (JLS) Section 15.21 will now be correctly enforced by javac.

9) In this release, the apt tool and its associated API contained in the package com.sun.mirror have been removed.

Javadoc Enhancements

In Java SE 8, the following new APIs were added to the Javadoc tool.

  • A new DocTree API introduces a scanner which enables you to traverse source code that is represented by an abstract syntax tree. This extends the Compiler Tree API to provide structured access to the content of javadoc comments.
  • The javax.tools package contains classes and interfaces that enable you to invoke the Javadoc tool directly from a Java application, without executing a new process.
  • The "Method Summary" section of the generated documentation of a class or interface has been restructured. Method descriptions in this section are grouped by type. By default, all methods are listed. You can click a tab to view methods of a particular type (static, instance, abstract, concrete, or deprecated, if they exist in the class or interface).
  • The javadoc tool now has support for checking the content of javadoc comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated by javadoc. The feature is enabled by default, and can also be controlled by the new -Xdoclint option.

Pack200 Enhancements

The Java class file format has been updated because of JSR 292, which Supports Dynamically Typed Languages on the Java Platform.

The Pack200 engine has been updated to ensure that Java SE 8 class files are compressed effectively. Now, it can recognize constant pool entries and new bytecodes introduced by JSR 292. As a result, compressed files created with this version of the pack200 tool will not be compatible with older versions of the unpack200 tool.

Java 8 I/O Enhancements

In Java 8, there are several improvements to the java.nio.charset.Charset and extended charset implementations. It includes the following:

  • A New SelectorProvider which may improve performance or scalability for server. The /dev/poll SelectorProvider continues to be the default. To use the Solaris event port mechanism, run with the system property java.nio.channels.spi.Selector set to the value sun.nio.ch.EventPortSelectorProvider.
  • The size of <JDK_HOME>/jre/lib/charsets.jar file is decreased.
  • Performance has been improvement for the java.lang.String(byte[], ∗) constructor and the java.lang.String.getBytes() method.

Java 8 Networking Enhancements

1) A new class java.net.URLPermission has been added. It represents a permission for accessing a resource defined by a given URL.

2) A package jdk.net has been added which contains platform specific socket options and a mechanism for setting these options on all of the standard socket types. The socket options are defined in jdk.net.ExtendedSocketOptions.

3) In class HttpURLConnection, if a security manager is installed, and if a method is called which results in an attempt to open a connection, the caller must possess either a "connect"SocketPermission to the host/port combination of the destination URL or a URLPermission that permits this request.

If automatic redirection is enabled, and this request is redirected to another destination, the caller must also have permission to connect to the redirected host/URL.

Java 8 Concurrency Enhancements

The java.util.concurrent package added two new interfaces and four new classes.

java.util.concurrent Interfaces

InterfaceDescription
public static interface CompletableFuture.AsynchronousCompletionTaskIt is a marker interface that is used to identify asynchronous tasks produced by async methods. It may be useful for monitoring, debugging, and tracking asynchronous activities.
public interface CompletionStage<T>It creates a stage of a possibly asynchronous computation that performs an action or computes a value when another CompletionStage completes.

java.util.concurrent Classess

ClassDescription
public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T>It is a Future that may be explicitly completed, and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
public static class ConcurrentHashMap.KeySetView<K,V> extends Object implements Set<K>, SerializableIt is a view of a ConcurrentHashMap as a Set of keys, in which additions may optionally be enabled by mapping to a common value.
public abstract class CountedCompleter<T> extends ForkJoinTask<T>A ForkJoinTask with a completion action performed when triggered, and there are no remaining pending actions.
public class CompletionException extends RuntimeExceptionIt throws an exception when an error or other exception is encountered in the course of completing a result or task.

New Methods in java.util.concurrent.ConcurrentHashMap Class

ConcurrentHashMap class introduces several new methods in its latest release. It includes various forEach methods (forEach, forEachKey, forEachValue, and forEachEntry), search methods (search, searchKeys, searchValues, and searchEntries) and a large number of reduction methods (reduce, reduceToDouble, reduceToLong etc.). Other miscellaneous methods (mappingCount and newKeySet) have been added as well.

New Classes in java.util.concurrent.atomic

Latest release introduces scalable, updatable, variable support through a small set of new classes DoubleAccumulator, DoubleAdder, LongAccumulator andLongAdder. It internally employ contention-reduction techniques that provide huge throughput improvements as compared to Atomic variables.

ClassDescription
public class DoubleAccumulator extends Number implements SerializableIt is used for one or more variables that together maintain a running double value updated using a supplied function.
public class DoubleAdder extends Number implements SerializableIt is used for one or more variables that together maintain an initially zero double sum.
public class LongAccumulator extends Number implements SerializableIt is used for one or more variables that together maintain a running long value updated using a supplied function.
public class LongAdder extends Number implements SerializableIt is used for one or more variables that together maintain an initially zero long sum.

New Methods in java.util.concurrent.ForkJoinPool Class

This class has added two new methods, getCommonPoolParallelism() and commonPool(), which return the targeted parallelism level of the common pool, or the common pool instance, respectively.

MethodDescription
public static ForkJoinPool commonPool()It returns the common pool instance.
public static int getCommonPoolParallelism()It returns the targeted parallelism level of the common pool.

New java.util.concurrent.locks.StampedLock Class

A new class StampedLock, is added, which is used to add a capability-based lock with three modes for controlling read/write access (writing, reading, and optimistic reading). This class also supports methods that conditionally provide conversions across the three modes.

ClassDescription
public class StampedLock extends Object implements SerializableThis class represents a capability-based lock with three modes for controlling read/write access.

Java API for XML Processing (JAXP) 1.6 Enhancements

In Java 8, the Java API is added for XML Processing (JAXP) 1.6. It requires the use of the service provider loader facility, which is defined by java.util.ServiceLoader to load services from service configuration files.

The rationale for this is to allow for future modularization of the Java SE platform, where service providers may be deployed by means other than JAR files and perhaps without the service configuration files.

Java Virtual Machine Enhancements

The verification of invokespecial instructions has been tightened so that only an instance initialization method in the current class or its direct superclass may be invoked.

Java Mission Control 5.3 is included in Java 8

Java Mission Control (JMC) is an advanced set of tools that enables efficient and detailed data analysis and delivers advanced, unobtrusive Java monitoring and management. JMC provides sections for common analysis areas such as code performance, memory and latency.

Babel Language Packs in Japanese and Simplified Chinese are now included by default in the Java Mission Control that is included in the JDK 8.

Java 8 Internationalization Enhancements

1) Unicode Enhancements

The JDK 8 includes support for Unicode 6.2.0. It contains the following features.

  • 733 new characters, including Turkish the Lira sign.
  • 7 new scripts:
    1. Meroitic Hieroglyphs
    2. Meroitic Cursive
    3. Sora Sompeng
    4. Chakma
    5. Sharada
    6. Takri
    7. Miao
  • 11 new blocks: including 7 blocks for the new scripts listed above and 4 blocks for the following existing scripts:
  • Arabic Extended-A
  • Sundanese Supplement
  • Meetei Mayek Extensions
  • Arabic Mathematical Alphabetical Symbols

Adoption of Unicode CLDR Data and the java.locale.providers System Property

The Unicode Consortium has released the Common Locale Data Repository (CLDR) project to "support the world's languages, with the largest and most extensive standard repository of locale data available." The CLDR is becoming the defacto standard for locale data. The CLDR's XML-based locale data has been incorporated into the JDK 8 release, it is disabled by default.

There are four distinct sources for locale data:

  • CLDR represents the locale data provided by the Unicode CLDR project.
  • HOST represents the current user's customization of the underlying operating system's settings. It works only with the user's default locale, and the customizable settings may vary depending on the OS, but primarily Date, Time, Number, and Currency formats are supported.
  • SPI represents the locale-sensitive services implemented in the installed SPI providers.
  • JRE represents the locale data that is compatible with the prior JRE releases.

To select the desired locale data source, use the java.locale.providers system property. Listing the data sources in the preferred order. For example: java.locale.providers=HOST,SPI,CLDR,JRE. The default behavior is equivalent to the following setting: java.locale.providers=JRE,SPI

Java 8 New Calendar and Locale APIs

The JDK 8 includes two new classes, several new methods, and a new return value for an existing static method.

Two new abstract classes for service providers are added to the java.util.spi package.

ClassDescription
public abstract class CalendarDataProvider extends LocaleServiceProviderIt is an abstract class for service providers that provide locale-dependent Calendar parameters.
public abstract class CalendarNameProvider extends LocaleServiceProviderIt is an abstract class for service providers that provide localized string representations (display names) of Calendar field values.

A static method is now able to recognize Locale.UNICODE_LOCALE_EXTENSION for the numbering system.

MethodDescription
public static final DecimalFormatSymbols getInstance(Locale locale)It is used to get the DecimalFormatSymbols instance for the specified locale. This method provides access to DecimalFormatSymbols instances for locales supported by the Java runtime itself as well as for those supported by installed DecimalFormatSymbolsProvider implementations. It throws NullPointerException if locale is null.

Added New methods in Calender API:

MethodDescription
public boolean isSupportedLocale(Locale locale)It returns true if the given locale is supported by this locale service provider. The given locale may contain extensions that should be taken into account for the support determination. It is define in java.util.spi.LocaleServiceProvider class
public String getCalendarType()It returns the calendar type of this Calendar. Calendar types are defined by the Unicode Locale Data Markup Language (LDML) specification. It is defined in java.util.Calendar class.

New style specifiers are added for the Calendar.getDisplayName and Calendar.getDisplayNames methods to determine the format of the Calendar name.

SpecifierDescription
public static final int SHORT_FORMATIt is a style specifier for getDisplayName and getDisplayNames indicating a short name used for format.
public static final int LONG_FORMATIt is a style specifier for getDisplayName and getDisplayNames indicating a long name used for format.
public static final int SHORT_STANDALONEIt is a style specifier for getDisplayName and getDisplayNames indicating a short name used independently, such as a month abbreviation as calendar headers.
public static final int LONG_STANDALONEIt is a style specifier for getDisplayName and getDisplayNames indicating a long name used independently, such as a month name as calendar headers.

Two new Locale methods for dealing with a locale's (optional) extensions.

MethodDescription
public boolean hasExtensions()It returns true if this Locale has any extensions.
public Locale stripExtensions()It returns a copy of this Locale with no extensions. If this Locale has no extensions, this Locale is returned itself.

Two new Locale.filter methods return a list of Locale instances that match the specified criteria, as defined in RFC 4647:

MethodDescription
public static List<Locale> filter(List<Locale.LanguageRange> priorityList,Collection<Locale> locales)It returns a list of matching Locale instances using the filtering mechanism defined in RFC 4647. This is equivalent to filter(List, Collection, FilteringMode) when mode is Locale.FilteringMode.AUTOSELECT_FILTERING.
public static List<Locale> filter(List<Locale.LanguageRange> priorityList,Collection<Locale> locales, Locale.FilteringMode mode)It returns a list of matching Locale instances using the filtering mechanism defined in RFC 4647.

Two new Locale.filterTags methods return a list of language tags that match the specified criteria, as defined in RFC 4647.

MethodDescription
public static List<String> filterTags(List<Locale.LanguageRange> priorityList, Collection<String> tags)It returns a list of matching languages tags using the basic filtering mechanism defined in RFC 4647. This is equivalent to filterTags(List, Collection, FilteringMode) when mode is Locale.FilteringMode.AUTOSELECT_FILTERING.
public static List<String> filterTags(List<Locale.LanguageRange> priorityList, Collection<String> tags, Locale.FilteringMode mode)It returns a list of matching languages tags using the basic filtering mechanism defined in RFC 4647.

Two new lookup methods return the best-matching locale or language tag using the lookup mechanism defined in RFC 4647.

MethodDescription
public static Locale lookup(List<Locale.LanguageRange> priorityList, Collection<Locale> locales)It returns a Locale instance for the best-matching language tag using the lookup mechanism defined in RFC 4647.
Public static String lookupTag(List<Locale.LanguageRange> priorityList,Collection<String> tags)It returns the best-matching language tag using the lookup mechanism defined in RFC 4647.

Other Java 8 Version Enhancements

Enhancements in JDK 8u5

1) The frequency at which the security prompts are shown for an application has been reduced.

Enhancements in JDK 8u11

1) An option to suppress offers from sponsors when the JRE is installed or updated is available in the Advanced tab of the Java Control Panel.

2) The Entry-Point attribute can be included in the JAR file manifest to identify one or more classes as a valid entry point for your RIA(Rich Internet application).

Enhancements in JDK 8u20

1) The javafxpackager tool has been renamed to javapackager. This tool has been enhanced with new arguments for self-contained application bundlers.

Following enhancements are related to the Java tool:

  • An experimental JIT compiler option related to Restricted Transactional Memory (RTM) has been added.
  • Several options related to string deduplication have been added.
  • Several options related to Advanced Encryption Standard (AES) intrinsics have been added.
  • Combinations of garbage collection options have been deprecated.

2) The Garbage Collection Tuning Guide has been added to the Java HotSpot Virtual Machine. It describes the garbage collectors included with the Java HotSpot VM and helps you to decide which garbage collector can best optimize the performance of your application, especially if it handles large amounts of data (multiple gigabytes), has many threads, and has high transaction rates.

Enhancements in JDK 8u31

1) In this release, the SSLv3 protocol is removed from the Java Control Panel Advanced options.

Enhancements in JDK 8u40

java Tool

1) The -XX:+CheckEndorsedAndExtDirs has been added because the endorsed-standards override mechanism (JDK-8065675) and the extension mechanism (JDK-8065702) have been deprecated. The option helps identify any existing uses of these mechanisms and is supported in JDK 7u80 and JDK 8u40.

2) Java Flight Recorder (JFR) offers a variety of ways to unlock commercial features and enable JFR during the runtime of an application.

It includes java command line options, such as jcmd diagnostic commands, and Graphical User Interface (GUI) controls within Java Mission Control. This flexibility enables you to provide the appropriate options at startup or interact with JFR later.

3) The option -XX:StartFlightRecording=parameter=value has a new parameter, dumponexit={true|false}, which specifies whether a dump file of JFR data should be generated when the JVM terminates in a controlled manner.

4) The options related to Restricted Transactional Memory (RTM) are no longer experimental. These options include -XX:RTMAbortRatio=abort_ratio, -XX:RTMRetryCount=number_of_retries, -XX:+UseRTMDeopt, and -XX:+UseRTMLocking.

5) In Java 8, Application Class Data Sharing (AppCDS) has been introduced. AppCDS extends CDS (Class Data Sharing) to enable classes from the standard extensions directories and the application class path to be placed in the shared archive. This is a commercial feature and is no longer considered experimental.

6) New options -XX:+ResourceManagement and -XX:ResourceManagementSampleInterval=value have been added.

7) Additional information about large pages has been added. Large Pages, also known as huge pages, are memory pages that are significantly larger than the standard memory page size. Large pages optimize processor Translation-Lookaside Buffers. The Linux options -XX:+UseHugeTLBFS, -XX:+UseSHM, and -XX:+UseTransparentHugePages have been documented.

8) The option -XX:ObjectAlignmentInBytes=alignment has been documented.

jjs Tool

1) The option --optimistic-types=[true|false] has been added. It enables or disables optimistic type assumptions with deoptimizing recompilation.

2) The option --language=[es5] has been added to the jjs tool. It specifies the ECMAScript language version.

javapackager Tool

1) New arguments are available for OS X bundlers. The mac.CFBundleVersion argument identifies the internal version number to be used.

2) The mac.dmg.simple argument indicates if DMG customization steps that depend on executing AppleScript code are skipped.

jcmd Tool

Jcmd tool is used to dynamically interact with Java Flight Recorder (JFR). You can use it to unlock commercial features, enable/start/stop flight recordings, and obtain various status messages from the system.

jstat Tool

The jstat tool has been updated with information about compressed class space, which is a special part of metaspace.

Virtual machine

The Scalable Native Memory Tracking HotSpot VM feature helps diagnose VM memory leaks and clarify users when memory leaks are not in the VM. Native Memory Tracker can be run without self-shutdown on large systems and without causing a significant performance impact beyond what is considered acceptable for small programs.

The following enhancements were introduced in JDK 8:

  • A new command, jjs, was added to the JDK. This command initiates the Nashorn JavaScript engine, allowing users to run JavaScript code either through an interactive shell or by executing script files.
  • Enhancements to the Java command now enable it to launch JavaFX applications, assuming the JavaFX application is correctly packaged. Guidance on how classes are located can be found in the relevant documentation.
  • Significant updates were made to the Java command's manual pages (available in both nroff and HTML formats), with a comprehensive reorganization of advanced options into categories such as Runtime, Compiler, Garbage Collection, and Serviceability, depending on their area of impact. This update includes descriptions of several options that were previously undocumented, along with a section dedicated to options that have been deprecated or removed in the current release.
  • JDK 8 introduces the jdeps command-line tool, designed to help developers analyze class files for dependencies at the package or class level.
  • Remote access to diagnostic commands, which were previously only available locally via the jcmd tool, has been enabled in JDK 8 through the Java Management Extensions (JMX). These diagnostic commands are now accessible through the com.sun.management.DiagnosticCommandMBean interface, with further details available in the jcmd tool documentation for different operating systems.
  • The jarsigner tool has been updated with a new -tsapolicyid option, allowing users to request and attach a timestamp from a Time Stamping Authority (TSA) to a signed JAR file.
  • JDK 8 allows the retrieval of formal parameter names of any method or constructor via the java.lang.reflect.Executable.getParameters method. To enable this feature, .class files must store formal parameter names, which can be achieved by compiling the source file with the -parameters option in the javac compiler.
  • The Java Language Specification (JLS) Section 15.21's type rules for binary comparisons have been strictly enforced by the javac compiler starting from JDK 8. This corrects previous behavior where javac accepted certain Object-primitive comparisons that did not align with JLS 15.21, marking them as type errors now.
  • JDK 8 sees the removal of the apt tool and its associated API in the com.sun.mirror package. Developers are advised to use the javac tool and the APIs in javax.annotation.processing and javax.lang.model packages for annotation processing instead.

References