Interview

15 Java 11 Interview Questions and Answers

Prepare for your next technical interview with this guide on Java 11, featuring common questions and detailed answers to enhance your understanding.

Java 11, as a long-term support (LTS) release, has become a cornerstone in modern software development. It brings a host of new features and enhancements, including improved performance, new APIs, and more streamlined coding practices. Java 11 is widely adopted in enterprise environments, making it a critical skill for developers aiming to work on robust, scalable applications.

This article offers a curated selection of interview questions designed to test your understanding of Java 11’s features and best practices. By familiarizing yourself with these questions and their answers, you’ll be better prepared to demonstrate your proficiency and problem-solving abilities in a technical interview setting.

Java 11 Interview Questions and Answers

1. What are the new methods added to the String class?

Java 11 introduced several new methods to the String class to enhance its functionality and make common string operations more convenient. These methods include:

  • isBlank(): Checks if the string is empty or contains only white space characters.
  • lines(): Returns a stream of lines extracted from the string, separated by line terminators.
  • strip(), stripLeading(), stripTrailing(): Removes white space from both ends, the beginning, or the end of the string, respectively.
  • repeat(int count): Repeats the string a specified number of times.
  • indent(int n): Adjusts the indentation of each line in the string by the specified number of spaces.
  • transform(Function f): Applies a function to the string and returns the result.

Example:

public class StringMethodsExample {
    public static void main(String[] args) {
        String str = "  Hello World  ";
        
        // isBlank()
        System.out.println(str.isBlank()); // false
        
        // lines()
        String multilineStr = "Hello\nWorld\nJava";
        multilineStr.lines().forEach(System.out::println);
        
        // strip(), stripLeading(), stripTrailing()
        System.out.println(str.strip()); // "Hello World"
        System.out.println(str.stripLeading()); // "Hello World  "
        System.out.println(str.stripTrailing()); // "  Hello World"
        
        // repeat(int count)
        System.out.println("Java".repeat(3)); // "JavaJavaJava"
        
        // indent(int n)
        System.out.println("Hello\nWorld".indent(4));
        
        // transform(Function<? super String, ? extends R> f)
        String result = str.transform(s -> s + " Transformed");
        System.out.println(result); // "  Hello World   Transformed"
    }
}

2. How do you create and send an HTTP request using the new HTTP Client API?

Java 11 introduced a new HTTP Client API that simplifies the process of creating and sending HTTP requests. This API is part of the java.net.http package and provides a more modern and flexible way to handle HTTP communication compared to the older HttpURLConnection.

The new HTTP Client API supports both synchronous and asynchronous operations, making it versatile for various use cases. It also supports HTTP/1.1 and HTTP/2, providing better performance and resource utilization.

Here is a concise example of how to create and send an HTTP GET request using the new HTTP Client API:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("https://api.example.com/data"))
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

3. Explain the concept of nest-based access control.

Nest-based access control in Java 11 allows nested classes to access each other’s private members directly. This feature is particularly useful for inner classes, static nested classes, and anonymous classes, as it simplifies the access control mechanism and improves encapsulation.

Example:

public class OuterClass {
    private String outerField = "Outer";

    class InnerClass {
        private String innerField = "Inner";

        private void accessOuter() {
            System.out.println(outerField); // Accessing private member of OuterClass
        }
    }

    private void accessInner() {
        InnerClass inner = new InnerClass();
        System.out.println(inner.innerField); // Accessing private member of InnerClass
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.accessInner();
        InnerClass inner = outer.new InnerClass();
        inner.accessOuter();
    }
}

4. What is the Epsilon garbage collector and when would you use it?

The Epsilon garbage collector, introduced in Java 11, is a no-op garbage collector, meaning it does not actually perform any memory reclamation. Its primary purpose is to provide a minimal overhead garbage collection implementation that can be used for performance testing, memory pressure testing, and VM interface testing.

Epsilon GC is designed to handle memory allocation without any automatic memory management. Once the Java heap is exhausted, the JVM will shut down. This makes it useful in scenarios where you want to measure the performance impact of garbage collection or when you need to test how your application behaves under memory pressure without the interference of garbage collection pauses.

