WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Advanced · question 56 of 100

What is a CompletableFuture join() method in Java? How is it used?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, a CompletableFuture is a Future that can be completed asynchronously, and is used to represent the result of an asynchronous computation. It has many methods that can be used to chain asynchronous operations and perform error handling. One such method is join(), which is used to block and wait for the result of the CompletableFuture.

The join() method is similar to the get() method, which is used to block and wait for the result of a Future. However, the join() method does not throw a checked InterruptedException, which makes it more convenient to use in functional programming scenarios where checked exceptions are not desirable.

Here’s an example that demonstrates the use of the join() method:


CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Hello";
});

String result = future.join();
System.out.println(result);

In this example, we create a CompletableFuture that returns a String asynchronously after a delay of 1 second. We then call the join() method on the CompletableFuture to block and wait for the result. Finally, we print the result to the console.

Note that if the CompletableFuture throws an exception, the join() method will re-throw the exception wrapped in an UnchekedExecutionException. Therefore, it’s important to handle exceptions properly when using the join() method.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics