Results for Java Core

Factory Design Pattern in Java with Real Examples

2:34 AM

The Factory Design Pattern is one of the most commonly used Creational Design Patterns in Java. Instead of creating objects directly using the new keyword, object creation logic is delegated to a factory class.


The Factory Pattern promotes loose coupling, improves maintainability and simplifies object creation. It is used extensively in enterprise applications, Spring Framework, Hibernate and Java SDK libraries.


What is Factory Design Pattern?

Factory Design Pattern provides an interface or method for creating objects without exposing object creation logic to the client.

The client requests an object from the factory instead of creating it directly.


Why Do We Need Factory Pattern?

Imagine an application that creates different types of vehicles.

Without a Factory Pattern, the client would need to know exactly which class to instantiate.


Vehicle vehicle = new Car();

As the number of vehicle types grows, object creation becomes difficult to manage.


Problem Without Factory Pattern


if(type.equals("CAR")) {

    vehicle = new Car();

}
else if(type.equals("BIKE")) {

    vehicle = new Bike();

}
else if(type.equals("TRUCK")) {

    vehicle = new Truck();

}

This approach violates the Open/Closed Principle and makes maintenance harder.


Factory Pattern Solution

Move object creation logic into a dedicated factory.


Client
   |
   v
Factory
   |
   +---- Car

   +---- Bike

   +---- Truck

The client no longer needs to know how objects are created.


Step 1: Create Interface


public interface Vehicle {

    void drive();

}

All vehicle implementations will follow this contract.


Step 2: Create Implementations

Car Class


public class Car
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Car"
        );

    }
}

Bike Class


public class Bike
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Bike"
        );

    }
}

Truck Class


public class Truck
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Truck"
        );

    }
}

Step 3: Create Factory Class


public class VehicleFactory {

    public static Vehicle
        getVehicle(String type) {

        if(type.equalsIgnoreCase("CAR")) {

            return new Car();

        }

        if(type.equalsIgnoreCase("BIKE")) {

            return new Bike();

        }

        if(type.equalsIgnoreCase("TRUCK")) {

            return new Truck();

        }

        throw new IllegalArgumentException(
            "Invalid Vehicle Type"
        );
    }
}

Step 4: Client Code


public class FactoryDemo {

    public static void main(String[] args) {

        Vehicle vehicle =
            VehicleFactory
                .getVehicle("CAR");

        vehicle.drive();

    }
}

Output


Driving Car

How Factory Pattern Works Internally

The client requests an object from the factory.

The factory decides which concrete implementation should be created and returned.


Client
   |
   v
VehicleFactory
   |
   +---- Car

   +---- Bike

   +---- Truck

This hides object creation details from the client.


Real World Example

Consider a Notification System.


Email Notification

SMS Notification

Push Notification

Instead of directly creating notification objects, a factory can return the correct implementation.


Notification notification =
NotificationFactory
    .getNotification("EMAIL");

Factory Pattern in Spring Framework

Spring internally uses factory-based approaches for bean creation.

A common example is FactoryBean.


FactoryBean<Object>

Spring delegates bean creation logic through factory mechanisms extensively.


Factory Pattern Advantages

  • Loose Coupling
  • Better Maintainability
  • Centralized Object Creation
  • Easier Extension
  • Improved Readability

Factory Pattern Disadvantages

  • Additional Classes
  • Increased Complexity for Small Projects
  • May Introduce Extra Abstraction

Factory Pattern vs Singleton Pattern

Factory Pattern Singleton Pattern
Creates Objects Restricts Object Creation
Multiple Instances Possible Single Instance
Focuses on Creation Logic Focuses on Object Uniqueness

Common Interview Questions

What is Factory Design Pattern?

A creational design pattern that delegates object creation to a factory class.


Why use Factory Pattern?

To reduce coupling and centralize object creation logic.


Which SOLID principle does Factory Pattern support?

Open/Closed Principle and Dependency Inversion Principle.


Is Factory Pattern used in Spring Framework?

Yes. Spring uses factory-based mechanisms internally for bean creation and management.


When should Factory Pattern be used?

When object creation logic becomes complex or multiple implementations exist.


Best Practices

  • Use interfaces for products.
  • Keep factory logic centralized.
  • Avoid overly complex factory implementations.
  • Combine Factory Pattern with Dependency Injection where appropriate.
  • Follow SOLID principles.

