Essential Java Interview Questions for Freshers

This section covers fundamental Java concepts frequently asked in interviews for entry-level positions.

JVM, JRE, and JDK

Understanding the relationship between the JVM (Java Virtual Machine), JRE (Java Runtime Environment), and JDK (Java Development Kit) is crucial. The JVM is the runtime engine that executes Java bytecode. The JRE includes the JVM, along with libraries and other necessary files. The JDK contains the JRE plus development tools (compiler, debugger, etc.).

`public static void main(String args[])`

This is the main method in Java, the entry point for program execution.

  • public: Accessible from anywhere.
  • static: Can be called without creating an object of the class.
  • void: Doesn't return any value.
  • main: The method's name (JVM looks for this).
  • String args[]: An array of strings to pass command-line arguments.

Classes and Objects

A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) of objects of that type. An object is an instance of a class; it represents a specific entity with its own state (values for its attributes).

Example: Student Class

class Student {
    int rollNo;
    String name;
    // ... methods ...
}

Methods in Java

A method is a block of code that performs a specific task. A method signature includes its name, return type, and parameter list.

Method Signatures

void myMethod();
int add(int a, int b);
String getName(int id);

Why Java Isn't Purely Object-Oriented

Java supports primitive data types (int, float, boolean, etc.) which are not objects. This makes Java a hybrid language, combining object-oriented and procedural programming paradigms.

Instance vs. Class Variables

An instance variable belongs to a specific object (each object has its own copy). A class variable (static variable) is shared among all objects of a class (only one copy exists).

Example

class MyClass {
    int instanceVar; // Instance variable
    static int classVar; // Class variable
}

Constructors in Java

Constructors initialize objects when they're created. They have the same name as the class and no return type. Java provides a default no-argument constructor if you don't define any.

Creating Objects in Java

Several ways exist to create objects:

  • Using the new keyword (most common).
  • Using reflection (Class.newInstance()).
  • Using cloning (clone() method).
  • Using deserialization.

Static Methods and Variables

The static keyword indicates that a member (method or variable) belongs to the class itself, not to any specific object. Static members are shared among all objects of the class.

Example: Static Method

class MyClass {
    static void myStaticMethod() {
        // ...
    }
}

Static Methods and Non-Static Members

Static methods cannot directly access instance variables or non-static methods because they exist independently of any specific object instance.

Static Classes

A static nested class (inner class) has all its members as static and a private constructor. It cannot be instantiated directly and is accessed using the outer class name.

Types of Variables in Java

Java has three main types of variables:

  1. Local Variables: Declared inside a method or block; exist only within that scope.
  2. Instance Variables: Declared within a class but outside any method; each object has its own copy.
  3. Static Variables (Class Variables): Declared with the static keyword; shared among all objects of the class.
Example: Variable Types

class MyClass {
    int instanceVar; // Instance variable
    static int classVar; // Static variable
    void myMethod() {
        int localVar; // Local variable
    }
}

Instance Variables

Instance variables (non-static variables) belong to specific objects. Each object of a class gets its own copy of instance variables. They're declared within a class but outside any method or block. Instance variables are created when an object is created and destroyed when the object is garbage collected. Access modifiers (public, private, protected) control their visibility.

VariableInstance.java

public class VariableInstance {
    int instVarId;
    String instVarName;
    public static void main(String args[]) {
        VariableInstance obj = new VariableInstance();
        obj.instVarId = 1;
        obj.instVarName = "InstVariable1";
        System.out.println("instanceVarId = " + obj.instVarId);
        System.out.println("instanceVarName = " + obj.instVarName);
    }
}

Static Variables (Class Variables)

Static variables (class variables) are shared among all objects of a class. There's only one copy, regardless of how many objects are created. They're declared using the static keyword within the class but outside any method or block. Static variables are created when the class is loaded and destroyed when the class is unloaded.

VarStatic.java

