Site icon Geeks kepler

Top 50 Java Interview Questions and Answers for 2025: Ace Your Tech Interview

Top 50 Java Interview Questions and Answers for 2025: Ace Your Tech Interview

Basic Java Questions

  1. What is Java, and why is it popular?
    Answer: Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It’s popular because it’s platform-independent (runs on any device with a JVM), versatile (used in web, mobile, and enterprise apps), and has a huge community with extensive libraries.
  2. What is the difference between JDK, JRE, and JVM?
    Answer:
    • JDK (Java Development Kit): Tools for developing Java apps, including the compiler and libraries.
    • JRE (Java Runtime Environment): Provides the runtime environment to execute Java apps, including JVM and libraries.
    • JVM (Java Virtual Machine): The engine that runs Java bytecode, making Java platform-independent.
  3. What is the main method in Java?
    Answer: The main method is the entry point of a Java program. It has the signature public static void main(String[] args) and is where the program starts execution.
  4. Why is Java platform-independent?
    Answer: Java code is compiled into bytecode, which the JVM interprets on any platform (Windows, macOS, Linux). This “write once, run anywhere” feature makes Java platform-independent.
  5. What are the main features of Java?
    Answer: Key features include being object-oriented, platform-independent, robust (with strong error handling), secure, multithreaded, and having a rich API.
  6. What is the difference between a class and an object?
    Answer: A class is a blueprint that defines properties and behaviors (methods). An object is an instance of a class, created to use those properties and behaviors.
  7. What is the difference between public, private, and protected access modifiers?
    Answer:
    • public: Accessible from everywhere.
    • private: Accessible only within the same class.
    • protected: Accessible within the same package and in subclasses (even in different packages).
  8. What is a constructor in Java?
    Answer: A constructor is a special method in a class used to initialize objects. It has the same name as the class and no return type. For example:

    java

    class Car {
        Car() {
            System.out.println("Car object created!");
        }
    }
  9. What is the difference between == and .equals() in Java?
    Answer:
    • == compares memory addresses (references) of objects.
    • .equals() compares the actual content or values of objects (e.g., for Strings). For example:

      java

      String s1 = new String("hello");
      String s2 = new String("hello");
      System.out.println(s1 == s2); // false (different references)
      System.out.println(s1.equals(s2)); // true (same content)
  10. What is a package in Java?
    Answer: A package is a group of related classes and interfaces, used to organize code and avoid naming conflicts. For example, java.util contains utility classes like ArrayList.

Object-Oriented Programming (OOP) Questions

  1. What are the four pillars of OOP in Java?
    Answer:
    • Encapsulation: Bundling data and methods, restricting access using access modifiers.
    • Inheritance: One class inherits properties and methods from another using extends.
    • Polymorphism: Objects can take multiple forms (method overriding or overloading).
    • Abstraction: Hiding complex details and showing only essential features (using abstract classes or interfaces).
  2. What is inheritance, and how is it implemented in Java?
    Answer: Inheritance allows a class (subclass) to inherit properties and methods from another class (superclass) using the extends keyword. Example:

    java

    class Animal {
        void eat() { System.out.println("Eating..."); }
    }
    class Dog extends Animal {
        void bark() { System.out.println("Barking..."); }
    }
  3. What is polymorphism in Java?
    Answer: Polymorphism allows objects to be treated as instances of their parent class. It’s achieved through:
    • Method overloading: Same method name, different parameters.
    • Method overriding: Subclass provides a specific implementation of a parent class method.
  4. What is an abstract class?
    Answer: An abstract class is a class that cannot be instantiated and may contain abstract methods (without implementation). It’s defined with the abstract keyword. Example:

    java

    abstract class Shape {
        abstract void draw();
    }
  5. What is an interface in Java?
    Answer: An interface is a blueprint of methods (without implementation) that a class must implement. It’s defined with the interface keyword. Example:

    java

    interface Vehicle {
        void start();
    }
    class Car implements Vehicle {
        public void start() { System.out.println("Car started"); }
    }
  6. Can a class implement multiple interfaces?
    Answer: Yes, a class can implement multiple interfaces using commas. Example:

    java

    interface A { void methodA(); }
    interface B { void methodB(); }
    class Test implements A, B {
        public void methodA() { System.out.println("A"); }
        public void methodB() { System.out.println("B"); }
    }
  7. What is the difference between an abstract class and an interface?
    Answer:
    • Abstract classes can have both abstract and concrete methods; interfaces have only abstract methods (or default methods since Java 8).
    • A class can extend only one abstract class but implement multiple interfaces.
    • Abstract classes can have instance variables; interfaces cannot (until Java 8’s static final fields).
  8. What is method overloading?
    Answer: Method overloading is when multiple methods in the same class have the same name but different parameters (number, type, or order). Example:

    java

    class Calculator {
        int add(int a, int b) { return a + b; }
        double add(double a, double b) { return a + b; }
    }
  9. What is method overriding?
    Answer: Method overriding is when a subclass provides a specific implementation of a method already defined in its superclass. It requires the same method signature. Example:

    java

    class Animal {
        void sound() { System.out.println("Generic sound"); }
    }
    class Dog extends Animal {
        void sound() { System.out.println("Woof"); }
    }
  10. What is the super keyword used for?
    Answer: The super keyword refers to the parent class. It’s used to:
    • Call the parent class’s constructor (super()).
    • Access parent class methods or fields. Example:

    java

    class Child extends Parent {
        Child() {
            super(); // Calls Parent's constructor
        }
    }