Frequently Asked Questions (FAQ)

Can Factory Pattern return different object types?

Yes. That is one of its primary purposes.


Can Factory Pattern improve maintainability?

Yes. It centralizes object creation and reduces direct dependencies.


Is Factory Pattern a Creational Pattern?

Yes. Factory Pattern belongs to the Creational Design Pattern category.


Conclusion

The Factory Design Pattern simplifies object creation and promotes loose coupling between application components. It is widely used across enterprise Java applications, Spring Framework and design pattern-based architectures. Mastering Factory Pattern is essential for interviews and writing maintainable software solutions.


Keywords

Factory Design Pattern, Factory Pattern Java, Creational Design Patterns, Java Design Patterns, Factory Method Pattern, Factory Pattern Interview Questions, Spring FactoryBean, Object Creation Pattern, Design Patterns Java, Factory Example Java, Core Java Interview Questions, Java Architecture, OOP Design Patterns, Software Design Patterns, Java Best Practices



Factory Design Pattern in Java with Real Examples Factory Design Pattern in Java with Real Examples Reviewed by 13thGhost on 2:34 AM Rating: 5

OutOfMemoryError in Java: Causes, Types and How to Fix It

3:14 AM

OutOfMemoryError is one of the most common and critical production issues faced by Java developers. It occurs when the JVM is unable to allocate memory for new objects because the available memory has been exhausted.


Understanding OutOfMemoryError is essential for Java developers, support engineers, performance engineers and architects because it directly impacts application stability and performance.


What is OutOfMemoryError?

OutOfMemoryError is a JVM error that occurs when memory allocation fails and the JVM cannot create new objects.



Exception in thread "main"
java.lang.OutOfMemoryError

Unlike normal exceptions, OutOfMemoryError indicates a serious memory problem that the application may not be able to recover from.


Common Types of OutOfMemoryError

  • Java Heap Space
  • GC Overhead Limit Exceeded
  • Metaspace
  • Unable to Create New Native Thread
  • Direct Buffer Memory

Java Heap Space Error

This is the most common OutOfMemoryError. It occurs when the heap becomes completely full and there is insufficient memory to create additional objects.


Example


List<Object> list =
        new ArrayList<>();

while(true) {

    list.add(new Object());

}

Possible Output


java.lang.OutOfMemoryError:
Java heap space

Why Does Heap Space Error Occur?

  • Memory leaks
  • Large collections
  • Improper caching
  • Huge object allocations
  • Insufficient heap configuration

GC Overhead Limit Exceeded

This error occurs when the Garbage Collector spends too much time attempting to free memory but recovers very little memory.



java.lang.OutOfMemoryError:
GC overhead limit exceeded

This typically indicates serious memory pressure in the application.


Metaspace OutOfMemoryError

Metaspace stores class metadata loaded by the JVM. If too many classes are loaded, Metaspace may become full.


Error Example


java.lang.OutOfMemoryError:
Metaspace

This can occur in applications that dynamically generate or load large numbers of classes.


Unable to Create New Native Thread

Every thread requires operating system resources. Creating too many threads may result in this error.



java.lang.OutOfMemoryError:
unable to create new native thread

Example


while(true) {

    new Thread(() -> {

        while(true) {

        }

    }).start();
}

Eventually the JVM or operating system will refuse to create additional threads.


Direct Buffer Memory Error

NIO applications may allocate off-heap memory using direct buffers.



java.lang.OutOfMemoryError:
Direct buffer memory

This error occurs when available direct memory has been exhausted.


Memory Leak Example

One of the most common causes of OutOfMemoryError is a memory leak.



public class MemoryLeak {

    private static final List<Object>
    cache = new ArrayList<>();

    public static void main(String[] args) {

        while(true) {

            cache.add(new Object());

        }

    }
}

Objects continue accumulating and cannot be garbage collected because references remain stored inside the list.


How to Identify Memory Leaks

Common symptoms include:


  • Increasing heap usage
  • Frequent Full GC
  • Application slowdowns
  • Unexpected crashes
  • OutOfMemoryError messages

Useful JVM Tools

Several tools help analyse memory problems.


  • jvisualvm
  • JConsole
  • Eclipse MAT
  • Java Flight Recorder
  • Mission Control

Heap Dump Analysis

Heap dumps capture the state of memory at a specific point in time.

To generate a heap dump automatically:



