Java Interview Questions and Answers
100%

Java Interview Questions and Answers

This lesson covers important Java interview questions for beginners and intermediate learners. These questions help students prepare for technical interviews, practical exams, and entry-level developer jobs.

Interview Tip: Understand each answer and practice explaining it in your own words. For programming questions, write and run the code yourself.

1. What Is Java?

Java is a high-level, class-based programming language used to develop desktop applications, web applications, backend systems, and many other types of software.

Important features include:

  • Object-oriented programming support
  • Platform independence through the JVM
  • Automatic memory management through garbage collection
  • Exception handling
  • Multithreading support
  • A large standard library

2. What Is the Difference Between JDK, JRE, and JVM?

Term Meaning
JDK Java Development Kit; provides development tools such as the compiler.
JRE Java Runtime Environment; traditionally describes the runtime components needed to run Java applications.
JVM Java Virtual Machine; executes Java bytecode.

Modern Java distributions may package runtime components differently, and a separate JRE download is not always provided.

3. Why Is Java Platform Independent?

Java source code is compiled into bytecode. A compatible JVM on a supported operating system can execute that bytecode.

Source Code (.java)
        |
        v
Java Compiler (javac)
        |
        v
Bytecode (.class)
        |
        v
Compatible JVM
        |
        v
Program Execution

This is why Java is commonly described as "Write Once, Run Anywhere", provided a compatible runtime and required dependencies are available.

4. What Is a Class and an Object?

A class defines fields and methods. An object is an instance of a class.

class Student {
    String name = "Rahul";

    void display() {
        System.out.println(name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.display();
    }
}

Output:

Rahul

5. What Are the Four Pillars of OOP?

  1. Encapsulation: Bundling data and methods while controlling access to internal state.
  2. Inheritance: Creating a class based on another class.
  3. Polymorphism: Allowing the same operation or method name to behave differently in different contexts.
  4. Abstraction: Hiding implementation details and exposing essential behavior.

6. What Is Inheritance in Java?

Inheritance allows a class to acquire accessible fields and methods from another class using the extends keyword.

class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}

Output:

Animal is eating
Dog is barking

7. What Is Polymorphism?

Polymorphism means that the same method name or operation can represent different behavior.

Java supports method overloading and method overriding.

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();

        System.out.println(c.add(2, 3));
        System.out.println(c.add(2, 3, 4));
    }
}

Output:

5
9

This is method overloading because the method name is the same but the parameter lists differ.

8. What Is the Difference Between Overloading and Overriding?

Overloading Overriding
Methods have the same name but different parameter lists. A subclass provides a new implementation of an inherited instance method.
Usually occurs within the same class. Occurs between a superclass and subclass.
Resolved using the method's parameter types and arguments at compile time. Overridden instance-method behavior is selected dynamically at runtime.

9. What Is a Constructor?

A constructor initializes a new object. Its name matches the class name, and it has no return type.

class Student {
    String name;

    Student(String studentName) {
        name = studentName;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Amit");
        System.out.println(s.name);
    }
}

Output:

Amit

10. What Is the Difference Between an Interface and an Abstract Class?

Interface Abstract Class
Defines a contract that implementing classes agree to follow. Provides a base class that can contain shared implementation and state.
A class can implement multiple interfaces. A class can extend only one class.
Can contain abstract, default, static, and private methods, subject to Java language rules. Can contain abstract and concrete methods, constructors, and instance fields.

11. What Is Encapsulation?

Encapsulation combines data and related methods in a class and controls how the data is accessed.

class Student {
    private int age;

    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        }
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();

        s.setAge(20);
        System.out.println(s.getAge());
    }
}

Output:

20

12. What Is the Difference Between == and equals()?

For object references, == checks whether two references point to the same object. The equals() method can compare logical content when the class implements it appropriately.

public class Main {
    public static void main(String[] args) {
        String a = new String("Java");
        String b = new String("Java");

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

Output:

false
true

13. What Is Exception Handling?

Exception handling allows a program to handle certain errors or exceptional conditions using try, catch, finally, throw, and throws.

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}

Output:

Cannot divide by zero

14. What Is the Difference Between Checked and Unchecked Exceptions?

  • Checked exceptions: The compiler requires them to be caught or declared when required by the method's signature. Example: IOException.
  • Unchecked exceptions: These are subclasses of RuntimeException. Example: NullPointerException.

15. What Is a String in Java?

A String represents a sequence of characters. String objects are immutable, meaning their contents cannot be changed after creation.

public class Main {
    public static void main(String[] args) {
        String name = "Java";

        System.out.println(name.length());
        System.out.println(name.toUpperCase());
    }
}

Output:

4
JAVA

16. What Is the Difference Between String, StringBuilder, and StringBuffer?

Class Description
String Immutable character sequence.
StringBuilder Mutable character sequence without synchronized methods; often suitable for single-threaded string modification.
StringBuffer Mutable character sequence with synchronized methods.

17. What Is an Array?

An array stores a fixed number of values of the same type. Its elements are accessed using zero-based indexes.

public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};

        System.out.println(numbers[0]);
        System.out.println(numbers.length);
    }
}