Core Java Concepts

  1. What is the difference between final, finally, and finalize?
    Answer:
    • final: A keyword to make a variable, method, or class unchangeable.
    • finally: A block used in try-catch to execute code regardless of an exception.
    • finalize: A method called by the garbage collector before an object is destroyed.
  2. What is exception handling in Java?
    Answer: Exception handling manages runtime errors using try, catch, finally, and throw. Example:

    java

    try {
        int x = 10 / 0;
    } catch (ArithmeticException e) {
        System.out.println("Cannot divide by zero!");
    }
  3. What is the difference between checked and unchecked exceptions?
    Answer:
    • Checked exceptions: Compile-time exceptions (e.g., IOException) that must be handled or declared.
    • Unchecked exceptions: Runtime exceptions (e.g., NullPointerException) that don’t require explicit handling.
  4. What is the throws keyword?
    Answer: The throws keyword in a method signature declares that the method can throw one or more exceptions. Example:

    java

    void myMethod() throws IOException {
        // Code that may throw IOException
    }
  5. What is a String in Java, and is it mutable?
    Answer: A String is a class in Java representing a sequence of characters. It is immutable, meaning its value cannot be changed after creation. Example:

    java

    String s = "hello";
    s = s + " world"; // Creates a new String object
  6. What is the difference between String, StringBuilder, and StringBuffer?
    Answer:
    • String: Immutable, good for fixed text.
    • StringBuilder: Mutable, not thread-safe, faster for single-threaded operations.
    • StringBuffer: Mutable, thread-safe, slower due to synchronization.
  7. What is the this keyword used for?
    Answer: The this keyword refers to the current object. It’s used to:
    • Differentiate instance variables from local variables.
    • Call another constructor in the same class. Example:

    java

    class Person {
        String name;
        Person(String name) {
            this.name = name; // Refers to instance variable
        }
    }
  8. What is a static method in Java?
    Answer: A static method belongs to the class, not an instance, and is called using the class name. Example:

    java

    class MathUtils {
        static int square(int x) { return x * x; }
    }
    // Call: MathUtils.square(5);
  9. What is a static variable?
    Answer: A static variable belongs to the class, not objects, and is shared across all instances. Example:

    java

    class Counter {
        static int count = 0;
        Counter() { count++; }
    }
  10. What is the difference between ArrayList and LinkedList?
    Answer:
    • ArrayList: Uses a dynamic array, fast for random access but slow for insertions/deletions.
    • LinkedList: Uses a doubly-linked list, fast for insertions/deletions but slow for random access.