-XX:+HeapDumpOnOutOfMemoryError

This is one of the most useful options when troubleshooting production memory issues.


Increasing Heap Memory

Sometimes the application genuinely requires additional memory.



-Xms512m
-Xmx2048m

These JVM parameters control initial and maximum heap size.


Best Practices to Avoid OutOfMemoryError

  • Remove unnecessary references.
  • Use bounded caches.
  • Close resources properly.
  • Avoid loading huge datasets into memory.
  • Monitor heap utilisation continuously.
  • Review thread creation strategies.

Real Interview Questions

What is OutOfMemoryError?

It occurs when JVM cannot allocate memory for new objects.


Is OutOfMemoryError an Exception?

No. It is an Error and represents a serious JVM memory issue.


What is the difference between StackOverflowError and OutOfMemoryError?

StackOverflowError occurs due to excessive stack usage, while OutOfMemoryError occurs when memory allocation fails.


What is a memory leak?

A memory leak occurs when objects remain referenced even though they are no longer required.


How can heap dumps help?

Heap dumps help identify which objects consume memory and why they are retained.


Frequently Asked Questions (FAQ)

Can Garbage Collection prevent all OutOfMemoryErrors?

No. If references remain active or memory demand exceeds available memory, OutOfMemoryError can still occur.


Can increasing heap memory solve every memory problem?

No. Memory leaks and inefficient application design must also be addressed.


What JVM argument helps generate heap dumps?

-XX:+HeapDumpOnOutOfMemoryError


Which type of OutOfMemoryError is most common?

Java Heap Space OutOfMemoryError.


Conclusion

OutOfMemoryError is one of the most important JVM topics for both interviews and production environments. Understanding heap memory, memory leaks, metaspace usage, garbage collection behaviour and heap dump analysis helps developers diagnose and fix memory problems effectively.


Keywords

OutOfMemoryError Java, Java Heap Space Error, Java Memory Leak, GC Overhead Limit Exceeded, Metaspace Error, Java Performance Tuning, Heap Dump Analysis, JVM Memory Management, Java Heap Memory, JVM Interview Questions, Memory Leak Detection, Java Monitoring Tools, Core Java Interview Questions, JVM Internals, Java Application Performance





OutOfMemoryError in Java: Causes, Types and How to Fix It OutOfMemoryError in Java: Causes, Types and How to Fix It Reviewed by 13thGhost on 3:14 AM Rating: 5

ClassLoader in Java Explained with Examples and Class Loading Process

3:08 AM

Every Java developer uses classes such as String, ArrayList and HashMap daily, but very few understand how these classes are loaded into memory. The ClassLoader is a crucial component of the JVM responsible for loading Java classes dynamically during runtime.


Understanding ClassLoader is important not only for interviews but also for debugging ClassNotFoundException, NoClassDefFoundError and understanding JVM internals.


What is a ClassLoader?

A ClassLoader is a JVM subsystem responsible for loading Java class files into memory. It loads classes only when they are required by the application.

Without ClassLoader, the JVM would not know where to find and load classes.

Why Do We Need ClassLoader?

Imagine a Java application containing thousands of classes. Loading all classes during startup would consume a huge amount of memory and increase startup time.

Instead, the JVM loads classes on demand using ClassLoaders.


Class Loading Process

Whenever a class is referenced for the first time, JVM follows three steps:



Loading
   |
   v
Linking
   |
   v
Initialization

Step 1: Loading

The JVM finds the corresponding .class file and loads it into memory.


Step 2: Linking

The JVM verifies and prepares the loaded class.


Step 3: Initialization

Static variables and static blocks are initialized.


Types of ClassLoaders

Java provides three primary ClassLoaders.


1. Bootstrap ClassLoader

Bootstrap ClassLoader is the parent of all ClassLoaders. It loads core Java classes from the JDK.


Examples


java.lang.String
java.lang.Object
java.util.ArrayList
java.util.HashMap

This ClassLoader is implemented in native code and is part of the JVM itself.


2. Platform (Extension) ClassLoader

This ClassLoader loads classes from platform libraries and Java extensions.

It sits between Bootstrap ClassLoader and Application ClassLoader.


3. Application ClassLoader

Application ClassLoader loads classes that belong to your application.

These are classes found in the application's classpath.


Example Program


public class ClassLoaderDemo {

