Top Java 11 Interview Questions

Java 11, released in September 2018, brought a host of new features and enhancements that have been crucial for developers. If you're preparing for a job interview that involves Java 11, it’s essential to be familiar with its key features, improvements, and best practices. This blog post will cover some of the most commonly asked Java 11 interview questions to help you prepare effectively.

1. What are the new features introduced in Java 11?

Answer: Java 11 introduced several new features and enhancements, including:

  • Local-Variable Syntax for Lambda Parameters: Allows the use of var in lambda expressions.
  • New String Methods: isBlank(), lines(), strip(), stripLeading(), stripTrailing(), and repeat().
  • File Methods: readString() and writeString().
  • Optional Methods: isEmpty(), ifPresentOrElse(), or(), and stream().
  • HTTP Client: Standardized the HTTP Client API that was introduced in Java 9 as an incubator module.
  • Nest-Based Access Control: Introduced to support the improved encapsulation of nested classes.
  • Deprecation of Nashorn JavaScript Engine: Marked for removal.
  • Epsilon Garbage Collector: A no-op garbage collector for testing.

2. How do you use the var keyword in Java 11?

Answer: In Java 11, the var keyword can be used for local variable type inference in lambda expressions. This means you can declare the type of lambda parameters using var, making the code more concise and readable.

Example:

import java.util.List;

public class VarLambdaExample {
    public static void main(String[] args) {
        List<String> list = List.of("Java", "Kotlin", "Scala");

        list.forEach((var item) -> System.out.println(item));
    }
}

3. What are the new methods added to the String class in Java 11?

Answer: Java 11 introduced several new methods to the String class:

  • isBlank(): Returns true if the string is empty or contains only white space code points.
  • lines(): Returns a stream of lines extracted from the string, separated by line terminators.
  • strip(): Removes leading and trailing white space.
  • stripLeading(): Removes leading white space.
  • stripTrailing(): Removes trailing white space.
  • repeat(int count): Returns a string whose value is the concatenation of this string repeated count times.

Example:

public class StringMethodsExample {
    public static void main(String[] args) {
        String str = "  Java 11  ";
        System.out.println(str.isBlank()); // false
        System.out.println(str.strip()); // "Java 11"
        System.out.println(str.stripLeading()); // "Java 11  "
        System.out.println(str.stripTrailing()); // "  Java 11"
        System.out.println("Java\nKotlin\nScala".lines().count()); // 3
        System.out.println("Hello ".repeat(3)); // "Hello Hello Hello "
    }
}

4. Explain the new methods added to the Optional class in Java 11.

Answer: Java 11 added several new methods to the Optional class:

  • isEmpty(): Returns true if the value is not present.
  • ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction): If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
  • or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
  • stream(): If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.

Example:

import java.util.Optional;

public class OptionalMethodsExample {
    public static void main(String[] args) {
        Optional<String> opt = Optional.of("Java 11");

        System.out.println(opt.isEmpty()); // false

        opt.ifPresentOrElse(
            value -> System.out.println("Value: " + value),
            () -> System.out.println("Value is absent")
        );

        Optional<String> orOpt = Optional.<String>empty().or(() -> Optional.of("Default"));
        System.out.println(orOpt.get()); // "Default"

        opt.stream().forEach(System.out::println); // "Java 11"
    }
}

5. What is the HTTP Client API in Java 11, and how do you use it?

Answer: The HTTP Client API, introduced in Java 9 as an incubator module and standardized in Java 11, provides a modern and easy-to-use HTTP client. It supports both synchronous and asynchronous operations, and also HTTP/1.1 and HTTP/2.

Example:

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

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI("https://postman-echo.com/get"))
            .GET()
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Response Body: " + response.body());
    }
}

6. What is the Epsilon Garbage Collector, and when would you use it?

Answer: The Epsilon Garbage Collector is a no-op garbage collector introduced in Java 11. It handles memory allocation but does not reclaim any memory. It is mainly used for performance testing and benchmarking where garbage collection overhead needs to be minimized.

Example Usage: To enable the Epsilon Garbage Collector, you can start your Java application with the following JVM option:

java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xmx2g -Xms2g -jar myapp.jar

7. How do you read and write strings from/to files in Java 11?

Answer: Java 11 introduced Files.readString() and Files.writeString() methods for reading and writing strings to files, simplifying file I/O operations.

Example:

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

public class FileReadWriteExample {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("example.txt");

        // Writing a string to a file
        Files.writeString(path, "Hello, Java 11!");

        // Reading a string from a file
        String content = Files.readString(path);
        System.out.println(content); // "Hello, Java 11!"
    }
}

8. What is Nest-Based Access Control in Java 11?

Answer: Nest-Based Access Control is a feature introduced in Java 11 that improves the access control mechanism between nested classes. It allows nested classes to access private members of other nested classes within the same outer class.

Example:

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

    class InnerClass {
        private String innerField = "Inner";

        private void innerMethod() {
            System.out.println(outerField);
        }
    }

    private void outerMethod() {
        InnerClass inner = new InnerClass();
        System.out.println(inner.innerField);
    }
}

9. Explain the isBlank() method in Java 11.

Answer: The isBlank() method is a new method added to the String class in Java 11. It returns true if the string is empty or contains only white space code points, otherwise false.

Example:

public class StringIsBlankExample {
    public static void main(String[] args) {
        String str1 = " ";
        String str2 = "Java 11";

        System.out.println(str1.isBlank()); // true
        System.out.println(str2.isBlank()); // false
    }
}

10. How does Java 11 improve the Optional class?

Answer: Java 11 improves the Optional class by adding several useful methods:

  • isEmpty(): Returns true if no value is present, otherwise false.
  • ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction): Performs the given action with the value if present, otherwise performs the given empty-based action.
  • or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
  • stream(): If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.

Example:

import java.util.Optional;

public class OptionalMethodsExample {
    public static void main(String[] args) {
        Optional<String> opt = Optional.of("Java 11");

        System.out.println

(opt.isEmpty()); // false

        opt.ifPresentOrElse(
            value -> System.out.println("Value: " + value),
            () -> System.out.println("Value is absent")
        );

        Optional<String> orOpt = Optional.<String>empty().or(() -> Optional.of("Default"));
        System.out.println(orOpt.get()); // "Default"

        opt.stream().forEach(System.out::println); // "Java 11"
    }
}

Conclusion

Java 11 brought many new features and improvements that enhance developer productivity and code readability. Understanding these features is crucial for any Java developer, especially when preparing for an interview. This blog post covered some of the most commonly asked Java 11 interview questions, helping you prepare effectively for your next interview. By mastering these concepts, you will be well-equipped to tackle any Java 11-related challenges you may encounter.

Comments