Java

Java

Top Interview Questions

About Java

 

Introduction to Java

Java is one of the most popular, versatile, and powerful programming languages in the world. Developed by James Gosling and his team at Sun Microsystems in 1995, Java was designed with the philosophy of “Write Once, Run Anywhere” (WORA). This means that Java programs can run on any platform that has a compatible Java Virtual Machine (JVM), making Java a truly platform-independent language. Over the years, Java has evolved into a robust ecosystem used for building desktop applications, web applications, enterprise systems, mobile apps, cloud services, and more.


Features of Java

Java offers several features that make it reliable, secure, and developer-friendly:

1. Platform Independent

Java code is compiled into bytecode, which is not specific to any operating system. This bytecode runs on the JVM, allowing Java programs to execute on Windows, Linux, macOS, and other platforms without modification.

2. Object-Oriented

Java is a fully object-oriented language, which means it is based on concepts like:

  • Classes

  • Objects

  • Inheritance

  • Polymorphism

  • Encapsulation

  • Abstraction

These concepts help developers build modular, reusable, and maintainable code.

3. Simple and Easy to Learn

Java syntax is similar to C and C++, but it removes complex features like pointers and multiple inheritance, making it simpler and less error-prone.

4. Secure

Java provides a secure execution environment through features like:

  • Bytecode verification

  • No explicit pointers

  • Security Manager

  • Sandbox execution

These features protect systems from malicious code.

5. Robust

Java emphasizes strong memory management, exception handling, and type checking. The automatic garbage collection feature helps prevent memory leaks.

6. Multithreaded

Java supports multithreading, allowing multiple tasks to run concurrently. This improves performance and responsiveness, especially in applications like games, servers, and real-time systems.

7. High Performance

Although Java is interpreted, the Just-In-Time (JIT) compiler improves performance by converting bytecode into native machine code at runtime.


Java Architecture

Java follows a three-step execution model:

  1. Java Source Code (.java)
    Written by the programmer.

  2. Compiler (javac)
    Converts source code into bytecode (.class).

  3. Java Virtual Machine (JVM)
    Executes the bytecode on the target machine.

Key Components:

  • JDK (Java Development Kit): Used for developing Java applications.

  • JRE (Java Runtime Environment): Required to run Java applications.

  • JVM (Java Virtual Machine): Executes Java bytecode.


Object-Oriented Programming Concepts in Java

1. Class and Object

A class is a blueprint, and an object is an instance of that class.

2. Encapsulation

Encapsulation binds data and methods together and restricts direct access using access modifiers like private, protected, and public.

3. Inheritance

Inheritance allows one class to acquire properties of another class using the extends keyword.

4. Polymorphism

Polymorphism allows methods to perform different tasks based on context. It is achieved through:

  • Method Overloading

  • Method Overriding

5. Abstraction

Abstraction hides implementation details and shows only essential features using abstract classes and interfaces.


Java Packages and Libraries

Java provides a rich set of built-in packages, including:

  • java.lang – Core classes (String, Math, Object)

  • java.util – Data structures and utilities

  • java.io – Input/Output operations

  • java.sql – Database connectivity

  • java.time – Date and time API

  • java.net – Networking support

These libraries reduce development time and improve code reliability.


Exception Handling in Java

Exception handling helps manage runtime errors gracefully. Java uses keywords such as:

  • try

  • catch

  • finally

  • throw

  • throws

By handling exceptions properly, Java applications become more robust and reliable.


Java Memory Management

Java handles memory automatically using Garbage Collection. Memory is divided into:

  • Heap – Stores objects

  • Stack – Stores method calls and local variables

  • Method Area – Stores class metadata

Garbage Collector automatically removes unused objects, improving application stability.


Java Applications

Java is widely used across various domains:

1. Desktop Applications

Tools like Eclipse, IntelliJ IDEA, and NetBeans are built using Java.

2. Web Applications

Java frameworks such as Spring, Spring Boot, Hibernate, and Struts are popular for building enterprise-grade web applications.

