top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java 9 Interview Questions with Explanation




Checkout these other important topics as well -



There is a huge demand for Java 17 and modern java concepts in industry . What do you think makes for a good Java 17 resource?

  • Perfect Ebook on Java 17 - can be referred whenever you wan

  • Some lame discussion giving tidbits on Java 17




What is the difference between a HashMap and a ConcurrentHashMap in Java 9?


A HashMap is not thread-safe and can cause issues in a multi-threaded environment, whereas a ConcurrentHashMap is thread-safe and can handle concurrent access. The ConcurrentHashMap is implemented using a partitioned array, where each partition is locked independently. This means that multiple threads can access different partitions simultaneously.

Code Snippet:



HashMap<Integer, String> map = new HashMap<>();
ConcurrentHashMap<Integer, String> concurrentMap = new ConcurrentHashMap<>();

What is the difference between a Set and a List in Java 9?


A List is an ordered collection of elements, whereas a Set is an unordered collection of unique elements. Lists can contain duplicate elements, while Sets cannot. Code Snippet:



List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();

How do you handle exceptions in Java 9?


In Java 9, you can use the try-with-resources statement to automatically close resources such as files and network connections. You can also use the catch block to handle exceptions and the finally block to execute code regardless of whether an exception occurs.

Code Snippet:



try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
// code to read from file
} catch (IOException e) {
// handle exception
} finally {
// code to execute regardless of whether an exception occurs
}

What is the difference between a checked exception and an unchecked exception in Java 9?


A checked exception is a type of exception that must be declared in a method's signature or caught in a try-catch block. An unchecked exception, on the other hand, does not need to be declared or caught. RuntimeExceptions and Error are examples of unchecked exceptions. Code Snippet:



public void checkedException() throws IOException {
// code that throws a checked exception
}
public void uncheckedException() {
throw new RuntimeException("Unchecked Exception");
}

How do you create a custom exception in Java 9?


To create a custom exception in Java 9, you need to create a new class that extends the Exception class. You can then throw this custom exception in your code as needed.

Code Snippet:



public class CustomException extends Exception {
public CustomException(String message) {
scssCopy code
   super(message); 
}
}


What is a lambda expression in Java 9?


A lambda expression is a concise way to represent a method that can be passed as an argument to another method. It is essentially a function that can be created and passed around like any other value.

Code Snippet:



List<Integer> list = new ArrayList<>();
list.forEach((n) -> System.out.println(n));

How do you create a thread in Java 9?


You can create a thread in Java 9 by implementing the Runnable interface or by extending the Thread class. You can then start the thread using the start() method.

Code Snippet:



public class MyRunnable implements Runnable {
public void run() {
javascriptCopy code
   // code to be executed in the thread
}
}
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();



What is a CompletableFuture in Java 9?


A CompletableFuture is a class that provides a way to perform asynchronous computations and handle their results. It is similar to a Promise in other programming languages.

Code Snippet:



CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// code to execute asynchronously
return "result";
});
future.thenAccept((result) -> {
// code to handle the result
});


What is the difference between a Stream and a Collection in Java 9?


A Stream is a sequence of elements that can be processed lazily and in parallel, whereas a Collection is a data structure that stores a fixed number of elements. Streams are designed to perform operations on collections of data, while Collections are designed to store and manipulate data.




List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = list.stream();

What is the diamond operator in Java 9?


The diamond operator (<>), introduced in Java 7 and improved in Java 9, is a shorthand way to declare a generic type without specifying its type arguments explicitly.

Code Snippet:



List<String> list = new ArrayList<>();

How do you create a module in Java 9?


You can create a module in Java 9 by defining a module descriptor file (module-info.java) that specifies the module's name, dependencies, and exported packages. You can then compile the module using the javac command.

Code Snippet:



module com.example.mymodule {
requires java.base;
exports com.example.mymodule.package1;
}

What is a module in Java 9?


A module in Java 9 is a self-contained unit of code that encapsulates its implementation details and specifies its dependencies on other modules. It is designed to improve the scalability, security, and maintainability of large-scale applications.

How do you use the jshell tool in Java 9?


The jshell tool, introduced in Java 9, is a command-line interface that allows you to interactively evaluate Java code. You can launch the jshell tool using the jshell command and enter Java expressions and statements at the prompt. Code Snippet:



jshell> int x = 10;
jshell> int y = 20;
jshell> x + y;

What is the Process API in Java 9?


The Process API, introduced in Java 9, is a set of classes and interfaces that allow you to manage and interact with external processes running on the operating system. It provides a more robust and platform-independent way to handle external processes than the previous ProcessBuilder API. Code Snippet:



ProcessBuilder pb = new ProcessBuilder("mycommand", "arg1", "arg2");
Process p = pb.start();
InputStream is = p.getInputStream();

What is the difference between a Module and a Package in Java 9?


A Module is a self-contained unit of code that encapsulates its implementation details and specifies its dependencies on other modules, whereas a Package is a namespace for organizing related classes and interfaces. Modules are designed to improve the scalability, security, and maintainability of large-scale applications, while packages are designed to organize code and avoid naming conflicts.


