Preparing for a Java backend developer interview with around three years of experience? Knowing Java syntax is a good start, but interviewers may also expect you to explain how things work internally, write code, and design a basic REST API.

This article covers questions encountered in a Backend Developer interview for a role requiring 3 years of experience. The questions cover core Java, collections, HashMap internals, Spring Boot REST API development, exception handling, and coding problems. SQL is included separately as a bonus.

Instead of presenting a generic list of interview questions, let’s walk through the actual questions, understand what each one tests, and review the answers you should be prepared to explain.

Core Java Interview Questions

1. Explain the basics of OOP in Java.

Object-Oriented Programming (OOP) is a programming approach that organizes code around classes and objects. Java uses OOP concepts to help developers structure applications and reuse code.

The four pillars of OOP are:

  • Encapsulation: Bundles data and methods together and controls direct access to data.
  • Inheritance: Allows a child class to inherit properties and methods from a parent class.
  • Polymorphism: Allows the same interface or method to exhibit different behavior depending on the implementation or context.
  • Abstraction: Hides implementation details and exposes only the functionality that is needed.

What the interviewer is looking for: You should be able to explain all four concepts clearly and give a simple Java example for each. Merely memorizing the definitions may not be enough if follow-up questions are asked.

2. What is a Functional Interface in Java?

A functional interface is an interface with exactly one abstract method. It is commonly used with lambda expressions, which were introduced in Java 8.

Consider this example:

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

You can implement the interface using a lambda expression:

Calculator calculator = (a, b) -> a + b;

System.out.println(calculator.calculate(10, 20));

Output:

30

The lambda expression provides the implementation of the calculate() method without requiring a separate implementation class.

Common examples of functional interfaces in Java include:

  • Runnable
  • Comparator
  • Predicate
  • Function
  • Consumer

What the interviewer is looking for: Understand the relationship between functional interfaces and lambda expressions. Also, remember that an interface can contain default and static methods while still qualifying as a functional interface, provided it has exactly one abstract method.

3. Do you know how to use Java Collections?

The Java Collections Framework provides interfaces and implementations for storing and manipulating groups of objects.

You should understand the differences between List, Set, Map, and Queue.

TypePurposeExamples
ListMaintains element order and allows duplicatesArrayList, LinkedList
SetStores unique elementsHashSet, TreeSet
MapStores key-value pairs with unique keysHashMap, Hashtable, ConcurrentHashMap
QueueSupports queue-oriented processingPriorityQueue

For example, a List allows duplicate values:

List<String> employees = new ArrayList<>();

employees.add("John");
employees.add("John");

System.out.println(employees);

Output:

[John, John]

Both entries remain in the list because duplicates are allowed.

A Set, on the other hand, does not retain duplicate elements according to its equality rules.

What the interviewer is looking for: Know when to choose each collection type. You should also be able to explain the differences between common implementations, rather than simply listing their names.

4. What is HashMap, and how does it work internally?

HashMap stores data as key-value pairs. It is commonly used when you need to retrieve a value using a key.

For example:

Map<Integer, String> employees = new HashMap<>();

employees.put(101, "John");
employees.put(102, "Priya");

System.out.println(employees.get(101));

Output:

John

The more important interview question is how HashMap works internally.

When you insert a key-value pair, the general process is:

  1. Java obtains the key’s hashCode().
  2. HashMap uses the hash information to calculate a bucket index.
  3. The entry is stored in the corresponding bucket.
  4. If multiple entries map to the same bucket, a collision occurs.

When retrieving a value, HashMap uses the key’s hash information to locate the bucket and equality checks to identify the matching key.

Two methods are particularly important:

  • hashCode() helps determine the bucket in which an entry is stored or searched for.
  • equals() determines whether two objects are logically equal, according to their implementation.

HashMap handles collisions internally using linked structures. Under certain conditions, heavily populated buckets can use a Red-Black Tree.

What the interviewer is looking for: Explain the insertion and retrieval process, the role of hashCode() and equals(), and how collisions are handled. Knowing only how to call put() and get() misses the main point of this question.

5. Can HashMap have collisions? How can you prevent or fix them?

Yes, collisions can occur in HashMap.

A collision happens when different keys map to the same bucket. It does not necessarily mean that the keys are equal.

HashMap handles collisions internally, so you generally don’t need to resolve them manually.

However, when designing custom key classes, you should:

  • Implement a well-designed hashCode() method.
  • Follow the contract between equals() and hashCode().
  • Avoid hash functions that distribute keys poorly.

If two objects are considered equal by equals(), they must return the same hash code. The reverse is not required: two different objects can have the same hash code.

What the interviewer is looking for: Understand why collisions happen, how HashMap handles them, and why correctly implementing equals() and hashCode() matters when custom objects are used as keys.

6. What is the difference between Java 8 and newer Java versions?

Java 8 introduced several important features that changed how developers write Java applications.

Some of the major Java 8 features are:

  • Lambda expressions
  • Functional interfaces
  • Stream API
  • Optional
  • Method references
  • Default and static methods in interfaces
  • The new Date and Time API