    public static void main(String[] args) {

        System.out.println(
            ClassLoaderDemo.class
                .getClassLoader()
        );

    }
}

Possible Output


jdk.internal.loader.ClassLoaders$AppClassLoader

This indicates that the application class was loaded by the Application ClassLoader.


Checking String ClassLoader


System.out.println(
    String.class.getClassLoader()
);

Output


null

Many developers get confused by this output. String is loaded by Bootstrap ClassLoader and JVM represents it as null.


Parent Delegation Model

Java follows the Parent Delegation Model while loading classes.



Application ClassLoader
           |
           v
Platform ClassLoader
           |
           v
Bootstrap ClassLoader

Whenever a class needs to be loaded:

  • Application ClassLoader first asks its parent.
  • Parent asks its own parent.
  • Bootstrap attempts loading first.
  • If not found, control returns back.

This prevents duplicate class loading and improves security.


Example of Parent Delegation

Suppose JVM needs String class.


  1. Application ClassLoader asks Platform ClassLoader.
  2. Platform ClassLoader asks Bootstrap ClassLoader.
  3. Bootstrap finds String.class.
  4. String class is loaded.

Application ClassLoader never loads String because Bootstrap already handled it.


ClassNotFoundException

This exception occurs when JVM cannot locate a required class during runtime.



Class.forName(
    "com.example.Employee"
);

Possible Output


java.lang.ClassNotFoundException

This generally happens when the required class is not present in the classpath.


NoClassDefFoundError

This error occurs when a class was available during compilation but is missing during execution.



java.lang.NoClassDefFoundError

This is different from ClassNotFoundException and is another favourite interview question.


Custom ClassLoader

Java allows developers to create their own ClassLoaders.


Custom ClassLoaders are commonly used in:

  • Application Servers
  • Plugin Systems
  • Framework Development
  • Runtime Module Loading

Real World Example

Application servers such as Tomcat use multiple ClassLoaders to isolate applications from each other.

This ensures that different applications can use different versions of the same library.


Common Interview Questions

What is a ClassLoader?

It is a JVM component responsible for loading class files into memory.


How many built-in ClassLoaders are available?

Bootstrap, Platform (Extension) and Application ClassLoader.


Why does String.class.getClassLoader() return null?

Because String is loaded by Bootstrap ClassLoader.


What is Parent Delegation Model?

A class loading mechanism where class loading requests are delegated to parent ClassLoaders first.


What is the difference between ClassNotFoundException and NoClassDefFoundError?

ClassNotFoundException occurs when JVM cannot locate a class. NoClassDefFoundError occurs when the class existed during compilation but is unavailable at runtime.


Best Practices

  • Avoid breaking the Parent Delegation Model unnecessarily.
  • Keep application dependencies organized.
  • Use custom ClassLoaders only when required.
  • Monitor classpath issues carefully.
  • Understand ClassLoader hierarchy for troubleshooting production issues.

Frequently Asked Questions (FAQ)

Can a class be loaded more than once?

Yes. Different ClassLoaders can load the same class separately.


Who loads Java core classes?

Bootstrap ClassLoader loads Java core classes.


Does JVM load all classes at startup?

No. JVM loads classes on demand.


Can we create our own ClassLoader?

Yes. Java provides support for creating custom ClassLoaders.


Conclusion

ClassLoader is one of the most important JVM components. It enables dynamic class loading, improves startup performance and supports Java's modular architecture. Understanding ClassLoader hierarchy, Parent Delegation Model and common runtime errors such as ClassNotFoundException and NoClassDefFoundError is essential for every Java developer.


Keywords

ClassLoader in Java, Java ClassLoader Tutorial, Bootstrap ClassLoader, Application ClassLoader, Parent Delegation Model, Class Loading Process, ClassNotFoundException, NoClassDefFoundError, JVM Internals, Java Interview Questions, ClassLoader Architecture, JVM Architecture, Core Java Concepts, Java Runtime Environment, JVM Tutorial



ClassLoader in Java Explained with Examples and Class Loading Process ClassLoader in Java Explained with Examples and Class Loading Process Reviewed by 13thGhost on 3:08 AM Rating: 5

Garbage Collection in Java Explained with Examples and GC Types

3:01 AM

One of the biggest advantages of Java is automatic memory management. Unlike languages where developers are responsible for allocating and freeing memory manually, Java uses Garbage Collection to reclaim memory occupied by unused objects.