3. Mobile Applications

Java is the primary language for Android app development.

4. Enterprise Applications

Java is extensively used in banking, insurance, and large-scale enterprise systems due to its scalability and security.

5. Big Data and Cloud

Technologies like Hadoop, Spark, and Kafka are built using Java.


Advantages of Java

  • Platform independent

  • Secure and robust

  • Large community support

  • Rich API and frameworks

  • Strong backward compatibility

  • High demand in the job market


Limitations of Java

  • Slower than some low-level languages like C/C++

  • Requires more memory

  • Verbose syntax compared to modern languages

Despite these limitations, Java remains a preferred choice for enterprise and large-scale systems.


Future of Java

Java continues to evolve with regular updates. Modern versions introduce features like:

  • Lambda expressions

  • Streams API

  • Modules

  • Improved garbage collectors

  • Enhanced performance

With its strong ecosystem and continuous innovation, Java remains future-proof.

Fresher Interview Questions

 

1. What is Java?

Answer:
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now owned by Oracle). Java is used to develop web applications, mobile apps (Android), desktop applications, enterprise systems, and embedded systems.

Key features of Java include:

  • Object-Oriented

  • Platform Independent

  • Secure

  • Robust

  • Multithreaded


2. Why is Java platform-independent?

Answer:
Java is platform-independent because it uses Bytecode.
When Java code is compiled, it is converted into bytecode (.class file). This bytecode can run on any system that has a Java Virtual Machine (JVM), regardless of the operating system.

Concept:

Write Once, Run Anywhere (WORA)


3. What is JVM?

Answer:
JVM (Java Virtual Machine) is a virtual machine that:

  • Executes Java bytecode

  • Converts bytecode into machine code

  • Manages memory

  • Provides security

JVM is platform-dependent, but Java programs are platform-independent.


4. What is JDK and JRE?

Answer:

JDK (Java Development Kit)

  • Used by developers

  • Contains JRE + development tools (javac, debugger)

JRE (Java Runtime Environment)

  • Used to run Java programs

  • Contains JVM + core libraries


5. What are the main features of Java?

Answer:

  • Simple

  • Object-Oriented

  • Platform Independent

  • Secure

  • Robust

  • Multithreading

  • High Performance

  • Distributed


6. What is Object-Oriented Programming (OOP)?

Answer:
OOP is a programming approach based on objects, which contain data and methods.

Java supports OOP through:

  1. Encapsulation

  2. Inheritance

  3. Polymorphism

  4. Abstraction


7. What is a Class?

Answer:
A class is a blueprint or template used to create objects. It defines properties (variables) and behaviors (methods).

Example:

class Student {
    int id;
    String name;
}

8. What is an Object?

Answer:
An object is an instance of a class. It represents real-world entities.

Example:

Student s1 = new Student();

9. What is Encapsulation?

Answer:
Encapsulation is the process of wrapping data and methods together and protecting data using access modifiers.

Example:

class Employee {
    private int salary;

    public int getSalary() {
        return salary;
    }
}

10. What is Inheritance?

Answer:
Inheritance allows one class to acquire properties of another class using the extends keyword.

Example:

class Animal {
    void eat() {}
}

class Dog extends Animal {
    void bark() {}
}

11. What is Polymorphism?

Answer:
Polymorphism means many forms.
It allows methods to behave differently based on the object.

Types:

  • Compile-time (Method Overloading)

  • Runtime (Method Overriding)


12. What is Method Overloading?

Answer:
When multiple methods have the same name but different parameters, it is method overloading.

Example:

int add(int a, int b) {}
int add(int a, int b, int c) {}

13. What is Method Overriding?

Answer:
When a subclass provides a specific implementation of a method already defined in its parent class.

Example:

class Parent {
    void show() {}
}

class Child extends Parent {
    void show() {}
}

14. What is Abstraction?

Answer:
Abstraction hides implementation details and shows only functionality.

