Interview Questions

1) What are the main features of Java?


Java has several features:

  • Object-Oriented: Supports encapsulation, inheritance, and polymorphism.
  • Platform-Independent: Java code can run on any machine with a Java Runtime Environment (JRE).
  • Secure: It has built-in security mechanisms like bytecode verification and runtime security.
  • Multithreaded: Supports concurrent execution of two or more parts of a program.
  • Distributed: Easily handles distributed applications with Java's networking capabilities.
  • Robust: Java provides automatic memory management (garbage collection) and exception handling.

2) What is the difference between JDK, JRE, and JVM?


  • JVM: Executes Java bytecode and makes Java platform-independent.
  • JRE: A runtime environment that includes the JVM and necessary libraries to run Java applications.
  • JDK: A development kit that includes JRE, JVM, and tools for developing Java applications (e.g., the compiler).

3) What is the difference between "==" and "equals()" in Java?


  • "==": Compares object references, i.e., whether two variables point to the same memory location.
  • equals(): Compares the actual contents of objects for equality. For example, comparing two strings using .equals() checks if their content is the same.

Example:

String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println(s1 == s2); // false (different memory locations)
System.out.println(s1.equals(s2)); // true (same content)

 

4) What is the difference between an abstract class and an interface?


  • Abstract Class: Can have both abstract methods (without implementation) and concrete methods (with implementation). A class can inherit only one abstract class.
  • Interface: Can have only abstract methods (before Java 8) and default or static methods (from Java 8 onward). A class can implement multiple interfaces.

Example:

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

interface Swimmer {
    void swim();
}

class Dog extends Animal implements Swimmer {
    void sound() {
        System.out.println("Bark");
    }
    public void swim() {
        System.out.println("Dog swims");
    }
}

 

5) What is the purpose of the final keyword in Java?


  • final variable: The value cannot be changed once assigned.
  • final method: The method cannot be overridden.
  • final class: The class cannot be subclassed.

Example:

final int x = 10;
// x = 20; // Error: Cannot assign a value to final variable x

 

6) What is a Singleton class?


A Singleton class ensures that only one instance of the class is created and provides a global point of access to it. It is useful for managing resources like database connections.

Example:

class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

 

7) What is the difference between HashMap and Hashtable?


  • HashMap: Not synchronized, allows one null key and multiple null values.
  • Hashtable: Synchronized, does not allow null keys or values.

Example:

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1"); // Allowed

Hashtable<String, String> hashTable = new Hashtable<>();
hashTable.put("key1", "value1"); // Allowed, but no nulls allowed.

 

8) What is the purpose of the transient keyword?


The transient keyword is used to indicate that a field should not be serialized when the object is being serialized.

Example:

class User implements Serializable {
    String name;
    transient int password; // Will not be serialized
}

 

9) What is garbage collection in Java?


Garbage collection is the process of automatically reclaiming memory from objects that are no longer in use. Java provides garbage collectors that remove unreferenced objects.

Example:

class Test {
    public void finalize() {
        System.out.println("Object is garbage collected");
    }
}

 

10) What is the difference between String, StringBuilder, and StringBuffer?


  • String: Immutable (cannot be changed after creation).
  • StringBuilder: Mutable and not synchronized (faster for single-threaded environments).
  • StringBuffer: Mutable and synchronized (slower but thread-safe).

Example:

String str = "Hello";
str = str + " World"; // New object created

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing object

 

11) What is multithreading in Java?


Multithreading allows a program to execute multiple tasks concurrently, improving performance on multi-core systems. In Java, threads can be created by extending the Thread class or implementing the Runnable interface.

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // Starts the thread
    }
}

 

12) What is the difference between ArrayList and LinkedList?


  • ArrayList: Backed by dynamic arrays, offers fast random access and slower insertions/removals.
  • LinkedList: Backed by a doubly linked list, offers slower random access but faster insertions/removals.

13) What is the difference between final, finally, and finalize()?


  • final: Used for constants, methods, and classes.
  • finally: Block that executes after try-catch, regardless of exceptions.
  • finalize(): Method that is called before an object is garbage collected.

14) Explain the term "Java Reflection".


Java Reflection is an API that allows you to inspect and manipulate the runtime properties of classes, methods, and fields. It is widely used for creating flexible frameworks.

Example:

Class<?> clazz = Class.forName("java.lang.String");
Method[] methods = clazz.getMethods();
for (Method method : methods) {
    System.out.println(method.getName());
}

 

15) What is method overloading?


Method overloading occurs when multiple methods in a class have the same name but different parameter lists (number or types of parameters).

Example:

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

 

16) What is method overriding?


Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

Example:

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

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

 

17) What is the use of super in Java?


The super keyword is used to refer to the immediate parent class of a class. It can be used to access parent class methods, constructors, and fields.

Example:

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