Garbage Collection is a favourite interview topic because it directly relates to JVM performance, memory management and application scalability.


What is Garbage Collection?

Garbage Collection is the process of automatically identifying and removing objects that are no longer being used by the application.

The Garbage Collector helps free Heap Memory by removing unreachable objects.


Example


Employee employee = new Employee();

employee = null;

After the reference becomes null, the Employee object becomes eligible for Garbage Collection.


Why Garbage Collection is Important

Without Garbage Collection, applications would continue consuming memory until the system eventually crashed.


Benefits include:

  • Automatic memory management
  • Reduced memory leaks
  • Improved developer productivity
  • Better application stability

Garbage Collection Terminologies

Reachable Object

An object that can still be accessed through an active reference.



Employee employee = new Employee();

The object is reachable because employee references it.


Unreachable Object

An object that no longer has any active references.



Employee employee = new Employee();

employee = null;

The object becomes unreachable and can be collected.


Object Lifecycle


Object Created
       |
       v
Object Used
       |
       v
Reference Removed
       |
       v
Eligible For GC
       |
       v
Memory Reclaimed

Heap Memory Structure

Garbage Collection primarily works inside Heap Memory.



Heap Memory
   |
   +-- Young Generation
   |
   +-- Old Generation

Different garbage collection strategies are applied to different regions of the heap.


Young Generation

Newly created objects are initially allocated in the Young Generation.

Most application objects are short-lived and are collected from this area quickly.


Components

  • Eden Space
  • Survivor Space S0
  • Survivor Space S1

Old Generation

Objects that survive multiple garbage collection cycles are promoted to the Old Generation.

These objects typically have a longer lifespan.


Minor Garbage Collection

Minor GC occurs when memory in the Young Generation becomes full.

Unused objects are removed and surviving objects are moved to Survivor spaces.

Minor GC is generally fast and frequent.


Major Garbage Collection

Major GC targets objects stored in the Old Generation.

This process is usually slower because it works on a significantly larger memory area.


Full Garbage Collection

Full GC cleans both Young Generation and Old Generation memory areas.

Full GC is the most expensive type of garbage collection and can temporarily impact application performance.


Using System.gc()

Java allows developers to request garbage collection.



System.gc();

However, this is only a request. The JVM may choose to ignore it.


Finalize Method

Historically, Java provided the finalize() method that could execute before object cleanup.



@Override
protected void finalize()
throws Throwable {

    System.out.println("Object removed");

}

Modern Java versions discourage using finalize() because of performance and reliability concerns.


Popular Garbage Collectors in Java

Serial GC

Uses a single thread for garbage collection. Suitable for small applications.


Parallel GC

Uses multiple threads and focuses on throughput.


CMS GC

Concurrent Mark Sweep reduces pause times but has largely been replaced by newer collectors.


G1 Garbage Collector

G1GC is the default garbage collector in modern Java versions.

It divides the heap into regions and prioritises efficient memory cleanup.


Z Garbage Collector (ZGC)

ZGC is designed for very large heaps and extremely low pause times.

It is frequently used in large-scale enterprise systems.


Example Program


public class GCDemo {

    public static void main(String[] args) {

        Employee emp =
                new Employee();

        emp = null;

        System.gc();

    }
}

The Employee object becomes eligible for garbage collection when the reference is removed.


Common Interview Questions

What is Garbage Collection?

Garbage Collection is the process of automatically reclaiming memory occupied by unused objects.


Can we force Garbage Collection?

No. We can request Garbage Collection using System.gc(), but the JVM decides whether to execute it.


What is the difference between Minor GC and Major GC?

Minor GC works on Young Generation. Major GC works on Old Generation.


Which Garbage Collector is the default in modern Java?

G1 Garbage Collector is the default collector in modern Java releases.


What makes an object eligible for Garbage Collection?

An object becomes eligible when no active references point to it.


Best Practices

  • Remove unnecessary object references.
  • Avoid creating excessive temporary objects.
  • Use object pooling carefully.
  • Monitor GC logs in production environments.
  • Choose an appropriate GC strategy for your workload.

Frequently Asked Questions (FAQ)

Does Garbage Collection immediately destroy objects?

No. An object becomes eligible for collection, but actual removal depends on JVM behaviour.



Can local variables be garbage collected?

No. Garbage Collection mainly operates on Heap Memory objects.


What is a memory leak in Java?

