Java Interview Questions

Searching for the top Java Interview Questions? Get the top Java Interview Questions for freshers and experienced Java developers.


Sample Java Interview Questions:


Core Java Interview Questions

Q1. In which situation would you use a LinkedList instead of an ArrayList

A. A common situation would be when add operations are common, the list size is not known ahead of time and read operations are not common.

The add operations are cheaper in a LinkedList compared to an ArrayList because when an ArrayList reaches its capacity, it needs to be resized by being copied into a new array.

On the other hand, using a LinkedList tends to consume more memory and you can’t access elements in O(1) if the element is not in the head.

Q2. What are some differences between the HashMap and the HashTable classes?

A. The HashMap class is not synchronized and can store one key with a null value and any number of values with null values.

On the other hand, the HashTable class is a synchronized class that offers guarantees to operate with multiple threads. The HashTable class doesn’t allow null either as key or a value.

Reference:

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

Q3. How can one find the common elements between two arrays in Java?

One can use the Java 8 Stream API and the filter() and distinct() method to filter the common elements between the two arrays, like this:

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {3, 4, 5, 6, 7};

Arrays.stream(array1)
      .filter(i -> Arrays.stream(array2).anyMatch(j -> i == j))
      .distinct()
      .forEach(System.out::println);

Q4. Which ArrayList method increases the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by some minimum capacity?

The ensureCapacity​(int minCapacity) increases the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

Reference:

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Q5. How does the Executor framework in Java simplify thread management?

The Executor framework in Java simplifies thread management by providing a higher-level abstraction than the traditional Thread and Runnable classes. It allows you to create and manage a pool of worker threads, and it provides a simple way to submit tasks for execution.

The Executor framework consists of the following components:

Executor: The main interface of the framework, which defines a single method execute(Runnable command) to submit tasks for execution.

ExecutorService: A subinterface of Executor, which adds methods to manage the lifecycle of an Executor and to submit multiple tasks at once.

ThreadPoolExecutor: A concrete implementation of ExecutorService, which creates a pool of worker threads and manages the execution of tasks.

By using an Executor instead of manually creating and managing threads, you can:

  • Improve the performance and scalability of your application by reusing a fixed number of worker threads, instead of creating a new thread for every task.
  • Simplify the code for task execution by abstracting away the details of thread creation and management.
  • Easily control the number of threads and the queue size, to fine-tune the performance of your application.
  • Easily shutdown the thread pool by invoking shutdown() method.

Here is an example of how to use an Executor to execute a task:

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            // task to be executed
            System.out.println("Hello from thread: " + Thread.currentThread().getName());
        });
    }
}

Q6. In which states can a Java thread be?

NEW – A thread that has not yet started is in this state.

RUNNABLE – A thread executing in the Java virtual machine is in this state.

BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.

WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED_WAITING – A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

TERMINATED – A thread that has exited is in this state.

Reference:

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

Q7. How can you use the HashMap to implement a simple cache in Java?

A cache is a temporary storage area that holds frequently accessed data to speed up future access to the same data.
Java’s HashMap can be used to implement a simple cache by using its put() and get() methods to store and retrieve data in the cache.
Here is an example of how to use the HashMap class to create a simple cache that stores a string value for a given string key:

Map<String, String> cache = new HashMap<>();

cache.put("key1", "value1");  // store "value1" in the cache for the key "key1"
cache.put("key2", "value2");  // store "value2" in the cache for the key "key2"

System.out.println(cache.get("key1"));  // retrieve the value for the key "key1" (output: "value1")
System.out.println(cache.get("key2"));  // retrieve the value for the key "key2" (output: "value2")

Java Developer Interview Questions

Q8. What are some advantages of using PreparedStatement objects over Statement objects?

A. One advantage is that the PreparedStatement objects are pre-compiled and tend to offer higher performance compared to Statement if the command is supposed to execute multiple times.

Another advantage is that PreparedStatement objects offer a set of features designed to prevent SQL Injection attacks. Those features are not available in Statement objects.


Advanced Java Interview Questions

Q9. Which data type is recommended to handle passwords in Java?

A. The char[] data type is recommended. String is a natural option, but since String is immutable, it can not be overwritten after usage. That property creates a potential attack window until the object is garbage collected.

The char arrays can be overwritten with data which allows that sensitive information disappear right after the usage, even before the garbage collector collects the object. 

Another disadvantage of String objects is related to potential password prints in logs and/or other insecure places. Since String objects toString() method prints text in plain sight, it can expose passwords if printed maliciously or by mistake.

By using the char array, the object toString() method prints the object hashcode. That mechanism prevents the exposure of password.

Additional information is available at:

https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords

Q10. What is the process of garbage collection? 

A. It is the process of identifying unused objects in order to reclaim memory space. Unused objects are objects for which there are no references by any part of the program. The garbage collection process takes place in the heap.



Get the Java best content, weekly, at Java Newsletter Insights