How do you use the HttpClient API in Java 9?


The HttpClient API, introduced in Java 9, is a standard API for making HTTP requests and handling responses. You can create an HttpClient instance using the HttpClient.newBuilder() method and send requests using the HttpRequest.Builder class. Code Snippet:



HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());


How do you use the Flow API in Java 9?


The Flow API, introduced in Java 9, is a standard API for reactive programming in Java. It provides interfaces and classes for defining and using reactive streams, Code Snippet:



public class MySubscriber<T> implements Subscriber<T> {
private Subscription subscription;
public void onSubscribe(Subscription subscription) {

   this.subscription = subscription;     subscription.request(1); 
}
public void onNext(T item) {

   System.out.println("Received: " + item);     subscription.request(1); 
}
public void onError(Throwable throwable) {

   System.err.println("Error: " + throwable.getMessage()); 
}
public void onComplete() {

   System.out.println("Done!"); 
}
}

What is the difference between a Process and a Thread in Java 9?


A Process is an external program running on the operating system, whereas a Thread is a lightweight unit of execution within a program. Processes are isolated from each other and communicate through IPC mechanisms, while threads share the same memory space and communicate through shared data structures.

How do you use the ProcessHandle API in Java 9?


The ProcessHandle API, introduced in Java 9, is a standard API for managing and monitoring external processes running on the operating system. You can obtain a ProcessHandle instance using the ProcessHandle.of(pid) method and call methods such as destroy() and onExit() to manage the process. Code Snippet:



ProcessHandle handle = ProcessHandle.of(pid);
handle.destroy();

What is the difference between a sealed and a non-sealed package in Java 9?


A sealed package is a package that restricts which other packages can use its types, while a non-sealed package allows any other package to use its types. Sealed packages are designed to improve the security and maintainability of large-scale applications by controlling which code can access the package's implementation details.

How do you use the Stack-Walking API in Java 9?


The Stack-Walking API, introduced in Java 9, is a standard API for accessing the call stack of a running program. You can obtain a StackWalker instance using the StackWalker.getInstance() method and call methods such as walk() and forEach() to traverse the stack frames. Code Snippet:



StackWalker walker = StackWalker.getInstance();
walker.walk(frames -> frames.forEach(System.out::println));

What is the difference between a VarHandle and a Field in Java 9?


A VarHandle is a low-level API for accessing and manipulating variables directly in memory, whereas a Field is a high-level API for accessing and manipulating variables through their Java objects. VarHandles are designed for performance-critical applications that require direct access to memory, while Fields are designed for general-purpose programming.

How do you use the VarHandle API in Java 9?


The VarHandle API, introduced in Java 9, is a low-level API for accessing and manipulating variables directly in memory. You can obtain a VarHandle instance using the MethodHandles.lookup().in(Class.class).findVarHandle() method and call methods such as get() and set() to read and write the variable. Code Snippet:



VarHandle intHandle = MethodHandles.lookup()
.in(MyClass.class)
.findVarHandle(MyClass.class, "myInt", int.class);
int value = (int) intHandle.get(myObject);
intHandle.set(myObject, value + 1);


What is the difference between a ProcessBuilder and a Runtime in Java 9?


A ProcessBuilder is a high-level API for creating and starting external processes, while a Runtime is a low-level API for managing the Java Virtual Machine itself. ProcessBuilders are designed for creating and managing external processes, while Runtimes are designed for managing the Java environment.

How do you use the HttpClient API in Java 9?


The HttpClient API, introduced in Java 9, is a standard API for making HTTP requests and receiving HTTP responses. You can create an HttpClient instance using the HttpClient.newBuilder() method and call methods such as send() and thenApply() to make requests and process responses. Code Snippet:



HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.GET()
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);

What is the difference between a List and a Set in Java 9?


A List is an ordered collection of elements that can contain duplicates, while a Set is an unordered collection of elements that cannot contain duplicates. Lists are designed for situations where order is important and duplicates are allowed, while Sets are designed for situations where order is not important and duplicates are not allowed.

How do you use the Stream API in Java 9?


The Stream API, introduced in Java 8 and enhanced in Java 9, is a standard API for processing collections of elements in a functional style. You can create a Stream instance using the stream() method on a collection and call methods such as filter(), map(), and reduce() to process the elements. Code Snippet:



List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);

What is the difference between a CompletableFuture and a Future in Java 9?


A CompletableFuture is a high-level API for representing a computation that may complete in the future, while a Future is a low-level API for representing a computation that may complete in the future. CompletableFutures are designed for asynchronous programming and support chaining of operations, while Futures are designed for low-level synchronization and blocking.

How do you use the CompletableFuture API in Java 9?


The CompletableFuture API, introduced in Java 8 and enhanced in Java 9, is a high-level API for representing a computation that may complete in the future. You can create a CompletableFuture instance using the CompletableFuture.supplyAsync() method and call methods such as thenApply() and thenAccept() to chain operations and process the result. Code Snippet:



CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, world!");
future.thenApply(String::toUpperCase)
.thenAccept(System.out::println);

93 views

Recent Posts

See All

Comments


bottom of page