A memory leak occurs when objects remain referenced even though they are no longer needed.


Why is Full GC considered expensive?

Because it processes large portions of heap memory and can increase application pause times.


Conclusion

Garbage Collection is one of the most important JVM features. It simplifies memory management by automatically reclaiming unused memory and reducing the possibility of memory-related failures. Understanding object lifecycle, heap generations, Minor GC, Major GC, G1GC and ZGC is essential for Java developers and interview preparation.


Keywords

Garbage Collection in Java, Java Garbage Collector, G1GC Explained, ZGC Explained, Minor GC vs Major GC, Heap Memory Management, Java Memory Management, JVM Garbage Collection, Java Performance Tuning, GC Interview Questions, Java Heap Memory, Full GC Java, Object Lifecycle Java, Core Java Interview Questions, JVM Internals


Garbage Collection in Java Explained with Examples and GC Types Garbage Collection in Java Explained with Examples and GC Types Reviewed by 13thGhost on 3:01 AM Rating: 5

20 Tricky Java Output Questions Every Experienced Developer Should Know

3:42 PM

Java interviews often contain tricky output-based questions that test your understanding of core Java concepts rather than your ability to memorize syntax.


These questions typically cover String Pool, Wrapper Classes, Method Overloading, Inheritance, Exception Handling, finally blocks, Increment Operators and Java Memory concepts.

Let's challenge your Java knowledge with 20 popular interview questions.


Question 1


String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2);

Output


true

Explanation

String literals are stored in the String Pool. Both variables point to the same memory location.


Question 2


String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2);

Output


false

Explanation

Two separate objects are created in heap memory. Therefore reference comparison returns false.


Question 3


String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1.equals(s2));

Output


true

equals() compares content, not memory references.


Question 4


Integer a = 127;
Integer b = 127;

System.out.println(a == b);

Output


true

Explanation

Integer values from -128 to 127 are cached by Java. Both references point to the same cached object.


Question 5


Integer a = 128;
Integer b = 128;

System.out.println(a == b);

Output


false

Explanation

128 falls outside Integer Cache range. Separate objects are created.


Question 6


String str = null;

System.out.println(str instanceof String);

Output


false

Explanation

instanceof never throws NullPointerException. It simply returns false.


Question 7


System.out.println(10 + 20 + "Java");

Output


30Java

Addition occurs before String concatenation.


Question 8


System.out.println("Java" + 10 + 20);

Output


Java1020

Once a String appears, subsequent operations become concatenations.


Question 9


int x = 10;

System.out.println(x++ + ++x);

Output


22

Explanation

x++ returns 10 then x becomes 11. ++x makes x 12 and returns 12. Result = 10 + 12.


Question 10


int x = 5;

System.out.println(x+++x);

Output


11

Explanation

Compiler interprets this as:


x++ + x

Result becomes 5 + 6.


Question 11


try {
    return;
}
finally {
    System.out.println("Finally");
}

Output


Finally

finally block executes before method exits.


Question 12


try {
    System.exit(0);
}
finally {
    System.out.println("Finally");
}

Output


No Output

JVM terminates immediately.


Question 13


StringBuilder sb =
        new StringBuilder("Java");

sb.append(" 8");

System.out.println(sb);

Output


Java 8

StringBuilder is mutable.


Question 14


final StringBuilder sb =
        new StringBuilder("Java");

sb.append(" 21");

System.out.println(sb);

Output


Java 21

Explanation

final prevents reference reassignment, not object modification.


Question 15


String s = "Java";

s.concat(" 8");

System.out.println(s);

Output


Java

String objects are immutable. concat() returns a new String.


Question 16


System.out.println(Math.round(2.5));
System.out.println(Math.round(3.5));

Output


3
4

Question 17


String s = null;

System.out.println(String.valueOf(s));

Output


null

String.valueOf() safely handles null references.


Question 18


List<String> list =
        Arrays.asList("Java","Spring");

list.add("Kafka");

Output


UnsupportedOperationException

Explanation

Arrays.asList() returns a fixed-size list.


Question 19


String s = "Java";

System.out.println(s.charAt(4));

Output


StringIndexOutOfBoundsException

Valid indexes are 0 to 3.


Question 20


String s1 = "Ja" + "va";
String s2 = "Java";

System.out.println(s1 == s2);

Output


true

Explanation

Compiler performs String constant folding and uses the String Pool.