Newer Java versions introduced additional language and runtime improvements, including:

  • Local variable type inference using var
  • Switch expressions
  • Text blocks
  • Records
  • Pattern matching
  • Sealed classes
  • Garbage collection and JVM performance improvements
  • Virtual threads in Java 21

For example, Java 8 allows you to use lambda expressions when iterating over a collection:

List<String> names = Arrays.asList(
    "John", "Priya", "Alex"
);

names.forEach(name -> System.out.println(name));

This makes the code more concise than writing an anonymous class for the same operation.

What the interviewer is looking for: Be comfortable with Java 8 features, since they remain common in existing applications. You should also understand newer features relevant to the Java version you work with.

Spring Boot Interview Question

7. How would you create a Spring Boot API to save Employee Master data into a database?

This question tests practical backend development knowledge. You’re expected to explain how a REST API receives data, processes it, and persists it to a database.

Suppose an employee_master table stores employee information. A typical Spring Boot application can use a controller-service-repository architecture.

The request flow looks like this:

Client
   |
   v
@RestController
   |
   v
@Service
   |
   v
@Repository
   |
   v
JPA / Hibernate
   |
   v
Database

Let’s break it down.

Step 1: Create the Employee entity

The entity represents the database data managed by JPA.

@Entity
@Table(name = "employee_master")
public class Employee {

    @Id
    @GeneratedValue(
        strategy = GenerationType.IDENTITY
    )
    private Long id;

    private String name;
    private String email;

    // Getters and setters
}

The @Entity annotation marks the class as a JPA entity. The @Table annotation specifies the database table.

Step 2: Create the repository

The repository provides database persistence operations.

@Repository
public interface EmployeeRepository
        extends JpaRepository<Employee, Long> {
}

By extending JpaRepository, you get methods such as save(), findById(), and findAll() without implementing each operation manually.

Step 3: Create the service layer

The service layer contains business logic and delegates persistence operations to the repository.

@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {
        this.repository = repository;
    }

    public Employee saveEmployee(Employee employee) {
        return repository.save(employee);
    }
}

The repository is supplied through constructor injection. This is a common way to implement dependency injection in Spring applications.

Step 4: Create the REST controller

The controller exposes the API endpoint.

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @PostMapping
    public Employee saveEmployee(
            @RequestBody Employee employee) {
        return service.saveEmployee(employee);
    }
}

A client can send a POST request to /employees with a JSON request body:

{
  "name": "John",
  "email": "john@example.com"
}

The controller receives the request, the service handles the application logic, and the repository saves the entity through JPA and Hibernate.

Which concepts should you explain?

  • REST API development
  • @RestController
  • @RequestMapping and @PostMapping
  • @RequestBody
  • Entity mapping
  • JPA and Hibernate
  • Repository and service layers
  • Dependency injection
  • Database persistence

What the interviewer is looking for: Explain the responsibilities of each layer and how the request reaches the database. You should also understand that @PostMapping maps the HTTP request, @RequestBody binds the JSON body, and constructor injection supplies the required dependencies.

The example is intentionally simplified. A production API would normally also consider request DTOs, validation, appropriate HTTP status codes, and centralized exception handling.

Java Coding and Exception Handling Questions

8. Given a string, count the occurrence of each character.

This coding question tests string handling, loops, collections, and basic problem-solving.

Suppose the input string is "hello". We need to count how many times each character appears.

Approach 1: Using HashMap

A HashMap provides a straightforward solution:

String str = "hello";

Map<Character, Integer> countMap = new HashMap<>();

for (char ch : str.toCharArray()) {
    countMap.put(
        ch,
        countMap.getOrDefault(ch, 0) + 1
    );
}

System.out.println(countMap);

Expected character counts:

h = 1
e = 1
l = 2
o = 1

The order of entries printed by a HashMap is not guaranteed.

Here’s how the solution works:

  1. toCharArray() converts the string into a character array.
  2. The loop processes each character.
  3. getOrDefault(ch, 0) returns the existing count or zero if the character is not yet present.
  4. The count is incremented and stored back in the map.

When the second l appears, its previous count is one, so the updated count becomes two.

What the interviewer is looking for: You should be able to write the solution, explain getOrDefault(), and reason through the output. Depending on follow-up requirements, you may also need to handle spaces or distinguish uppercase from lowercase characters.

Approach 2: Without HashMap or counting utility methods

You can also solve the same problem using nested loops and a boolean array to track characters that have already been counted.

public class CharacterCount {
    public static void main(String[] args) {
        String str = "hello";
        boolean[] visited = new boolean[str.length()];

        for (int i = 0; i < str.length(); i++) {
            if (visited[i]) {
                continue;
            }

            int count = 1;

            for (int j = i + 1; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j)) {
                    count++;
                    visited[j] = true;
                }
            }

            System.out.println(
                str.charAt(i) + " = " + count
            );
        }
    }
}

Output:

h = 1
e = 1
l = 2
o = 1

Here’s how this approach works:

  1. The outer loop selects a character from the string.
  2. The inner loop compares it with the remaining characters.
  3. Whenever a match is found, the count increases and the matching position is marked as visited.
  4. Previously counted positions are skipped, so duplicate characters aren’t counted again.

This approach avoids HashMap, toCharArray(), and getOrDefault(). It still uses the basic String methods length() and charAt() to access characters.

Which approach should you use?

  • HashMap approach: More concise and generally suitable for character-frequency problems.
  • Nested-loop approach: Useful when the interviewer asks you to solve the problem without collections or counting utility methods.

The HashMap approach typically takes (O(n)) time on average, while the nested-loop approach takes (O(n^2)) time.

Interview tip: Practise both solutions. The important part isn’t just getting the output right; it’s explaining your logic, understanding the trade-offs, and adapting your solution to the interviewer’s constraints.

9. What will execute in this try-catch-finally code?

Consider the following code:

int a = 30;
int b = 40;
int c = 10;

try {
    int expression = (a * b) / (a - b + c);
    System.out.println(expression);
} catch (Exception e) {
    System.out.println("Exception");
} finally {
    System.out.println("Finally");
}

Before deciding the output, calculate the denominator:

a - b + c
= 30 - 40 + 10
= 0

The expression becomes:

1200 / 0

Java throws an ArithmeticException because integer division by zero is not allowed.

The println(expression) statement is skipped because the exception occurs before it can execute. The catch block then prints Exception, and the finally block prints Finally.

Output:

Exception
Finally

The finally block is generally used for cleanup operations that should run whether an exception occurs or not, although there are exceptional circumstances in which it may not execute.

What the interviewer is looking for: Be able to trace the execution order and explain why the exception occurs. Also remember that floating-point division by zero behaves differently from integer division by zero.

10. What does equals() do in Java?

The equals() method is used to compare objects for logical equality when the class implements or overrides it appropriately.

Compare these two strings:

String a = new String("Hello");
String b = new String("Hello");

System.out.println(a == b);
System.out.println(a.equals(b));

Output:

false
true

Why are the results different?

  • == checks whether the two references point to the same object.
  • equals() checks logical equality according to the class’s implementation.

The two strings are separate objects, so a == b returns false. However, both contain the same text, and the String class overrides equals() to compare string content. Therefore, a.equals(b) returns true.

One important detail: not every Java class automatically compares its object’s contents using equals(). If a class does not override the method, it inherits the implementation from Object, which compares references.

What the interviewer is looking for: Understand the difference between reference equality and logical equality. You should also know why equals() and hashCode() must be implemented consistently when custom objects are used in hash-based collections.

Bonus Interview Questions

The following questions were also part of the interview material, but they sit outside the main Java and Spring Boot discussion. They’re worth revising because backend developers often work with databases and SQL.

Bonus 1. How do you find the second-highest salary in SQL?

Assume you have an employee_master table with a salary column.

One approach is to use a subquery:

SELECT MAX(salary)
FROM employee_master
WHERE salary < (
    SELECT MAX(salary)
    FROM employee_master
);

The inner query finds the highest salary. The outer query finds the maximum salary below that value.

This returns the second-highest distinct salary, or NULL if no lower salary exists.

Another approach, supported by databases such as MySQL and PostgreSQL, is:

SELECT DISTINCT salary
FROM employee_master
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

The DISTINCT keyword removes duplicate salary values, while ORDER BY sorts them from highest to lowest. OFFSET 1 skips the highest distinct value.

Interview tip: Clarify whether the question asks for the second-highest distinct salary or the second row after sorting. The expected query depends on that requirement.

Final Thoughts

This interview covered several fundamentals that Java backend developers should be comfortable explaining: OOP, functional interfaces, collections, HashMap internals, Java versions, Spring Boot REST API development, coding logic, and exception handling.

The main lesson is that understanding the concepts matters just as much as knowing the syntax. For example, you should be able to explain how HashMap uses hashCode() and equals(), why dependency injection is useful, and how a request travels through a Spring Boot application’s layers.

If you’re preparing for a Backend Developer role requiring around three years of experience, use these questions as a practical revision exercise. Write the code yourself, trace the execution, and practise explaining your reasoning without relying on memorized answers.

That approach will help you prepare for similar technical interviews more effectively.

A quick note: These questions are based on one real interview experience. Interview questions can vary depending on the company, role, interviewer, and project requirements, so your experience may be different. Use this guide to prepare for similar questions, not as a guaranteed list of questions you’ll be asked.


Frequently Asked Questions

What Java interview questions are asked for 3 years of experience?

Core Java questions may cover OOP, functional interfaces, collections, HashMap internals, Java 8 features, string handling, and exception handling. Practical coding questions may also test how well you apply these concepts.

What Spring Boot concepts should a backend developer prepare?

Focus on REST controllers, service and repository layers, dependency injection, JPA, Hibernate, and database persistence. Practise explaining how an API receives a request and saves data.

Are coding questions important in Java backend interviews?

Yes, coding exercises help assess problem-solving and implementation skills. The character-frequency problem in this interview is a useful example because it combines strings, loops, and HashMap.

Should I prepare SQL for a Java developer interview?

Yes. SQL may be relevant to backend roles that involve database access. Practise subqueries, aggregate functions, sorting, joins, and questions such as finding the second-highest distinct salary.