Key characteristics of Epsilon GC include:

  • No memory reclamation: Epsilon GC does not reclaim memory, leading to predictable and consistent performance.
  • Minimal overhead: Since it does not perform garbage collection, it has minimal impact on application performance.
  • Testing and benchmarking: Useful for performance testing, memory pressure testing, and understanding the impact of garbage collection on your application.

Epsilon GC is not intended for production use in applications that require automatic memory management. It is best suited for specialized scenarios where the absence of garbage collection is beneficial for testing and analysis.

5. Describe the Z Garbage Collector (ZGC) and its benefits.

The Z Garbage Collector (ZGC) is a concurrent, region-based, and low-latency garbage collector introduced in Java 11. It is designed to handle applications that require large heap sizes and low pause times. ZGC achieves this by performing most of its work concurrently with the application threads, thus minimizing the pause times to typically less than 10 milliseconds, even for multi-terabyte heaps.

Key features of ZGC include:

  • Concurrent Marking and Relocation: ZGC performs garbage collection tasks concurrently with the application, reducing the need for long pauses.
  • Region-Based Heap Management: The heap is divided into regions, allowing for more efficient memory management and garbage collection.
  • Load Barriers: ZGC uses load barriers to ensure that the application threads can continue running while garbage collection is in progress.
  • Scalability: ZGC is designed to scale efficiently with large heap sizes, making it suitable for applications with high memory requirements.

6. What is ConstantDynamic and how does it improve constant pool entries?

ConstantDynamic is a feature introduced in Java 11 that allows for the dynamic resolution of constants in the constant pool at runtime. This is a significant improvement over the traditional approach where constants are resolved at compile time and stored directly in the constant pool.

The primary advantage of ConstantDynamic is that it enables more flexible and efficient handling of constants. Instead of embedding all constants directly in the constant pool, ConstantDynamic allows for the deferred resolution of constants until they are actually needed. This can lead to reduced memory usage and improved performance, especially in cases where not all constants are used during the execution of a program.

Additionally, ConstantDynamic supports the use of bootstrap methods, which are invoked to compute the value of the constant dynamically. This allows for more complex and context-dependent constant values that can be computed based on the current state of the application.

7. How do you run a single-file source-code program directly using the java command?

In Java 11, you can run a single-file source-code program directly using the java command without explicitly compiling it first. This feature is particularly useful for quick testing and scripting purposes. The java command will automatically compile the source code and then execute it.

Example:

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

To run this program directly, you can use the following command:

java HelloWorld.java

The java command will compile the HelloWorld.java file and then run the resulting bytecode, displaying the output “Hello, World!” on the console.

8. How do you use var in lambda parameters?

Java 11 introduced the ability to use var in lambda parameters, which allows for local variable type inference. This means that the compiler can infer the type of the lambda parameters based on the context, making the code more concise and readable. However, it is important to note that var can only be used when the type of the lambda parameter is explicitly declared.

Example:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class VarInLambda {
    public static void main(String[] args) {
        List<String> list = Stream.of("one", "two", "three")
                                  .map((var s) -> s.toUpperCase())
                                  .collect(Collectors.toList());
        System.out.println(list);
    }
}

In this example, var is used to declare the type of the lambda parameter s. The compiler infers that s is of type String based on the context provided by the Stream.of method.

9. How do you read and write strings to files using the new methods in the Files class?

In Java 11, the Files class introduced new methods to read and write strings to files more efficiently. The readString method reads all content from a file into a string, while the writeString method writes a string to a file. These methods simplify file operations by reducing the amount of boilerplate code required.

