← Back to list

Core JAVA Question Bank

Core JAVA Question Bank

TechWealthBuzz · 2026-02-25 07:44 · 0 claps · 6.0 min read paywalled
#java-question #core-java-interview #interview-preparation #java-interview-questions #interview-questions
Open on Medium ↗

Core JAVA Question Bank

Core JAVA Question Bank

Core JAVA Question Bank

Core JAVA Question Bank

Happy reading! 🎉 🚧 Free access to the article **here. 👏 Please support by clapping, following & [subscribing](https://techwealthbuzz.com/)! 💬 Drop a comment — I’d love to hear from you! 📲 Let’s connect on X (Twitter): [@vivekprasadx](https://x.com/vivekprasadx) 🎁 Support my work via UPI: VivekPrasadUpi@jio**

Q) What are the differences between Association, Aggregation, and Composition in Object-Oriented Programming (OOP)


Feature           | Association                           | Aggregation                             | Composition
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Relationship Type | General "uses-a" or "has-a"           | "Has-a" (weak ownership)                | "Has-a" or "part-of" (strong ownership)
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Strength          | Weakest                               | Moderate (weak "has-a")                 | Strongest (strong "has-a")
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Lifecycle         | Independent (objects can exist        | Independent (parts can exist            | Dependent (parts cannot exist
Dependency        | without each other)                   | without the whole)                      | without the whole)
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Ownership         | No specific ownership                 | Shared ownership (parts can be shared)  | Exclusive ownership (parts not shared)
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Deletion of Whole | Does not affect the parts             | Does not necessarily affect the parts   | Parts are also deleted with the whole
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
Example           | Student uses Teacher                  | Department has Professors               | Car has an Engine
------------------|---------------------------------------|-----------------------------------------|---------------------------------------------
UML Notation      | Simple line (or line with arrow)      | Line with empty diamond on whole side   | Line with filled diamond on whole side

Association: General “uses-a” or “has-a” Relationship

// Java Code for Association
class Teacher {
    String name;
    Teacher(String name) { this.name = name; }
}

class Student {
    String name;
    Teacher teacher; // Student HAS-A Teacher (teacher can be null or shared)

    Student(String name, Teacher teacher) { // Teacher is passed in, exists independently
        this.name = name;
        this.teacher = teacher;
    }
}

// How it works:
// Teacher t = new Teacher("Ms. Davis");
// Student s = new Student("Alice", t); // Student gets an existing teacher
// t = null; // Ms. Davis could still be assigned to other students
// s = null; // Alice is gone, but Ms. Davis still exists

Aggregation: The “Weak” Has-A Relationship

// Java Code for Aggregation
import java.util.List;
import java.util.ArrayList;

class Professor {
    String name;
    Professor(String name) { this.name = name; }
}

class Department {
    String name;
    List<Professor> professors; // Department HAS-A list of Professors

    Department(String name, List<Professor> professors) { // Professors are passed in
        this.name = name;
        this.professors = new ArrayList<>(professors); // Copies references
    }
}

// How it works:
// Professor p1 = new Professor("Dr. Smith");
// List<Professor> profs = new ArrayList<>();
// profs.add(p1);
// Department d = new Department("CS", profs);
// d = null; // Department gone
// p1.name; // Dr. Smith still exists, can be assigned to another department

Composition: The “Strong” Has-A Relationship

// Java Code for Composition
class Engine {
    String type;
    Engine(String type) { this.type = type; } // Engine creation
}

class Car {
    String model;
    Engine engine; // Car HAS-A Engine (Engine's lifecycle is tied to Car)

    Car(String model, String engineType) {
        this.model = model;
        this.engine = new Engine(engineType); // Car *creates* its own Engine
    }
}

// How it works:
// Car myCar = new Car("Sedan", "V6"); // Car and its Engine created together
// myCar = null; // Car is eligible for GC. The V6 Engine object also becomes eligible.

Q) Compare and contrast instance, local, and static variables


Feature            | Instance Variables               | Local Variables                | Static Variables
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Declaration        | Inside class, outside methods    | Inside methods/blocks          | Inside class, outside methods, with `static`
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Keyword            | None (implicitly non-static)     | None (implicitly local)        | `static`
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Scope              | Within object (all non-static    | Within method/block only       | Class-wide (accessible from anywhere
                   | parts)                           |                                | in class)
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Lifetime           | Until object is garbage collected| Until method/block exits       | Until program terminates
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Memory             | Heap (part of object)            | Stack                          | Method Area (part of Heap)
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Copies             | One per object                   | One per method/block invocation| Only one copy for the entire class
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Access             | `objectName.variableName`        | Directly within scope          | `ClassName.variableName` (preferred)
                   |                                  |                                | `objectName.variableName` (discouraged)
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Default Value      | Yes                              | No (must be initialized)       | Yes
-------------------|----------------------------------|--------------------------------|-------------------------------------------
Purpose            | Object state                     | Temporary method data          | Class-level data, shared, constants

Q) Explain System.out.println

Explain System.out.println