Output:

10
3

18. What Is the Java Collections Framework?

The Collections Framework provides interfaces and classes for storing and working with groups of objects.

  • List: An ordered collection that can contain duplicates.
  • Set: A collection that does not allow duplicate elements.
  • Queue: A collection designed for holding elements before processing.
  • Map: Stores key-value mappings and is separate from the Collection interface hierarchy.
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Rahul");
        names.add("Amit");

        System.out.println(names);
    }
}

Output:

[Rahul, Amit]

19. What Is Multithreading?

Multithreading allows a program to execute multiple threads of work. Threads share the process's memory, so shared data may require synchronization.

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("Thread is running");
        });

        t.start();
    }
}

Possible Output:

Thread is running

The call to start() schedules the thread to run independently. Calling run() directly would execute the method as an ordinary method call instead.

20. What Is the Difference Between final, finally, and finalize()?

  • final: Used to prevent reassignment of a variable, overriding of a method, or extension of a class, depending on where it is applied.
  • finally: A block commonly used for cleanup after a try/catch construct.
  • finalize(): A deprecated lifecycle mechanism that should not be used for resource cleanup.
Best Practice: Use try-with-resources for resources that implement AutoCloseable, such as file streams and database connections.

21. What Is the static Keyword?

The static keyword declares a member associated with the class rather than with each individual object.

class Student {
    static String school = "Soopro Pathshala";
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Student.school);
    }
}

Output:

Soopro Pathshala

22. What Is the this Keyword?

The this keyword refers to the current object. It is often used to distinguish an instance field from a parameter with the same name.

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}

Here, this.name refers to the object's field, while name refers to the constructor parameter.

23. What Is the super Keyword?

The super keyword refers to superclass members and can be used to invoke a superclass constructor.

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void sound() {
        super.sound();
        System.out.println("Dog barks");
    }
}

24. What Is Garbage Collection?

Garbage collection automatically reclaims heap memory used by objects that are no longer reachable, subject to the JVM's implementation and execution decisions.

Java developers normally do not manually free object memory. However, they should still close files, sockets, and database resources when finished with them.

25. What Is a Package in Java?

A package groups related classes and interfaces. It helps organize code and avoid naming conflicts.

package myapp;

public class Student {
    public void display() {
        System.out.println("Student class");
    }
}

The package declaration must appear before imports and class declarations in a source file.

26. What Is JDBC?

JDBC stands for Java Database Connectivity. It provides APIs that Java applications use to connect to databases and execute SQL.

Common JDBC interfaces and classes include:

  • Connection
  • PreparedStatement
  • Statement
  • ResultSet
  • DriverManager
Interview Tip: Prefer PreparedStatement for SQL statements containing user-provided values. It supports parameter binding and helps prevent SQL injection when used correctly.

27. What Are Lambda Expressions?

A lambda expression provides a concise implementation of a functional interface, which has one abstract method.

interface Greeting {
    void sayHello();
}

public class Main {
    public static void main(String[] args) {
        Greeting g = () -> System.out.println("Hello Java");

        g.sayHello();
    }
}

Output:

Hello Java

28. What Is the Difference Between ArrayList and LinkedList?

ArrayList LinkedList
Uses a resizable array internally. Uses a doubly linked list internally.
Usually provides fast indexed access. Indexed access requires traversing the list.
Inserting or removing elements in the middle can require shifting elements. Insertion or removal can be efficient once the position is reached, but finding that position may require traversal.

29. What Is an Enum in Java?

An enum defines a fixed set of named constants.

enum Day {
    MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.MONDAY;

        System.out.println(today);
    }
}

Output:

MONDAY

30. What Is the Difference Between break and continue?

  • break: Exits the nearest enclosing loop or switch statement.
  • continue: Skips the remainder of the current loop iteration and proceeds to the next iteration when applicable.
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
4
5

31. Java Coding Questions for Interviews

Practice writing programs for the following questions:

  1. Reverse a string without using a built-in reverse method.
  2. Check whether a number is prime.
  3. Find the factorial of a number.
  4. Check whether a string is a palindrome.
  5. Find the largest element in an array.
  6. Find duplicate elements in an array.
  7. Count the vowels in a string.
  8. Print the Fibonacci series.
  9. Sort an array in ascending order.
  10. Remove duplicate elements from a list.

32. Common HR Interview Questions for Java Developers

  1. Tell me about yourself.
    Explain your education, Java skills, projects, and career goals.
  2. Why do you want to become a Java developer?
    Discuss your interest in programming and building software.
  3. Describe a project you have developed.
    Explain the problem, technologies, your contribution, and the result.
  4. How do you solve programming problems?
    Explain how you understand requirements, design a solution, test it, and debug errors.
  5. What do you do when you do not know an answer?
    Explain that you clarify the problem, research reliable documentation, experiment, and learn.

Java Interview Questions - Quick Quiz

Choose the correct answer for each question.

1. Which component executes Java bytecode?



2. Which keyword is used to inherit a class in Java?



3. Which collection interface does not allow duplicate elements?