Achieved using:

  • Abstract classes

  • Interfaces


15. What is an Interface?

Answer:
An interface is a blueprint that contains abstract methods and constants.

Example:

interface Vehicle {
    void run();
}

16. What is an Abstract Class?

Answer:
An abstract class can have both abstract and non-abstract methods.

Example:

abstract class Shape {
    abstract void draw();
}

17. What are Access Modifiers?

Answer:

Modifier Scope
public Everywhere
protected Same package + subclass
default Same package
private Same class

18. What is Constructor?

Answer:
A constructor is a special method used to initialize objects.

Rules:

  • Same name as class

  • No return type

Example:

class Test {
    Test() {
        System.out.println("Constructor called");
    }
}

19. What is static keyword?

Answer:
static belongs to the class, not objects.

Uses:

  • Static variables

  • Static methods

  • Static blocks


20. What is final keyword?

Answer:

  • final variable → value cannot change

  • final method → cannot override

  • final class → cannot inherit


21. What is Exception?

Answer:
An exception is an unexpected event that disrupts program execution.

Types:

  • Checked Exceptions

  • Unchecked Exceptions


22. What is try-catch block?

Answer:
Used to handle exceptions and prevent program crash.

Example:

try {
    int a = 10 / 0;
} catch (Exception e) {
    System.out.println(e);
}

23. What is Multithreading?

Answer:
Multithreading allows multiple threads to run simultaneously, improving performance.


24. What is Garbage Collection?

Answer:
Garbage Collection automatically removes unused objects from memory to free space.


25. What is String in Java?

Answer:
String is an immutable object used to store text.

Example:

String s = "Java";

26. Difference between == and .equals()?

Answer:

  • == compares memory reference

  • .equals() compares content


27. What is Array?

Answer:
An array is a collection of similar data types stored in contiguous memory.

Example:

int[] a = {1, 2, 3};

28. What is Package?

Answer:
A package is a group of related classes and interfaces.

Example:

package com.company.project;

29. What is Collection Framework?

Answer:
Collection Framework provides classes like:

  • List

  • Set

  • Map

  • Queue


30. Difference between List and Set?

Answer:

  • List allows duplicates

  • Set does not allow duplicates


31. What is the difference between JDK, JRE, and JVM?

Answer:

  • JDK: Used for development (JRE + tools like compiler)

  • JRE: Used to run Java programs

  • JVM: Executes bytecode and manages memory


32. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread-safe Yes No Yes
Performance Slow Fast Medium

33. What is Immutable Object?

Answer:
An immutable object cannot be changed after creation.
Example: String


34. What is Wrapper Class?

Answer:
Wrapper classes convert primitive data types into objects.

Examples:

  • int → Integer

  • char → Character


35. What is Autoboxing and Unboxing?

Answer:

  • Autoboxing: Primitive → Wrapper

  • Unboxing: Wrapper → Primitive


36. What is ArrayList?

Answer:
ArrayList is a resizable array implementation of List.


37. Difference between Array and ArrayList?

Answer:

Array ArrayList
Fixed size Dynamic size
Can store primitives Stores objects only
Faster Slightly slower

38. What is LinkedList?

Answer:
LinkedList stores elements as nodes with pointers.


39. Difference between ArrayList and LinkedList?

Answer:

  • ArrayList → faster access

  • LinkedList → faster insertion/deletion


40. What is HashMap?

Answer:
HashMap stores data in key-value pairs and allows one null key.


41. Difference between HashMap and Hashtable?

Answer:

  • HashMap is non-synchronized

  • Hashtable is synchronized

  • HashMap allows null keys; Hashtable doesn’t


42. What is Set?

Answer:
Set does not allow duplicate elements.


43. What is HashSet?

Answer:
HashSet uses hashing and does not maintain insertion order.


44. Difference between HashSet and TreeSet?

Answer:

  • HashSet → no order

  • TreeSet → sorted order


45. What is Map?

Answer:
Map stores data as key-value pairs.


46. What is Iterator?

Answer:
Iterator is used to traverse collections.


47. Difference between Iterator and Enumeration?

Answer:

  • Iterator is universal

  • Enumeration is legacy


48. What is Exception Handling?

Answer:
Handling runtime errors using try, catch, finally.


49. Difference between Checked and Unchecked Exception?

Answer:

  • Checked → compile-time

  • Unchecked → runtime


50. What is finally block?

Answer:
Always executes whether exception occurs or not.


51. What is throw vs throws?

Answer:

  • throw → explicitly throw exception

  • throws → declare exception


52. What is Multithreading?

Answer:
Running multiple threads simultaneously.


53. Difference between Thread and Runnable?

Answer:

  • Thread → class

  • Runnable → interface


54. What is Synchronization?

Answer:
Controls access to shared resources.


55. What is Deadlock?

Answer:
Threads waiting for each other forever.


56. What is Serialization?

Answer:
Converting object into byte stream.


57. What is Deserialization?

Answer:
Converting byte stream back to object.


58. What is transient keyword?

Answer:
Prevents variable from serialization.


59. What is Java 8 Stream?

Answer:
Processes collections in functional style.


60. What is Lambda Expression?

Answer:
Short syntax for functional interfaces.

Example:

(a, b) -> a + b

Experienced Interview Questions

 

1. Explain JVM architecture in detail

Answer:
JVM consists of:

a) ClassLoader

  • Loads .class files into memory

  • Types: Bootstrap, Extension, Application

b) Runtime Data Areas

  • Heap: Stores objects

  • Stack: Stores method calls & local variables

  • Method Area / Metaspace: Class metadata

  • PC Register: Tracks current instruction

  • Native Method Stack

c) Execution Engine

  • Interpreter

  • JIT Compiler

  • Garbage Collector


2. How does Garbage Collection work in Java?

Answer:
GC automatically removes unused objects.

GC Areas:

  • Young Generation (Eden, Survivor)

  • Old Generation

  • Metaspace

Common GC Algorithms:

  • Serial GC

  • Parallel GC

  • CMS

  • G1 GC


3. Difference between == and .equals() (Real-time)

Answer:

  • == compares reference

  • .equals() compares content

In HashMap, equals() and hashCode() must be consistent.


4. What is hashCode() and why is it important?

Answer:
hashCode() returns an integer used in hashing collections like HashMap.

Contract:

  • If equals() is true, hashCode must be same

  • Same hashCode does not guarantee equals


5. How HashMap works internally?

Answer:

  • Uses array of buckets

  • Uses hash function

  • Uses linked list / red-black tree (Java 8+)

Time complexity:

  • Average: O(1)

  • Worst: O(log n)


6. Difference between HashMap and ConcurrentHashMap

Answer:

  • HashMap → Not thread-safe

  • ConcurrentHashMap → Thread-safe with segment locking

  • No null keys allowed in ConcurrentHashMap


7. What is Fail-Fast vs Fail-Safe Iterator?

Answer:

  • Fail-Fast → throws ConcurrentModificationException

  • Fail-Safe → works on copy

Example:

  • Fail-Fast → ArrayList

  • Fail-Safe → CopyOnWriteArrayList


8. How does ArrayList grow internally?

Answer:

  • Initial capacity: 10

  • Growth formula: newCapacity = old * 1.5


9. Difference between Comparable and Comparator

Answer:

  • Comparable → natural ordering

  • Comparator → custom ordering


10. Explain immutability with example

Answer:
Immutable objects cannot change state.

Benefits:

  • Thread-safe

  • Secure

  • Caching

Example: String


11. Explain Java Memory Model (JMM)

Answer:
Defines how threads interact through memory.

Key concepts:

  • Happens-before

  • Visibility

  • Atomicity


12. Difference between volatile and synchronized

Answer:

  • volatile → visibility only

  • synchronized → visibility + atomicity


13. How does synchronization work internally?