Example:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class FileOperations {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");

        // Writing a string to a file
        String contentToWrite = "Hello, Java 11!";
        try {
            Files.writeString(filePath, contentToWrite);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading a string from a file
        try {
            String fileContent = Files.readString(filePath);
            System.out.println(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

10. How does Java 11 support TLS 1.3?

Java 11 introduced support for TLS 1.3, which is the latest version of the Transport Layer Security protocol. TLS 1.3 offers several improvements over its predecessor, TLS 1.2, including enhanced security, reduced latency, and simplified handshake processes.

Key features of TLS 1.3 in Java 11 include:

  • Improved Security: TLS 1.3 removes outdated cryptographic algorithms and ciphers, reducing the attack surface and enhancing overall security.
  • Performance Enhancements: The handshake process in TLS 1.3 is more efficient, requiring fewer round trips between the client and server, which reduces latency and improves performance.
  • Backward Compatibility: Java 11 maintains backward compatibility with TLS 1.2, allowing applications to continue using older versions of the protocol if necessary.
  • Simplified Configuration: The configuration for enabling TLS 1.3 in Java 11 is straightforward, often requiring minimal changes to existing codebases.

11. How does the enhanced deprecation mechanism work?

In Java 11, the enhanced deprecation mechanism provides more detailed information about deprecated APIs, helping developers understand the implications and alternatives. The key components of this mechanism include:

  • @Deprecated annotation: Marks an API as deprecated.
  • forRemoval attribute: Indicates whether the API is intended to be removed in a future release.
  • since attribute: Specifies the version in which the API was deprecated.

The enhanced deprecation mechanism allows developers to make more informed decisions about using deprecated APIs. For example, if an API is marked with @Deprecated(forRemoval = true), it signals that the API will be removed in a future release, and developers should avoid using it or find an alternative.

12. Explain the new HttpClient API.

The HttpClient API in Java 11 is designed to replace the older HttpURLConnection API. It offers a more user-friendly and flexible approach to handling HTTP requests and responses. Key features include support for HTTP/2, WebSocket, and asynchronous programming.

Example:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;

public class HttpClientExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/data"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

13. Describe the new Files.writeString and Files.readString methods.

Java 11 introduced the Files.writeString and Files.readString methods to simplify file I/O operations. These methods allow you to write a string directly to a file and read a string directly from a file, respectively. This reduces the boilerplate code required for such operations, making the code more readable and concise.

Example:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class FileExample {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        String content = "Hello, World!";

        try {
            // Write string to file
            Files.writeString(path, content);

            // Read string from file
            String fileContent = Files.readString(path);
            System.out.println(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

14. What is the significance of the Local-Variable Syntax for Lambda Parameters feature?

The Local-Variable Syntax for Lambda Parameters feature introduced in Java 11 allows developers to use the var keyword when declaring the parameters of a lambda expression. This feature provides several benefits:

  • Consistency: It allows the use of the same syntax for local variable declarations and lambda parameters, making the code more consistent.
  • Readability: It can improve readability by reducing boilerplate code and making the type inference more explicit.
  • Annotations: It allows the use of annotations on lambda parameters, which was not possible with the previous syntax.

Example:

import java.util.List;
import java.util.stream.Collectors;

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie");

        // Using var in lambda parameters
        List<String> upperCaseNames = names.stream()
            .map((var name) -> name.toUpperCase())
            .collect(Collectors.toList());

        System.out.println(upperCaseNames);
    }
}

In this example, the var keyword is used to declare the name parameter in the lambda expression. This makes the code more consistent with other local variable declarations and allows for potential annotations on the name parameter.

15. What are the key security enhancements?

Java 11 introduced several key security enhancements aimed at improving the overall security of the Java platform. Some of the notable enhancements include:

  • Enhanced KeyStore Mechanisms: Java 11 added support for PKCS12 as the default keystore format, which provides stronger encryption algorithms and better interoperability with other systems.
  • Improved TLS Protocols: Java 11 supports TLS 1.3, which offers improved security and performance over previous versions of the TLS protocol. This includes faster handshake processes and enhanced encryption methods.
  • Enhanced Cryptographic Algorithms: Java 11 includes updates to several cryptographic algorithms, ensuring they meet the latest security standards. This includes support for new algorithms and improvements to existing ones.
  • Class-Data Sharing (CDS) Improvements: Java 11 extends CDS to allow application classes to be included in the shared archive, which can help reduce startup time and memory footprint, indirectly contributing to security by reducing the attack surface.
  • Deprecation and Removal of Weak Algorithms: Java 11 deprecates and removes several weak cryptographic algorithms and protocols, encouraging developers to use more secure alternatives.
Previous

10 Bitwise Interview Questions and Answers

Back to Interview
Next

10 Link Building Interview Questions and Answers