Advanced Java Questions

  1. What is multithreading in Java?
    Answer: Multithreading allows multiple threads to run concurrently in a program, improving performance. Threads can be created by extending Thread or implementing Runnable. Example:

    java

    class MyThread implements Runnable {
        public void run() { System.out.println("Thread running"); }
    }
  2. What is the difference between Thread and Runnable?
    Answer:
    • Thread is a class that represents a thread.
    • Runnable is an interface with a run() method that defines the task a thread will execute. Runnable is preferred for flexibility (allows class to extend another class).
  3. What is synchronization in Java?
    Answer: Synchronization ensures that only one thread can access a resource at a time, preventing data inconsistency. It’s achieved using the synchronized keyword. Example:

    java

    synchronized void sharedMethod() {
        // Thread-safe code
    }
  4. What is a deadlock in Java?
    Answer: A deadlock occurs when two or more threads wait for each other to release resources, causing all to be stuck. Example: Thread A holds Resource 1 and waits for Resource 2, while Thread B holds Resource 2 and waits for Resource 1.
  5. What is the volatile keyword?
    Answer: The volatile keyword ensures that a variable’s value is always read from and written to main memory, preventing thread caching issues. Example:

    java

    volatile boolean flag = false;
  6. What is the Java Collections Framework?
    Answer: It’s a set of classes and interfaces (e.g., List, Set, Map) for storing and manipulating groups of data. Example: ArrayList, HashMap, HashSet.
  7. What is the difference between HashMap and HashTable?
    Answer:
    • HashMap: Not thread-safe, allows null keys/values, faster.
    • HashTable: Thread-safe, doesn’t allow nulls, slower due to synchronization.
  8. What is a HashSet?
    Answer: A HashSet is a collection that stores unique elements using a hash table. It doesn’t maintain insertion order and allows one null element.
  9. What is the difference between Iterator and ListIterator?
    Answer:
    • Iterator: Traverses collections (e.g., List, Set) in one direction, supports remove().
    • ListIterator: Traverses List only, supports forward/backward traversal and add()/set() operations.
  10. What is the Comparable interface?
    Answer: The Comparable interface defines a compareTo() method for natural ordering of objects. Example:

    java

    class Person implements Comparable<Person> {
        int age;
        public int compareTo(Person p) { return this.age - p.age; }
    }

Java 8 and Beyond

  1. What are lambda expressions in Java?
    Answer: Lambda expressions provide a concise way to implement functional interfaces (interfaces with one abstract method). Example:

    java

    (a, b) -> a + b; // Lambda for adding two numbers
  2. What is the Stream API in Java?
    Answer: The Stream API processes collections of data in a functional style (e.g., filtering, mapping). Example:

    java

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
    numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println); // Prints 2, 4
  3. What is the Optional class in Java?
    Answer: Optional is a container that may or may not hold a value, used to avoid NullPointerException. Example:

    java

    Optional<String> name = Optional.ofNullable(null);
    System.out.println(name.orElse("Unknown")); // Prints "Unknown"
  4. What are default methods in interfaces?
    Answer: Default methods provide a default implementation in interfaces, allowing backward compatibility. Example:

    java

    interface MyInterface {
        default void defaultMethod() { System.out.println("Default"); }
    }
  5. What is the difference between map() and flatMap() in Streams?
    Answer:
    • map(): Transforms each element into a single result (1:1 mapping).
    • flatMap(): Transforms each element into a stream of results and flattens it (1:many mapping).

Miscellaneous Questions

  1. What is garbage collection in Java?
    Answer: Garbage collection automatically reclaims memory from objects that are no longer referenced, managed by the JVM. The System.gc() method suggests running it, but it’s not guaranteed.
  2. What is the try-with-resources statement?
    Answer: It automatically closes resources (e.g., files) that implement AutoCloseable. Example:

    java

    try (FileReader fr = new FileReader("file.txt")) {
        // Use file
    } // fr is closed automatically
  3. What is the difference between Array and ArrayList?
    Answer:
    • Array: Fixed-size, primitive or object type, faster for simple operations.
    • ArrayList: Dynamic size, only objects, part of the Collections Framework.
  4. What is the transient keyword?
    Answer: The transient keyword prevents a variable from being serialized. Example:

    java

    class User implements Serializable {
        transient String password; // Not serialized
    }
  5. What is the purpose of the equals() and hashCode() methods?
    Answer:
    • equals(): Checks if two objects are logically equal (content-based).
    • hashCode(): Returns an integer hash code for an object, used in hash-based collections like HashMap. They should be consistent: if a.equals(b), then a.hashCode() == b.hashCode().
Exit mobile version