Answer:
Uses object monitor, mutex locks, and lock escalation.


14. What is Deadlock and how to prevent it?

Answer:
Deadlock occurs when threads wait for each other.

Prevention:

  • Lock ordering

  • Timeout

  • Avoid nested locks


15. Difference between Thread and Executor framework

Answer:
Executor manages thread lifecycle efficiently.


16. Explain Thread Pool

Answer:
Reuses threads to improve performance.


17. Difference between Runnable and Callable

Answer:

  • Runnable → no return

  • Callable → returns result and throws exception


18. What is Future and CompletableFuture?

Answer:

  • Future → result of async task

  • CompletableFuture → non-blocking async programming


19. Explain Java 8 Streams in real-time

Answer:
Processes collections functionally.

Example:

list.stream()
    .filter(x -> x > 10)
    .map(x -> x * 2)
    .collect(Collectors.toList());

20. Difference between map() and flatMap()

Answer:

  • map → one-to-one

  • flatMap → one-to-many flattening


21. Explain Optional class

Answer:
Avoids NullPointerException.


22. What are Functional Interfaces?

Answer:
Interface with single abstract method.

Example:

  • Runnable

  • Comparator

  • Supplier


23. How does Exception handling work in enterprise apps?

Answer:

  • Custom exceptions

  • Global exception handlers

  • Logging

  • Meaningful error codes


24. Difference between Checked and Unchecked Exceptions (Real-time)

Answer:
Checked → business logic
Unchecked → programming errors


25. Explain try-with-resources

Answer:
Automatically closes resources.


26. What is Serialization? Problems?

Answer:
Object → byte stream.

Problems:

  • Performance

  • Security

  • Versioning


27. What is transient and serialVersionUID?

Answer:

  • transient → skip serialization

  • serialVersionUID → version control


28. How do you make a class thread-safe?

Answer:

  • Immutability

  • Synchronization

  • Concurrent collections

  • Atomic classes


29. Difference between StringBuilder and StringBuffer

Answer:

  • StringBuilder → faster, not thread-safe

  • StringBuffer → thread-safe


30. What is Reflection and its use?

Answer:
Allows runtime inspection of classes.

Used in:

  • Spring

  • Hibernate


31. How does Spring use Java concepts internally?

Answer:

  • Reflection

  • Dependency Injection

  • Proxies

  • AOP


32. Difference between shallow copy and deep copy

Answer:

  • Shallow → reference copy

  • Deep → actual object copy


33. What are Design Patterns commonly used in Java?

Answer:

  • Singleton

  • Factory

  • Builder

  • Observer

  • DAO


34. Explain Singleton in multi-threaded environment

Answer:
Use double-checked locking.


35. What is SOLID principle?

Answer:

  • S – Single Responsibility

  • O – Open/Closed

  • L – Liskov Substitution

  • I – Interface Segregation

  • D – Dependency Inversion


36. How do you improve Java application performance?

Answer:

  • Efficient collections

  • Caching

  • JVM tuning

  • Thread pools


37. What is ClassLoader leak?

Answer:
Occurs when classes are not unloaded properly.


38. Difference between Soft, Weak, Phantom reference

Answer:

  • Soft → cache

  • Weak → GC quickly

  • Phantom → cleanup


39. What is Microservices impact on Java apps?

Answer:

  • Lightweight JVM

  • Faster startup

  • Reactive programming


40. Common mistakes in Java projects

Answer:

  • Memory leaks

  • Poor exception handling

  • Improper synchronization++++++++


41. How does ConcurrentHashMap work internally?

Answer:

  • Uses bucket-level locking

  • Java 8 uses CAS (Compare-And-Swap) instead of segment locking

  • Allows concurrent read/write

  • No null keys or values


42. Why HashMap allows one null key but ConcurrentHashMap doesn’t?

Answer:
To avoid ambiguity during concurrent operations and prevent NullPointerException.


43. What is CAS (Compare-And-Swap)?

Answer:
A low-level atomic operation used in multithreading to update values without locks.


