Most Common Java Interview Questions

Most Common Java Interview Questions

Most Common Java Interview Questions

Java plays a crucial role in modern technology, powering everything from household devices like DTH to large-scale enterprise applications. Given its importance, Java knowledge is frequently tested in placement interviews. To help you ace your Java interviews, we have already covered Set 1 and Set 2 of commonly asked questions. In this article, we will discuss Set 3, featuring more in-depth Java interview questions along with detailed explanations.


1. What are Wrapper Classes?

Java provides 8 primitive data types:
boolean, byte, char, int, float, double, long, and short.

For each of these, Java has a corresponding wrapper class that encapsulates the primitive data type inside an object. These are known as Wrapper Classes.

Functions of Wrapper Classes:

  1. Object Representation: They allow primitive data types to be treated as objects, enabling operations like storing them in data structures (ArrayList, HashSet, HashMap, etc.).
  2. Utility Functions: They provide various methods for conversion (e.g., converting a primitive to a String, or changing number bases to binary, octal, or hexadecimal).

Below is the list of primitive data types and their corresponding wrapper classes:

Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
intInteger
floatFloat
doubleDouble
longLong
shortShort

2. What is a Singleton Class? How do you implement it?

A Singleton Class is a class that restricts the instantiation of an object to only one instance during the program’s lifetime.

Steps to Create a Singleton Class:

  • Declare the constructor as private to prevent external instantiation.
  • Provide a static method that returns the single instance.

Example Implementation:

javaCopyEditclass Singleton {
    private static Singleton singleInstance; // Static instance

    private Singleton() { } // Private constructor

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

3. Differences between .equals() and == in Java

Both .equals() and == are used for comparison in Java, but they serve different purposes:

Feature== (Equality Operator).equals() Method
Comparison TypeCompares memory address (reference comparison)Compares content (value comparison)
Works onPrimitives & ObjectsObjects only
Example Usageif (obj1 == obj2)if (obj1.equals(obj2))

Example Code:

javaCopyEditpublic class EqualsTest {
    public static void main(String[] args) {
        String str1 = new String("Java");
        String str2 = new String("Java");

        System.out.println(str1 == str2);        // Output: false (different memory locations)
        System.out.println(str1.equals(str2));   // Output: true (same content)
    }
}

4. What are Stack and Heap Memory in Java?

Heap Memory:

  • Stores objects and instance variables.
  • Objects persist until garbage collection removes them.

Stack Memory:

  • Stores local variables and method calls.
  • Follows LIFO (Last In, First Out) order.
  • Automatically cleared after method execution.

5. Key Differences Between Heap and Stack Memory

FeatureStack MemoryHeap Memory
UsageStores method calls & local variablesStores objects & instance variables
AccessLimited to a single threadGlobally accessible
Memory ManagementAutomatically managed (LIFO)Garbage collected
SpeedFasterSlower
LifetimeExists during method executionExists throughout the application

6. Lifecycle of a JSP (Java Server Pages)

JSP pages go through three stages during their lifecycle:

  1. jspInit() – Initializes resources (database connections, files, lookup tables).
  2. _jspService() – Handles client requests and generates responses.
  3. jspDestroy() – Cleans up resources when the page is no longer needed.
javaCopyEditpublic void jspInit() { 
    // Initialization code 
}

public void _jspService(ServletRequest request, ServletResponse response) 
    throws ServletException, IOException { 
    // Request processing code 
}

public void jspDestroy() { 
    // Cleanup code 
}

7. Variable Scope in Java

Variable TypeScope & Usage
Member VariableDefined inside a class but outside methods. Accessible throughout the class.
Local VariableDefined inside a method. Only accessible within that method.
Loop VariableDefined inside loops. Accessible only within the loop block {}.

Example:

javaCopyEditclass VariableScopeExample {
    int memberVariable = 10; // Class-level scope

    public void methodExample() {
        int localVariable = 5; // Method-level scope
        for (int i = 0; i < 3; i++) { 
            int loopVariable = i * 2; // Loop-level scope
            System.out.println(loopVariable);
        }
    }
}

8. What is the this Keyword in Java?

The this keyword is a reference variable that refers to the current object.

Use Cases of this in Java:

  1. Referring to the instance variable when a local variable has the same name.
  2. Invoking another method of the same class.
  3. Calling the constructor of the same class (this()).
  4. Passing the current object as a method argument.
  5. Passing the current object as a constructor argument.
  6. Returning the current instance from a method.

Example:

javaCopyEditclass Example {
    int num;

    Example(int num) {
        this.num = num; // Using 'this' to refer to instance variable
    }

    void display() {
        System.out.println("Number: " + this.num);
    }

    public static void main(String[] args) {
        Example obj = new Example(10);
        obj.display(); // Output: Number: 10
    }
}

Final Thoughts

Mastering these Java interview concepts will help you perform well in placement interviews. Make sure to practice coding these concepts, as interviewers often ask candidates to implement solutions on the spot.