Java Developer Interview Question Series-19(for 0–5years experience candidates)
In this article, we will explore Core Java interview questions for Junior to Senior level Java Developers. By familiarizing yourself with these questions and their potential answers, you can better prepare for your next senior Java developer interview and showcase your expertise in the field.
(A bit of context: I’ve conducted numerous interviews for software engineering positions in most of the MNCs. Additionally, there have been instances where I faced challenges during coding interviews due to lack of preparation.)
Are you preparing for a job interview as a Java developer?
Find my book Guide To Clear Java Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).
Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).
Download the sample copy here: Guide To Clear Java Developer Interview[Free Sample Copy]
Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]
Why String is immutable?
Strings are immutable because their values cannot be changed after they are created. Once a string is created, its contents cannot be modified. This immutability provides several advantages, such as efficient memory usage, thread safety, and enabling string interning for improved performance.
How to create a Custom Immutable class?
- Declare the class
final
to prevent inheritance. - Make all the fields
private
andfinal
, so they cannot be modified once assigned. - Do not provide any setter methods for the fields.
- If the class contains mutable objects, make sure to create copies of those objects to avoid modification from external sources.
- Ensure that any methods that return the class’s internal state do not expose the actual references to mutable objects.
- If necessary, provide methods to access the fields, but make sure they return copies or immutable versions of the objects.
- Implement the
hashCode()
andequals()
methods correctly, considering the immutable state of the object. - Consider making the class implement the
Serializable
interface to support serialization if needed.
How mutable reference can be handled in an immutable class?
To handle mutable references in an immutable class:
- Use defensive copying.
- Wrap mutable objects with immutable wrappers.
- Return defensive copies of mutable objects.
- Ensure the mutable object is immutable by contract.
Java 8 stream program — sort employees names based on alphabet A and sort in descending order.
public class EmployeeFilterAndSortExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("John"));
employees.add(new Employee("Alice"));
employees.add(new Employee("David"));
employees.add(new Employee("Bob"));
List<Employee> filteredAndSortedEmployees = employees.stream()
.filter(e -> e.getName().startsWith("A")) // Filter based on names starting with 'A'
.sorted(Comparator.comparing(Employee::getName).reversed()) // Sort in descending order
.collect(Collectors.toList());
System.out.println("Filtered and Sorted Employees (Descending Order):");
for (Employee employee : filteredAndSortedEmployees) {
System.out.println(employee.getName());
}
}
static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
Difference between Hashtable and Concurrent HashMap?
The key differences between Hashtable
and ConcurrentHashMap
can be summarized as follows:
- Locking Mechanism:
Hashtable
uses a single lock for the entire table, whileConcurrentHashMap
uses multiple locks (segments) to achieve concurrency. - Concurrency:
Hashtable
has lower concurrency and can suffer from contention, whileConcurrentHashMap
allows concurrent read and update operations on different segments, resulting in improved performance in highly concurrent environments. - Null Support:
Hashtable
does not allow null keys or values, whereasConcurrentHashMap
supports null keys and values. - Performance:
ConcurrentHashMap
is designed for better scalability and performance in concurrent scenarios, whereasHashtable
may exhibit slower performance in highly concurrent environments. - Enumeration: Enumeration in
Hashtable
is not fail-safe, whileConcurrentHashMap
provides fail-safe enumeration. - Java Version:
Hashtable
has been available since Java 1.0, whileConcurrentHashMap
was introduced in Java 1.5.
Overall, ConcurrentHashMap
provides improved concurrency, better performance, null support, and fail-safe enumeration compared to Hashtable
.
How does Hashmap work?
- Hashing: When a key-value pair is inserted into a
HashMap
, the hash code of the key is calculated using the key'shashCode()
method. The hash code is used to determine the index or bucket where the entry will be stored. - Bucket and Array:
HashMap
internally uses an array of buckets, where each bucket can hold multiple entries. The size of the array is initially set and grows dynamically as needed. The index of each bucket is calculated based on the hash code of the key. - Collision Handling: In some cases, different keys can produce the same hash code, leading to a collision. To handle collisions,
HashMap
uses a linked list or a tree (in Java 8+) within each bucket. If multiple entries have the same hash code, they are stored as nodes in the linked list or tree. - Retrieval: When retrieving a value from a
HashMap
using a key, the hash code of the key is calculated again. The index is determined based on the hash code, and the linked list or tree within the corresponding bucket is traversed to find the entry with the matching key. - Performance:
HashMap
provides constant-time performance for most operations, such asget()
andput()
, on average, assuming a good hash function and uniform distribution of keys. However, in the case of frequent collisions or a poorly designed hash function, the performance can degrade to O(n), where n is the number of entries.
The above question is asked million times in an interview, its a must know questions.
Why do we need to override the equal and hashcode method?
Overriding the equals()
and hashCode()
methods is necessary to ensure correct behavior when working with custom classes in Java collections. It enables proper object comparison, allows objects to be used as keys in hash-based data structures, and ensures consistency and adherence to the Java object contract.
Uses of Executor Service
This Framework helps in concurrent multithreading scenarios.
- Thread management: It manages the creation, allocation, and reusability of threads, providing a thread pool for efficient task execution.
- Asynchronous task execution: It allows tasks to be submitted for execution and handles the assignment of tasks to available threads in the thread pool.
- Improved performance: By utilizing a thread pool, it optimizes resource utilization and reduces the overhead of thread creation, resulting in improved performance.
- Task coordination: It provides methods for coordinating the execution of tasks, such as waiting for multiple tasks to complete or obtaining the result of a task through a
Future
object. - Task scheduling: It enables scheduling tasks to run at specific times or after certain delays, allowing for the implementation of periodic tasks or delayed execution.
- Graceful shutdown: It allows for the orderly shutdown of the ExecutorService, ensuring that running tasks are complete while rejecting new tasks, and preventing abrupt termination of threads.
If you are looking for some interview guides for the Java Developer role you can use the below resources for your prep as well.
The below Book contains 250 Curated Java, Spring-Boot, and Microservice Questions.
Free PDF’s from javinpaul from @javarevisited
Grokking the Java Interview [Free Sample Copy]
Grokking the Spring Boot Interview [Free Sample Copy]
Thanks for reading
- 👏 Please clap for the story and subscribe 👉
- 📰 Read more content on my Medium (30 stories on Java Developer interview)
Find my books here: