Interview Questions

1) What are the main features of Java?


Answer: Java is:

  • Object-Oriented: Everything is treated as an object.
  • Platform-Independent: Write Once, Run Anywhere (WORA).
  • Secure: Provides a secure execution environment.
  • Multithreaded: Supports concurrent execution.
  • Distributed: Supports web services, remote method invocation (RMI).
  • Robust: Exception handling and garbage collection.

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


  • JVM (Java Virtual Machine): Executes Java bytecode and ensures platform independence.
  • JRE (Java Runtime Environment): Provides libraries and JVM required to run Java applications.
  • JDK (Java Development Kit): Includes JRE, JVM, and development tools like compilers.

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


  • "==" compares object references (memory location).
  • equals() compares the contents of objects (for string, it compares the value).

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


  • Abstract Class: Can have both abstract and concrete methods. It allows one constructor and can maintain state (fields).
  • Interface: Can only have abstract methods (until Java 8). It cannot have instance variables.

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


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

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's used to represent a single instance of an object.

7) What is the difference between HashMap and Hashtable?


  • HashMap: Not synchronized, allows one null key and multiple null values, faster.
  • Hashtable: Synchronized, doesn't allow null keys or values, slower.

8) What is the purpose of the transient keyword?


The transient keyword is used to indicate that a field should not be serialized.

9) What is garbage collection in Java?


Garbage collection automatically removes objects that are no longer reachable or referenced, freeing memory in Java.

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


  • String: Immutable.
  • StringBuilder: Mutable and not synchronized (faster).
  • StringBuffer: Mutable and synchronized (slower).

11) What are the types of access modifiers in Java?


Java has four access modifiers:

  • public: Accessible from any other class.
  • private: Accessible only within the class.
  • protected: Accessible within the package and subclasses.
  • default (no modifier): Accessible within the same package.

12) What is multithreading in Java?


Multithreading allows the execution of two or more threads in parallel, improving the efficiency of the CPU by performing multiple tasks concurrently.

13) What is the difference between ArrayList and LinkedList?


  • ArrayList: Based on dynamic arrays, fast random access, slower insertions and deletions.
  • LinkedList: Based on doubly linked lists, slower random access, faster insertions and deletions.

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


  • final: Used for constants, methods, and classes.
  • finally: A block that always executes after a try-catch block.
  • finalize(): A method called by the garbage collector before an object is destroyed.

15) Explain the term "Java Reflection".


Java Reflection is an API that allows inspection of classes, methods, fields, and other properties of objects at runtime.

16) What is method overloading?


Method overloading occurs when multiple methods with the same name have different parameters (either in type, number, or both).

17) What is method overriding?


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

18) 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 and constructors.

19) What is an exception in Java?


An exception is an event that disrupts the normal flow of the program. It is an object that describes an abnormal condition in a program's flow.

20) What are checked and unchecked exceptions in Java?


  • Checked exceptions: Exceptions that are checked at compile-time (e.g., IOException).
  • Unchecked exceptions: Exceptions that occur at runtime (e.g., NullPointerException).

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


The try-catch block is used to handle exceptions. The code that may throw an exception is placed inside the try block, and the catch block handles the exception.

22) What is the difference between throw and throws?


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

23) 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.

24) What is the purpose of the this keyword?


The this keyword refers to the current object instance, used to differentiate between class members and method parameters.

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


  • ==: Checks if two references point to the same object.
  • .equals(): Compares the content of the two strings.

26) What is the default method in an interface?


A default method in an interface allows you to define a method with a body in the interface, which can be optionally overridden by implementing classes.

27) 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.

28) What is the use of Iterator in Java?


Iterator is used to traverse through a collection and safely remove elements while iterating.

29) What is the difference between Comparable and Comparator?


  • Comparable: Allows objects to be compared and sorted within the class (using the compareTo() method).
  • Comparator: Allows custom sorting of objects in different classes (using the compare() method).

30) What is the use of volatile keyword?


The volatile keyword ensures that the value of a variable is always read from and written to the main memory, ensuring visibility across threads.

31) What are the types of access modifiers in Java?


Java has four access modifiers:

  • public: Accessible from any other class.
  • private: Accessible only within the same class.
  • protected: Accessible within the same package and subclasses.
  • default (no modifier): Accessible only within the same package.

32) Write a program to find the longest substring without repeating characters.


import java.util.HashSet;

public class LongestSubstring {
    public static void main(String[] args) {
        String str = "abcabcbb";
        int length = lengthOfLongestSubstring(str);
        System.out.println("Length of longest substring: " + length);
    }

    public static int lengthOfLongestSubstring(String s) {
        HashSet<Character> set = new HashSet<>();
        int left = 0, right = 0, maxLength = 0;

        while (right < s.length()) {
            if (!set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                maxLength = Math.max(maxLength, right - left + 1);
                right++;
            } else {
                set.remove(s.charAt(left));
                left++;
            }
        }
        return maxLength;
    }
}

Explanation: The program uses a sliding window approach with two pointers (left and right). The window expands by adding characters and shrinks when a repeating character is found.

33) Write a program to find the GCD of two integers.


public class GCD {
    public static void main(String[] args) {
        int a = 56, b = 98;
        int gcd = findGCD(a, b);
        System.out.println("The GCD of " + a + " and " + b + " is: " + gcd);
    }

    public static int findGCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

Explanation: The program uses the Euclidean algorithm to compute the GCD. It continues to reduce b by finding the remainder of a divided by b until b becomes zero.

34) Write a program to check if a string of parentheses is balanced.


import java.util.Stack;

public class BalancedParentheses {
    public static void main(String[] args) {
        String str = "{[()]}";
        boolean isBalanced = isBalanced(str);
        System.out.println("Is the string balanced? " + isBalanced);
    }

    public static boolean isBalanced(String str) {
        Stack<Character> stack = new Stack<>();
        for (char ch : str.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

Explanation: The program uses a Stack to keep track of opening parentheses. It checks whether each closing parenthesis matches the most recent opening parenthesis. If the stack is empty at the end, the string is balanced.