Most Common Topics Covered

  • String Pool
  • Wrapper Classes
  • Integer Cache
  • StringBuilder
  • Exception Handling
  • finally Block
  • instanceof Operator
  • Collection Framework
  • Immutability
  • Operators

Interview Tips

  • Never assume == compares content.
  • Know Integer cache behaviour.
  • Understand String Pool concepts.
  • Remember finally block execution rules.
  • Practice output-based questions regularly.
  • Focus on Java memory concepts and object references.

Conclusion

Output-based Java questions reveal how well a developer understands JVM behavior, String Pool, Collections, Wrapper Classes and Exception Handling. Mastering these questions can significantly improve interview performance for both mid-level and senior Java developers.

Keywords

Java Output Questions, Java Interview Puzzles, Tricky Java Questions, Java Coding Questions, Java Interview Preparation, Java String Pool Questions, Java Integer Cache, Java instanceof Examples, Java Output Programs, Core Java Interview Questions, Java Will It Work Questions, Java Puzzle Examples, Java Coding Interview Questions, Java Senior Developer Interview, Java Technical Interview Preparation

20 Tricky Java Output Questions Every Experienced Developer Should Know 20 Tricky Java Output Questions Every Experienced Developer Should Know Reviewed by 13thGhost on 3:42 PM Rating: 5

How HashMap Works Internally in Java with Examples

2:05 AM

HashMap is one of the most frequently used classes in Java and is a favourite topic in Java interviews. Almost every Java developer uses HashMap, but very few understand how it works internally. In this article, we will explore the internal working of HashMap, including buckets, hashCode(), collisions, linked lists, treeification, and performance optimizations.

What is HashMap?

HashMap is a part of the Java Collections Framework and is used to store data in key-value pairs. It allows one null key and multiple null values. HashMap does not maintain insertion order.


Map<Integer, String> employeeMap = new HashMap<>();

employeeMap.put(1, "John");
employeeMap.put(2, "David");
employeeMap.put(3, "Alex");

Important Characteristics of HashMap

  • Stores data as key-value pairs
  • Allows one null key
  • Allows multiple null values
  • Not synchronized
  • Provides nearly O(1) lookup performance
  • Uses hashing mechanism internally

Internal Structure of HashMap

Internally, HashMap stores data inside an array called buckets. Each bucket can contain multiple entries.


Bucket[0]
Bucket[1]
Bucket[2]
Bucket[3]
...
Bucket[n]

Whenever a key-value pair is inserted, HashMap calculates which bucket should contain the entry.

How put() Works Internally

When we add an element into HashMap:


map.put(101, "Java");

The following steps occur internally:

  1. HashMap calls hashCode() on the key.
  2. A hash value is generated.
  3. The bucket index is calculated.
  4. The key-value pair is stored in the bucket.
  5. If the bucket already contains data, collision handling occurs.

Example


Integer key = 101;

int hash = key.hashCode();

The generated hash helps HashMap identify the correct bucket location.

How get() Works Internally

Retrieving a value from HashMap is fast because Java calculates the bucket directly.


String course = map.get(101);

HashMap performs these operations:

  1. Calculate hashCode() of the key.
  2. Identify bucket index.
  3. Search inside the bucket.
  4. Compare keys using equals().
  5. Return matching value.

What is Collision in HashMap?

A collision occurs when two different keys generate the same bucket index.


map.put(1, "Java");
map.put(17, "Spring");

Both keys may point to the same bucket. In such cases HashMap stores multiple entries inside that bucket.

Collision Handling Before Java 8

Before Java 8, collisions were handled using Linked Lists.


Bucket 15

Key1 -> Key2 -> Key3 -> Key4

Searching becomes slower as the linked list grows.

Collision Handling in Java 8 and Later

Java 8 introduced Treeification. When the number of entries in a bucket exceeds a threshold, the linked list converts into a Red-Black Tree.


Bucket 15

         7
       /   \
      3     12
     / \   / \
    1  5 10 15

This improves lookup performance significantly.

Performance Comparison

Structure Search Complexity
Linked List O(n)
Red Black Tree O(log n)

Why equals() and hashCode() Are Important

HashMap relies heavily on both hashCode() and equals().

hashCode() identifies the bucket and equals() identifies the exact object within that bucket.

Example


public class Employee {

    private int id;