class Dog extends Animal {
    void sound() {
        super.sound(); // Calling parent class method
        System.out.println("Bark");
    }
}

 

18) What is an exception in Java?


An exception is an event that disrupts the normal flow of a program's execution. Java provides exception handling mechanisms like try, catch, and finally.

19) What are checked and unchecked exceptions in Java?


  • Checked exceptions: Exceptions that are checked at compile-time, e.g., IOException.
  • Unchecked exceptions: Exceptions that are not checked at compile-time, e.g., NullPointerException.

20) What is the use of the try-catch block?


The try-catch block is used to handle exceptions. Code that may throw an exception is placed in the try block, and exceptions are handled in the catch block.

Example:

try {
    int a = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Error: Division by zero");
}

 

21) What is the difference between throw and throws?


  • throw: Used to explicitly throw an exception from a method.
  • throws: Declares that a method might throw an exception.

22) What is a constructor in Java?


A constructor is a special method used to initialize objects. It has the same name as the class and no return type.

Example:

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

 

23) What is the purpose of the this keyword?


The this keyword refers to the current object instance. It is often used to differentiate between class members and method parameters with the same name.

24) What is the difference between == and .equals() for comparing two strings?


  • ==: Compares references (whether two variables point to the same memory location).
  • .equals(): Compares the actual contents of two objects.

Example:

String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true

 

25) What is the default method in an interface?


A default method allows you to define a method with a body inside an interface. This was introduced in Java 8 to allow backward compatibility when adding new methods to interfaces.

Example:

interface MyInterface {
    default void sayHello() {
        System.out.println("Hello");
    }
}

 

26) What are the collection classes in Java?


Java Collections include classes like ArrayList, HashMap, LinkedList, TreeSet, HashSet, etc., used for storing and manipulating groups of objects.

27) What is the use of Iterator in Java?


An Iterator allows you to traverse through a collection and safely remove elements while iterating.

Example:

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

 

28) What is the difference between Comparable and Comparator?


  • Comparable: Defines a natural ordering for objects in a class (using compareTo()).
  • Comparator: Provides a way to define custom ordering (using compare()).

29) What is the use of volatile keyword?


The volatile keyword ensures that a variable's value is always read from and written to the main memory, preventing caching issues in multi-threaded environments.

Example:

private volatile boolean flag = false;

 

30) What is the difference between ArrayList and Vector?


  • ArrayList: It is not synchronized, meaning it is not thread-safe. It is faster compared to Vector in single-threaded environments.
  • Vector: It is synchronized, meaning it is thread-safe but slower compared to ArrayList.

31) What is an enumeration (enum) in Java?


An enum in Java is a special class that represents a group of constants (unchangeable variables). Enums provide a type-safe way to handle a fixed set of constants.

Example:

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

 

32) What is the difference between StringBuilder and StringBuffer?


  • StringBuilder: Not synchronized, faster for single-threaded environments.
  • StringBuffer: Synchronized, slower but thread-safe for multi-threaded environments.

33) What are the different types of inner classes in Java?


Java supports four types of inner classes:

  • Member Inner Class: Defined inside a class and has access to all members of the outer class.
  • Static Nested Class: A static class defined inside another class.
  • Local Inner Class: Defined inside a method.
  • Anonymous Inner Class: A class with no name, used to instantiate objects.

34) What is the super() keyword in Java?


The super() keyword is used to call the constructor of the parent class. It must be the first statement in the subclass constructor.

Example:

class Parent {
    Parent() {
        System.out.println("Parent class constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // Calls the parent class constructor
        System.out.println("Child class constructor");
    }
}

 

35) What is the purpose of the instanceof operator?


The instanceof operator checks whether an object is an instance of a particular class or implements a specific interface.

Example:

String str = "Hello";
System.out.println(str instanceof String); // true

 

36) What is the difference between wait() and sleep() in Java?


  • wait(): It is used in synchronization blocks to make the current thread wait until another thread notifies it.
  • sleep(): It is a static method of Thread that makes the thread sleep for a specified amount of time.

Example:

Thread.sleep(1000); // Makes the current thread sleep for 1 second

 

37) What is the use of synchronized keyword in Java?


The synchronized keyword is used to ensure that a method or block of code is accessed by only one thread at a time, which is essential for thread safety.

Example:

public synchronized void increment() {
    count++;
}

 

38) What is a deadlock in Java?


A deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. This situation arises when threads hold resources while waiting for others to release their resources.

39) What is the clone() method in Java?


The clone() method creates a copy of an object. The object class implements the Cloneable interface, and it must override the clone() method.

Example:

class Person implements Cloneable {
    String name;

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

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

 

40) What is the difference between HashMap and TreeMap?


  • HashMap: Does not maintain any order of elements. It uses hash values for indexing.
  • TreeMap: Maintains a sorted order of elements, sorted according to their natural order or a comparator provided during creation.