public class VarStatic {
    private static int cnt = 0;
    private int nonStaticCnt = 0;
    public void incCounter() {
        cnt++;
        nonStaticCnt++;
    }
    public static int getStaticCnt() { return cnt; }
    public int getNonStaticCnt() { return nonStaticCnt; }
    public static void main(String args[]) {
        VarStatic stVarOb1 = new VarStatic();
        VarStatic stVarOb2 = new VarStatic();
        stVarOb1.incCounter();
        stVarOb2.incCounter();
        System.out.println("Static count for stVarOb1: " + stVarOb1.getStaticCnt());
        System.out.println("NonStatic count for stVarOb1: " + stVarOb1.getNonStaticCnt());
    }
}

`HashMap` vs. `Hashtable`

Feature `HashMap` `Hashtable`
Synchronization Not synchronized Synchronized (thread-safe)
Null Keys/Values One null key, multiple null values allowed Null keys and values not allowed
Performance Generally faster (no synchronization overhead) Slower (synchronization overhead)

Overloading the `main()` Method

Yes, you can overload the `main()` method in Java. However, only the method with the signature `public static void main(String[] args)` is invoked by the JVM when you run the program. Other overloaded `main` methods need to be called explicitly.

OverloadMain.java

public class OverloadMain {
    public static void main(String argvs[]) {
        System.out.println("Main method with String array");
        main(5); // Calling the overloaded main method
    }
    public static void main(int i) {
        System.out.println("Main method with integer argument");
    }
}

Synchronization in Java

Synchronization prevents multiple threads from accessing the same code block simultaneously. This avoids race conditions and ensures data consistency. Synchronization is achieved using the synchronized keyword.

Collections in Java

The Java Collections Framework provides classes and interfaces for working with groups of objects. It offers methods for sorting, searching, adding, removing, and manipulating collections.

Disadvantages of Synchronization

Synchronization can reduce performance because it introduces waiting times for threads. Use it judiciously where thread safety is essential.

Why No Pointers in Java?

Pointers are omitted in Java for safety and simplicity. The JVM manages memory allocation, eliminating the risks of dangling pointers and memory corruption associated with explicit pointer manipulation.

Inheritance in Java

Inheritance allows classes to inherit properties and methods from parent classes, promoting code reusability. Java supports several types of inheritance (single, multiple via interfaces, multi-level, hierarchical, hybrid).

Interface vs. Abstract Class

Feature Interface Abstract Class
Members Constants and abstract methods (since Java 8, default and static methods are allowed) Constants, variables, abstract and concrete methods
Constructors No constructors Constructors allowed
Method Implementation Implementing classes *must* implement all abstract methods Implementing classes can choose which abstract methods to implement
Multiple Inheritance Supported (a class can implement multiple interfaces) Not directly supported for classes

Thread Lifecycle

A thread's lifecycle includes these states:

  1. New: Thread object created, but start() not yet called.
  2. Runnable: Ready to run; waiting for CPU time.
  3. Running: Currently executing.
  4. Blocked: Waiting for a resource (lock, I/O).
  5. Waiting: Waiting for another thread to signal it.
  6. Timed Waiting: Waiting for a specific time period.
  7. Terminated: Finished execution.

Stack vs. Heap Memory

Feature Stack Memory Heap Memory
Purpose Stores local variables, method calls Stores objects
Error on Overflow StackOverflowError OutOfMemoryError
Access Speed Faster Slower
Scope Method-specific Application-wide

Modifying `throws` Clauses in Overriding Methods

When overriding a method, you can modify the throws clause (the list of exceptions a method can throw), but with restrictions:

  • If the superclass method doesn't declare any checked exceptions, the subclass method can't declare checked exceptions (though unchecked exceptions are allowed).
  • If the superclass method declares checked exceptions, the subclass method can declare the same exceptions or fewer, but it cannot declare their parent exceptions.

Changing Method Scope in Overriding

You can change the access modifier (visibility) of an overridden method in a subclass, but you cannot reduce its accessibility. For example:

  • private can become public, protected, or default.
  • protected can become public or default.
  • Default can become public.
  • public cannot be changed.

Passing `this` vs. Object Reference

Passing this (a reference to the current object) to a method instead of the object reference itself has advantages:

  • this is final (cannot be reassigned), providing a degree of immutability.
  • this can be used in synchronized blocks, ensuring thread safety.