    public Employee(int id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        return id;
    }

    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(obj == null || getClass() != obj.getClass())
            return false;

        Employee emp = (Employee)obj;

        return id == emp.id;
    }
}

Overriding both methods correctly ensures HashMap behaves properly.

Initial Capacity and Load Factor

HashMap uses two important parameters:

  • Initial Capacity = 16
  • Load Factor = 0.75

When capacity reaches 75%, HashMap automatically resizes.


Map<Integer,String> map =
new HashMap<>(32,0.75f);

Time Complexity of HashMap Operations

Operation Complexity
put() O(1)
get() O(1)
remove() O(1)
Worst Case O(log n)

Real-World Example


Map<Integer,String> employees =
new HashMap<>();

employees.put(101,"John");
employees.put(102,"David");
employees.put(103,"Alex");

System.out.println(employees.get(102));

Output


David

Common HashMap Interview Questions

  1. How does HashMap work internally?
  2. What causes a collision?
  3. What is Treeification?
  4. Difference between HashMap and Hashtable?
  5. Why override equals() and hashCode()?
  6. What is Load Factor?
  7. Can HashMap have null keys?
  8. What is the default capacity of HashMap?

Conclusion

HashMap is one of the most important data structures in Java. It provides near constant-time performance using hashing techniques. Understanding buckets, hashCode(), equals(), collisions, linked lists, and red-black trees will help developers write efficient applications and perform well in Java interviews.

Related Articles

Keywords

HashMap Internal Working, How HashMap Works in Java, HashMap Interview Questions, Java Collections Framework, HashMap Collision Handling, HashMap Java 8, HashMap Buckets, hashCode and equals in Java, Java HashMap Examples, HashMap Performance, Treeification in HashMap, Java Collection Interview Questions, HashMap Time Complexity, Java Core Concepts, Java Programming Tutorial

How HashMap Works Internally in Java with Examples How HashMap Works Internally in Java with Examples Reviewed by 13thGhost on 2:05 AM Rating: 5

What is the difference between Abstraction and Encapsulation in OOPS in Java?

2:17 AM

 Encapsulation and Abstraction are two fundamental concepts in Object-Oriented Programming (OOP) that help to promote modularity, reusability, and maintainability in code. In this blog post, we will explore the differences between encapsulation and abstraction in Java, as well as the steps and commands required to implement them.

abstraction and encapsulation in java

Encapsulation refers to the practice of hiding the implementation details of an object and exposing only the necessary information to the outside world. This is achieved by using access modifiers such as private, protected, and public. For example, in Java, we can use the private access modifier to restrict access to a class's fields and methods, making them only accessible within the class.

To implement encapsulation in Java, we can use the following steps:


  1. Create a class with fields and methods
  2. Use the private access modifier to restrict access to the fields and methods
  3. Provide public getter and setter methods to access the private fields.

Example:

class EncapsulationExample {
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Abstraction, on the other hand, refers to the practice of hiding the complexity of an object and exposing only the essential features to the outside world. This is achieved by creating abstract classes and interfaces. An abstract class is a class that cannot be instantiated and is used as a blueprint for other classes. An interface is a collection of abstract methods that must be implemented by any class that implements the interface.


To implement abstraction in Java, we can use the following steps:


  1. Create an abstract class or interface
  2. Declare abstract methods in the abstract class or interface
  3. Implement the abstract methods in the concrete class

Example:

abstract class AbstractionExample {
    public abstract void print();
}

class ConcreteClass extends AbstractionExample {
    public void print() {
        System.out.println("This is a concrete class");
    }
}

Comparison of Encapsulation and Abstraction:

EncapsulationAbstraction
Hides implementation details of an objectHides complexity of an object
Achieved by using access modifiersAchieved by using abstract classes and interfaces
Provides a level of securityProvides a level of flexibility
Encourages reusabilityEncourages modularity

In summary, encapsulation and abstraction are two important concepts in OOP that work together to promote maintainability, reusability, and security in code. Encapsulation is the practice of hiding the implementation details of an object and abstraction is the practice of hiding the complexity of an object. Both are achieved by using access modifiers and abstract classes and interfaces respectively in Java.

What is the difference between Abstraction and Encapsulation in OOPS in Java? What is the difference between Abstraction and Encapsulation in OOPS in Java? Reviewed by 13thGhost on 2:17 AM Rating: 5

Recommended Posts

Powered by Blogger.