44. What is Fork/Join Framework?

Answer:
Used for parallel processing by dividing tasks into smaller subtasks.


45. Difference between submit() and execute() in ExecutorService?

Answer:

  • execute() → no return

  • submit() → returns Future


46. What is ThreadLocal and where is it used?

Answer:
Stores thread-specific data.

Used in:

  • User sessions

  • Database connections

  • Logging


47. How do you detect memory leaks in Java?

Answer:

  • Heap dump

  • JVisualVM

  • JProfiler

  • GC logs


48. What is OutOfMemoryError? Types?

Answer:

  • Heap space

  • Metaspace

  • GC overhead

  • Direct buffer memory


49. What is PermGen vs Metaspace?

Answer:

  • PermGen (Java 7) → fixed size

  • Metaspace (Java 8+) → native memory


50. What is JVM tuning?

Answer:
Optimizing JVM parameters like heap size and GC algorithm.


51. Difference between Parallel Stream and Sequential Stream?

Answer:

  • Parallel → multi-core processing

  • Sequential → single thread


52. When not to use Parallel Streams?

Answer:

  • Small data sets

  • IO-heavy tasks

  • Shared mutable state


53. What is Spliterator?

Answer:
Used by streams to split data for parallel processing.


54. How does Stream API handle lazy evaluation?

Answer:
Intermediate operations execute only when terminal operation is called.


55. What is Backpressure?

Answer:
Controls data flow in reactive systems.


56. Difference between Reactive and Imperative programming?

Answer:

  • Imperative → step-by-step

  • Reactive → event-driven


57. What is Java NIO?

Answer:
Non-blocking IO with buffers and channels.


58. Difference between IO and NIO?

Answer:

  • IO → blocking

  • NIO → non-blocking


59. What is CompletableFuture chaining?

Answer:
Allows async task composition.


60. Difference between thenApply() and thenCompose()?

Answer:

  • thenApply → transforms result

  • thenCompose → flattens async result


61. How does JDBC connection pooling work?

Answer:
Reuses database connections to improve performance.


62. What is HikariCP?

Answer:
A fast JDBC connection pool.


63. How do you prevent SQL Injection?

Answer:

  • PreparedStatement

  • Input validation

  • ORM frameworks


64. Difference between Statement and PreparedStatement?

Answer:

  • Statement → slow, unsafe

  • PreparedStatement → fast, secure


65. What is Batch Processing in JDBC?

Answer:
Executes multiple SQL statements together.


66. What is Transaction Management?

Answer:
Ensures ACID properties.


67. Difference between Optimistic and Pessimistic Locking?

Answer:

  • Optimistic → version-based

  • Pessimistic → database locks


68. How do you handle millions of records efficiently?

Answer:

  • Pagination

  • Streaming

  • Batch processing

  • Indexing


69. What is ORM?

Answer:
Maps Java objects to database tables.


70. Common issues with Hibernate?

Answer:

  • N+1 problem

  • LazyInitializationException


71. How do you solve N+1 problem?

Answer:

  • Fetch joins

  • Batch fetching


72. What is First-level and Second-level cache?

Answer:

  • First-level → Session cache

  • Second-level → Application-wide


73. Difference between @Component, @Service, @Repository?

Answer:
Used for stereotype classification in Spring.


74. What is AOP?

Answer:
Aspect-Oriented Programming for cross-cutting concerns.


75. How does Spring handle transactions?

Answer:
Using proxies and annotations.


76. What is REST and RESTful services?

Answer:
Stateless web services using HTTP methods.


77. Difference between PUT and PATCH?

Answer:

  • PUT → full update

  • PATCH → partial update


78. What is Idempotency?

Answer:
Multiple calls give same result.


79. How do you secure Java applications?

Answer:

  • Authentication

  • Authorization

  • Encryption

  • Secure coding


80. Real-time production issues in Java apps

Answer:

  • Memory leaks

  • Thread starvation

  • Slow GC