Member-only story

Java Interview Questions and Answers: A Comprehensive Guide (Part 1)

Suleyman Yildirim
4 min readNov 4, 2024

--

Over the years, I’ve encountered various interview questions on core Java concepts. Here’s a compilation of frequently asked questions, explanations, and examples.

Even if you have 10+ years of experience in Java, you will most likely encounter these questions during interviews or online tests. It isn’t very pleasant, but that is the reality of the hiring process in the IT industry.

Photo by Gabriele Stravinskaite on Unsplash

1. How to Create an Immutable Class in Java?

Definition: An immutable class is one whose instances cannot be modified after creation.

Steps to Create an Immutable Class:

  • Declare the class as final: This prevents subclasses from altering behavior.
  • Make all fields private and final: This prevents changes to fields and ensures immutability.
  • Do not provide "setter" methods: This means once values are set in the constructor, they cannot be modified.
  • Initialize fields only in the constructor: This ensures all properties are assigned only once.
  • If a field is a mutable object (e.g., a List or Date), create defensive copies: This prevents the caller from altering the original object.

Example: Here, ImmutableClass cannot be modified once created. Any mutable fields like a list are also safeguarded through defensive copying.

public final class ImmutableClass {
private final String name;
private final List<String> list;

public ImmutableClass(String name, List<String> list) {
this.name = name;
this.list = new ArrayList<>(list); // defensive copy
}

public String getName() {
return name;
}

public List<String> getList() {
return new ArrayList<>(list); // return defensive copy
}

}

2. Singleton Pattern and Options to Create Singleton Class

Definition: A Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

Common Ways to Create a Singleton:

1. Eager Initialization: Create the instance when the class is loaded.

public class Singleton {
private static final Singleton INSTANCE = new Singleton()…

--

--

No responses yet

Write a response