+-------------------+      +-------------------+      +-----------------------+
|  java.lang.System | .----->  static field 'out' | .----->  method 'println()'   |
| (Class)           |      | (PrintStream object)|      | (Prints text to console)|
|                   |      |                     |      | + adds a new line     |
| - main system     |      | - standard output   |      |                       |
|   functionality   |      |   stream            |      | Arguments:            |
| - static members  |      | - directs output    |      |   - String            |
|                   |      |   to console        |      |   - int, double, etc. |
+-------------------+      +-------------------+      +-----------------------+
        ^
        | Accesses
        |
    [Your Java Program]

Q) Class Modifiers in Java


Modifier    | Type              | Purpose                                   | Key Characteristic(s)

`public`    | Access            | Makes class accessible from any package.  | Widest visibility.
            |                   |                                           |

`default`   | Access            | (No keyword) Makes class accessible       | Only visible within its own package.
(no keyword)|                   | only within its own package.              |
            |                   |                                           |

`final`     | Non-Access        | Prevents a class from being subclassed.   | Cannot be extended.
            |                   |                                           |

`abstract`  | Non-Access        | Serves as a base class; cannot be         | Cannot be instantiated directly;
            |                   | instantiated directly. May contain        | may have abstract methods (no body).
            |                   | abstract methods.                         |

`strictfp`  | Non-Access        | Ensures strict floating-point computation | Guarantees same floating-point results
            |                   | adherence to IEEE 754 standard across     | across all platforms.
            |                   | platforms.                                |

Q) Final vs finally vs finalize


Feature           | `final` (Keyword)                     | `finally` (Block)                   | `finalize()` (Method)
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**What it is**    | A keyword used to define entities     | A block of code associated with     | A protected method in `java.lang.Object`
                  | that cannot be changed/extended.      | a `try-catch` statement.            | that can be overridden by classes.
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**Applies to**    | **Classes**: Cannot be subclassed.    | A `try` block (optionally with      | Any class that inherits from `Object`
                  | **Methods**: Cannot be overridden.    | `catch` blocks).                    | (i.e., almost all classes).
                  | **Variables**: Value cannot be        |                                     |
                  | changed after initialization.         |                                     |
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**Purpose**       | Ensures immutability (variables),     | Ensures a block of code is          | Performs cleanup actions on an object
                  | prevents inheritance (classes),       | executed regardless of whether      | *before* it is garbage collected.
                  | prevents method overriding (methods). | an exception occurred or not.       |
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**Execution Time**| Compile-time (for variables/methods)  | Always executes after `try`         | Called by the Garbage Collector (GC)
                  | or during class loading (for classes).| and `catch` blocks, before          | *if and when* it decides to collect
                  |                                       | the method exits.                   | the object.
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**Guaranteed**    | Yes (compiler enforces it).           | Yes (virtually always executes,     | No (GC might not run, or might run
**Execution**     |                                       | even if an exception is thrown      | much later).
                  |                                       | or `return` is called).             | **Deprecated in Java 9+**.
------------------|---------------------------------------|-------------------------------------|---------------------------------------
**Common Use**    | Defining constants, immutable objects,| Releasing resources (closing files, | Releasing non-Java resources (e.g.,
                  | preventing unwanted modification/     | database connections, network       | native memory handles).
                  | extension.                            | sockets).                           |

Q) How to create a Singleton class in java

In Java, a Singleton class is a design pattern that ensures only one instance of the class exists throughout the JVM. This is useful when exactly one object is needed to coordinate actions across the system (e.g., logging, configuration, caching).

Steps to Create a Singleton Class

  1. Private Constructor → Prevents instantiation from outside the class.
  2. Private Static Instance → Holds the single object of the class.
  3. Public Static Method (getInstance) → Provides global access to that single instance.

Example: Lazy Initialization Singleton

class Singleton {
    // Step 1: Private static instance
    private static Singleton singleInstance;

    // Step 2: Private constructor
    private Singleton() {
        System.out.println("Singleton instance created");
    }

    // Step 3: Public static method to provide access
    public static Singleton getInstance() {
        if (singleInstance == null) {
            singleInstance = new Singleton();
        }
        return singleInstance;
    }
}

public class Main {
    public static void main(String[] args) {
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();

        System.out.println(obj1 == obj2); // true → same instance
    }
}

Variations

  • Eager Initialization → Create the instance at class loading.
  • Thread-Safe Singleton → Use synchronized in getInstance() or use the Bill Pugh Singleton with a static inner helper class.
  • Enum Singleton → Simplest and safest way in Java (prevents reflection and serialization issues).

In short: A Singleton class in Java is created by making the constructor private, storing a static instance, and exposing it through a public static method. This ensures only one instance exists across the application.


메타데이터
post_id
e51614b4ff37
slug
core-java-question-bank-e51614b4ff37
url
https://medium.com/@techwealthbuzz/core-java-question-bank-e51614b4ff37
canonical_url
https://medium.com/@techwealthbuzz/core-java-question-bank-e51614b4ff37
author_url
https://medium.com/@techwealthbuzz
status
ok
fetched_at
2026-07-30 03:42:02