41) What is the purpose of the default keyword in Java 8 interfaces?


Java 8 introduced the default keyword in interfaces to provide concrete methods with default implementation, allowing backward compatibility when adding new methods to interfaces.

Example:

interface MyInterface {
    default void sayHello() {
        System.out.println("Hello from MyInterface");
    }
}

 

42) What is the purpose of finally block in exception handling?


The finally block is always executed after the try-catch blocks, regardless of whether an exception was thrown or not. It is used for cleanup operations like closing file streams.

43) What is the difference between StringBuilder and String in Java?


  • String: Immutable, meaning once a String is created, it cannot be changed.
  • StringBuilder: Mutable, which means its contents can be modified.

44) What is the use of the continue statement in Java?


The continue statement is used to skip the current iteration of a loop and continue with the next iteration.

Example:

for (int i = 0; i < 5; i++) {
    if (i == 3) continue; // Skip 3
    System.out.println(i);
}

 

45) What is the break statement used for in Java?


The break statement is used to exit a loop or a switch case prematurely.

Example:

for (int i = 0; i < 5; i++) {
    if (i == 3) break; // Exit the loop when i is 3
    System.out.println(i);
}

 

46) What is the difference between == and equals() for comparing objects in Java?


  • ==: Compares references (i.e., whether two variables point to the same object in memory).
  • equals(): Compares the actual content of the objects.

47) What is the difference between List, Set, and Map in Java Collections?


  • List: An ordered collection that allows duplicate elements (e.g., ArrayList).
  • Set: A collection that does not allow duplicates (e.g., HashSet).
  • Map: A collection of key-value pairs, where each key is unique (e.g., HashMap).

48) What is the role of Object class in Java?


The Object class is the root class of all Java classes. Every class in Java implicitly inherits from Object. It provides basic methods like equals(), hashCode(), toString(), and clone().

49) What is a HashSet in Java?


A HashSet is a collection that does not allow duplicate elements and does not maintain any order of its elements. It is backed by a HashMap.

Example:

Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate element
System.out.println(set); // Output: [Apple, Banana]

 

50) What is the Iterator interface in Java?


The Iterator interface provides methods for traversing a collection, allowing you to safely access elements and remove them during iteration.

Example:

List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

 

51) What is the Thread.sleep() method?


The Thread.sleep() method pauses the current thread for the specified number of milliseconds, allowing other threads to execute.

Example:

try {
    Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
    e.printStackTrace();
}

 

52) What are the differences between throw and throws in Java?


  • throw: Used to explicitly throw an exception.
  • throws: Used in a method signature to declare that a method might throw exceptions.

Example:

void myMethod() throws IOException { // Throws declaration
    throw new IOException("IOException occurred");
}

 

53) What is a try-catch-finally block in Java?


The try-catch-finally block is used for exception handling. Code that may throw an exception is placed inside the try block, exceptions are caught in the catch block, and the finally block executes regardless of exception occurrence.

54) What is a Checked Exception in Java?


A checked exception is an exception that is checked at compile-time. The program must handle these exceptions explicitly with a try-catch block or declare them using throws.

55) What is an Unchecked Exception in Java?


An unchecked exception (also known as a runtime exception) is an exception that is not checked at compile-time. These exceptions are subclasses of RuntimeException. The program does not have to explicitly handle them with a try-catch block or declare them using throws.

Example:

public class Example {
    public static void main(String[] args) {
        int a = 5 / 0; // ArithmeticException: Division by zero
    }
}

 

56) What is the difference between equals() and hashCode() in Java?


  • equals(): Compares the content of two objects to check if they are logically equivalent.
  • hashCode(): Returns an integer value that is used to identify the object. The hashCode() method is used in hashing-based collections (like HashMap, HashSet).

Example:

String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // true
System.out.println(str1.hashCode() == str2.hashCode()); // true

 

57) What is the assert keyword in Java?


The assert keyword is used for debugging purposes. It tests a boolean expression, and if the expression evaluates to false, an AssertionError is thrown.

Example:

int x = 10;
assert x > 0 : "x must be positive"; // If x is not positive, an AssertionError is thrown

 

58) What is the volatile keyword in Java?


The volatile keyword is used to indicate that a variable's value will be modified by multiple threads. It ensures that the latest value of the variable is always visible to all threads.

Example:

private volatile boolean flag = false;

 

59) What is a Lambda Expression in Java?


A lambda expression is a concise way to represent an anonymous function (i.e., a function with no name) that can be passed around as an argument or assigned to a variable. Introduced in Java 8, it is commonly used with functional interfaces.

Example:

// Syntax: (parameters) -> expression
Runnable r = () -> System.out.println("Hello, Lambda!");
r.run(); // Output: Hello, Lambda!