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 60 of 100

What is the difference between a callable and a runnable in Java?

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

In Java, both Callable and Runnable are interfaces used for defining tasks that can be executed in separate threads. However, they have some key differences in terms of return value and exception handling.

Runnable is a functional interface that has only one method run() that takes no arguments and returns no value. It is typically used to define tasks that perform some action or work without returning any results. For example:

class MyRunnable implements Runnable {
    public void run() {
    // Perform some work or action
    }
}

To execute a Runnable in a separate thread, you can create a new thread object and pass an instance of the Runnable to its constructor:

Thread t = new Thread(new MyRunnable());
t.start();

Callable, on the other hand, is also a functional interface but has a single method call() that returns a result and can throw an exception. It is typically used to define tasks that return a result after performing some work or computation. For example:

class MyCallable implements Callable<Integer> {
    public Integer call() throws Exception {
        // Perform some work or computation and return a result
        return 42;
    }
}

To execute a Callable in a separate thread, you can use the ExecutorService framework:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
Integer result = future.get(); 
// This will block until the result is available

Here, submit() method of ExecutorService returns a Future object that can be used to retrieve the result of the Callable. The get() method of Future will block until the result is available.

In summary, the main differences between Runnable and Callable are:

Runnable does not return a result, while Callable does. Runnable cannot throw checked exceptions, while Callable can. Callable is executed using the ExecutorService framework, while Runnable can be executed using Thread directly.

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