Java Programming

Java Programming – SECTION 1

Fundamentals (Q1–Q20)

Q1. What is Java and why is it heavily used in large enterprise systems?

Java is a high‑level, object‑oriented programming language designed for reliability and portability. It follows the principle of "Write Once, Run Anywhere" because Java code runs on the JVM instead of directly on hardware. Enterprises prefer Java because it offers strong memory management, multithreading, security features, and long‑term stability. Java also has a massive ecosystem of frameworks such as Spring and Hibernate that support large applications. Because of these features, Java is widely used in banking, telecom, insurance, and government systems.

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Java");
    }
}

Tip: In interviews say Java is platform‑independent, secure, and enterprise ready.


Q2. Explain JVM, JRE, and JDK in detail.

JVM (Java Virtual Machine) executes Java bytecode and converts it into machine code. JRE (Java Runtime Environment) contains JVM plus core libraries needed to run Java programs. JDK (Java Development Kit) includes JRE along with development tools like compiler and debugger. Developers use JDK to write programs, users need JRE to run them. This layered architecture is the reason Java works across operating systems.

javac Main.java
java Main

Tip: Remember order: JDK → JRE → JVM.


Q3. What are primitive data types in Java and why are they important?

Java provides eight primitive types: byte, short, int, long, float, double, char, and boolean. These store simple values directly in memory and are faster than objects. They have fixed sizes which helps performance optimization. Primitive types are commonly used in loops, calculations, and high‑performance systems. Understanding primitives helps avoid unnecessary memory overhead.

int age = 25;
double salary = 55000.50;
boolean active = true;

Tip: Primitives store values, objects store references.


Q4. What is a class and what is an object?

A class is a blueprint that defines properties and behaviors. An object is a real instance created from that class. Classes describe structure, while objects hold actual data. Java programs are built around objects interacting with each other. This concept is the foundation of object‑oriented programming.

class User {
    String name;
}

User u = new User();
u.name = "Sumit";

Tip: Class = design, Object = reality.


Q5. What is a constructor and why is it used?

A constructor is a special method used to initialize objects. It has the same name as the class and no return type. Constructors run automatically when an object is created. They help assign initial values and perform setup tasks. Constructors can also be overloaded.

class User {
    User() {
        System.out.println("User created");
    }
}

Tip: Constructors prepare objects for use.


Q6. Explain method overloading with example.

Method overloading means having multiple methods with the same name but different parameters. It improves readability and flexibility. Java decides which method to call at compile time. This is known as compile‑time polymorphism. It is widely used in Java libraries.

class Calc {
    int add(int a,int b){ return a+b; }
    double add(double a,double b){ return a+b; }
}

Tip: Same name, different parameters.


Q7. What is inheritance and how does it help?

Inheritance allows a class to acquire properties of another class. It promotes code reuse and reduces duplication. The child class uses the extends keyword. Inheritance supports hierarchical relationships. It is a core concept for building scalable systems.

class A { }
class B extends A { }

Tip: Parent → Child relationship.


Q8. Explain encapsulation.

Encapsulation hides internal data and exposes controlled access. Variables are kept private and accessed through getters and setters. This protects data from accidental modification. Encapsulation improves maintainability and security. It is widely used in enterprise applications.

private int age;

Tip: Always keep variables private.


Q9. What is abstraction?

Abstraction shows only essential features and hides implementation details. It is achieved using abstract classes or interfaces. Abstraction reduces complexity in large systems. Developers focus on what an object does rather than how it works. It supports loose coupling.

abstract class Shape {
    abstract void draw();
}

Tip: Abstraction simplifies design.


Q10. What is polymorphism?

Polymorphism means many forms. It allows the same method to behave differently based on object type. Runtime polymorphism is achieved using method overriding. This makes systems flexible and extensible. Frameworks rely heavily on polymorphism.

@Override
void draw() { }

Tip: One interface, many implementations.


Q11. Difference between == and equals()?

== compares memory references. equals() compares actual content. For objects like String, equals() is overridden to check values. Using == on objects often produces wrong results. This is a very common interview trap.

s1.equals(s2);

Tip: Use equals() for objects.


Q12. Why are Strings immutable in Java?

Strings cannot be changed after creation. Any modification creates a new object. This improves security, thread safety, and caching. String pool optimizes memory usage. Immutability is critical in authentication systems.

String s = "Hi";
s = s + "!";

Tip: Strings are safe and shared.


Q13. What does static mean?

Static members belong to the class, not objects. They are shared across all instances. Static methods can be called without creating objects. Static is commonly used for utility functions and constants. The main method is static.

static int count;

Tip: Static = class level.


Q14. Explain final keyword.

Final prevents modification. Final variables cannot change. Final methods cannot be overridden. Final classes cannot be inherited. It is used to enforce design rules and improve safety.

final int x = 10;

Tip: Final locks behavior.


Q15. What is this keyword?

This refers to the current object. It resolves variable conflicts. Commonly used inside constructors. It improves clarity in code. Frequently seen in setters.

this.age = age;

Tip: this = current object.


Q16. What is super keyword?

Super refers to parent class object. It calls parent constructors and methods. Used when child overrides parent behavior. Helps reuse parent logic.

super();

Tip: super = parent.


Q17. What are packages?

Packages organize related classes. They prevent name conflicts. Improve project structure. Used heavily in enterprise applications. Java standard library is package based.

package com.app;

Tip: Packages group code logically.


Q18. What are access modifiers?

Access modifiers control visibility. public allows everywhere access. private restricts to class. protected allows inheritance. Default is package‑private. They enforce encapsulation.

private int id;

Tip: Private by default is best practice.


Q19. What is the main method?

Main is program entry point. JVM starts execution here. It must be public and static. Without main, application cannot start. Every Java application requires it.

public static void main(String[] args){}

Tip: JVM looks for main.


Q20. What are command line arguments?

Command line arguments allow passing values during program execution. They are received through args array. Useful for configuration. Common in batch programs. Avoid hardcoding values.

System.out.println(args[0]);

Tip: args provide runtime input.


SECTION 2 – Object-Oriented Programming in Java (Q21–Q40)

Q21. What is Object-Oriented Programming in Java and why is it important?

Explanation

Object-Oriented Programming (OOP) is a programming approach where software is designed around objects instead of functions.
An object represents a real-world entity and contains both data (variables) and behavior (methods).
Java is fully based on OOP principles, which makes large applications easier to design, scale, and maintain.
OOP helps reduce code duplication by promoting reuse through inheritance and composition.
In enterprise systems, OOP improves readability, testing, and teamwork because code is organized logically.

Example

class User { String name; void greet() { System.out.println("Hello " + name); } } public class Main { public static void main(String[] args) { User u = new User(); u.name = "Sumit"; u.greet(); } }

Tip

Interviewers expect you to explain OOP using real-world examples like “Car”, “User”, or “BankAccount”.


Q22. What is a Class in Java?

Explanation

A class is a blueprint or template used to create objects.
It defines what data an object will store and what actions it can perform.
Classes help organize code into logical units.
Without classes, Java programs would become unmanageable for large projects.
Every object in Java is created from a class.

Example

class Car { String brand; void drive() { System.out.println("Car is driving"); } }

Tip

Remember: Class = design, Object = actual thing.


Q23. What is an Object in Java?

Explanation

An object is a real instance of a class.
It occupies memory and represents actual data during program execution.
Objects interact with each other using methods.
Each object has its own state and behavior.
Most Java applications work by passing objects between layers.

Example

Car c = new Car(); c.brand = "BMW"; c.drive();

Tip

Say clearly: objects are created using the new keyword.


Q24. Explain Encapsulation in Java.

Explanation

Encapsulation means hiding internal data and exposing it through controlled methods.
Variables are marked private and accessed using getters and setters.
This protects data from accidental modification.
Encapsulation improves maintainability and security.
It is one of the most asked interview topics.

Example

class Student { private int age; public void setAge(int a) { age = a; } public int getAge() { return age; } }

Tip

Use this phrase: Encapsulation = data hiding + controlled access.


Q25. What is Inheritance?

Explanation

Inheritance allows one class to acquire properties of another class.
The child class reuses code from the parent class.
It promotes code reuse and hierarchical structure.
Java supports single inheritance using extends.
It is commonly used in framework development.

Example

class Animal { void eat() { System.out.println("Eating"); } } class Dog extends Animal { void bark() { System.out.println("Barking"); } }

Tip

Parent → Child relationship is written using extends.


Q26. What is Polymorphism?

Explanation

Polymorphism means one method behaving differently in different situations.
It is achieved using method overriding and interfaces.
It allows writing flexible and scalable code.
Runtime polymorphism is heavily used in Spring and enterprise apps.
It follows the concept “one interface, many implementations”.

Example

class Shape { void draw() { System.out.println("Drawing shape"); } } class Circle extends Shape { void draw() { System.out.println("Drawing circle"); } }

Tip

Explain: same method name, different behavior.


Q27. What is Abstraction?

Explanation

Abstraction hides implementation details and shows only required features.
It focuses on what an object does, not how.
Java provides abstraction using abstract classes and interfaces.
It simplifies complex systems.
Used heavily in API design.

Example

abstract class Bank { abstract void interest(); }

Tip

Use real-life example: ATM hides banking logic.


Q28. Difference between Abstract Class and Interface?

Explanation

Abstract class can have both abstract and concrete methods.
Interface supports only abstract methods (Java 8 added default methods).
A class can extend only one abstract class but implement multiple interfaces.
Interfaces are used for full abstraction.
Abstract classes are used for partial abstraction.

Example

interface Payment { void pay(); }

Tip

Say: interfaces support multiple inheritance.


Q29. What is Constructor?

Explanation

Constructor initializes objects.
It has same name as class.
It runs automatically when object is created.
Used to set default values.
Constructors cannot return values.

Example

class User { User() { System.out.println("User created"); } }

Tip

No return type, not even void.


Q30. What is Method Overriding?

Explanation

Method overriding occurs when child class provides its own version of parent method.
Used for runtime polymorphism.
Method signature must be same.
Access level cannot be reduced.
Common in framework callbacks.

Example

class A { void show() {} } class B extends A { void show() { System.out.println("Overridden"); } }

Tip

Always happens at runtime.


Q31. What is super keyword?

Explanation

super refers to parent class object.
Used to access parent variables and methods.
Also used to call parent constructor.
Helps avoid ambiguity.
Common in inheritance chains.

Example

super.show();

Tip

Think: super = parent reference.


Q32. What is this keyword?

Explanation

this refers to current object.
Used to differentiate instance variables.
Helps in constructor chaining.
Improves code clarity.
Frequently used in setters.

Example

this.age = age;

Tip

this always points to current class.


Q33. What is Method Overloading?

Explanation

Same method name with different parameters.
Occurs at compile time.
Improves readability.
Return type alone cannot overload.
Used in utility classes.

Example

void add(int a); void add(int a, int b);

Tip

Compile-time polymorphism.


Q34. What is Final keyword?

Explanation

Final prevents modification.
Final variable cannot change.
Final method cannot override.
Final class cannot inherit.
Used for security and constants.

Example

final int x = 10;

Tip

Final = restriction.


Q35. What is Static keyword?

Explanation

Static belongs to class, not object.
Shared across all instances.
Used for utility methods.
Reduces memory usage.
Main method is static.

Example

static void show() {}

Tip

Static members accessed without object.


Q36. What is Composition?

Explanation

Composition means HAS-A relationship.
One class contains another class object.
Preferred over inheritance.
Provides flexibility.
Used in microservices.

Example

class Engine {} class Car { Engine e = new Engine(); }

Tip

Composition > inheritance in real projects.


Q37. What is Access Modifier?

Explanation

Controls visibility of classes and members.
Public: everywhere.
Private: same class only.
Protected: same package or subclass.
Default: package scope.

Example

private int age;

Tip

Private is most restrictive.


Q38. What is instanceof?

Explanation

Checks object type at runtime.
Used before casting.
Prevents ClassCastException.
Common in polymorphism.
Returns boolean.

Example

if(obj instanceof Dog)

Tip

Used for safe downcasting.


Q39. What is Object class?

Explanation

Root class of Java hierarchy.
Every class inherits it.
Provides methods like toString().
Used internally by JVM.
Important for equality checks.

Example

Object o = new String("Hi");

Tip

All classes extend Object automatically.


Q40. What is SOLID in OOP?

Explanation

SOLID is a design principle set.
Helps build scalable systems.
Each letter represents one rule.
Used in enterprise architecture.
Improves maintainability.

Example

// Single Responsibility Principle

Tip

Mention SRP, OCP, LSP, ISP, DIP in interviews.

SECTION 3 – Exception Handling & Collections in Java (Q41–Q60)

Q41. What is Exception Handling in Java and why is it required?

Explanation

Exception Handling is a mechanism that allows Java programs to deal with runtime errors gracefully.
Instead of crashing the application, Java provides structured blocks (try, catch, finally) to manage unexpected situations.
Common errors include dividing by zero, file not found, or null references.
In enterprise applications, exception handling prevents system failure and improves user experience.
It also helps developers log errors and take recovery actions.

Example

try { int result = 10 / 0; // risky code } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }

Tip

Interviewers love hearing: Exception handling prevents abnormal program termination.


Q42. Difference between Checked and Unchecked Exceptions?

Explanation

Checked exceptions are verified at compile time and must be handled explicitly.
Unchecked exceptions occur at runtime and are not forced to be caught.
Checked exceptions usually come from external resources like files or databases.
Unchecked exceptions mostly result from programming mistakes.
Understanding this difference is critical for backend interviews.

Example

// Checked FileReader fr = new FileReader("data.txt"); // Unchecked int x = 5 / 0;

Tip

Say clearly: Checked → compile time, Unchecked → runtime.


Q43. What is try-catch-finally?

Explanation

try contains risky code.
catch handles the exception if it occurs.
finally always executes whether exception happens or not.
Finally is commonly used to close database or file resources.
This structure makes Java applications reliable.

Example

try { System.out.println(10/2); } catch(Exception e) { System.out.println("Error"); } finally { System.out.println("Always runs"); }

Tip

Finally block runs even if return statement exists.


Q44. What is throw vs throws?

Explanation

throw is used to manually create an exception.
throws declares that a method may pass exception to caller.
Throw works inside method body.
Throws works in method signature.
Both help in custom error handling.

Example

void checkAge(int age) throws Exception { if(age < 18) { throw new Exception("Underage"); } }

Tip

throw = create, throws = declare.


Q45. What is Custom Exception?

Explanation

Custom exception allows developers to create application-specific errors.
It improves clarity when something goes wrong.
Created by extending Exception class.
Used widely in banking and payment systems.
Helps separate business errors from system errors.

Example

class InvalidBalance extends Exception { InvalidBalance(String msg){ super(msg); } }

Tip

Custom exceptions improve professional code quality.


Q46. What is Java Collections Framework?

Explanation

Collections Framework provides ready-made data structures.
It stores, retrieves, and manipulates groups of objects.
Includes List, Set, Queue, Map interfaces.
Reduces coding effort significantly.
Used in almost every Java application.

Example

ArrayList<String> list = new ArrayList<>();

Tip

Always mention: Collection is interface, Collections is utility class.


Q47. Difference between ArrayList and LinkedList?

Explanation

ArrayList uses dynamic array internally.
LinkedList uses doubly linked list.
ArrayList is faster for reading.
LinkedList is faster for insertion/deletion.
Choosing correct one impacts performance.

Example

ArrayList<Integer> a = new ArrayList<>(); LinkedList<Integer> l = new LinkedList<>();

Tip

ArrayList → access, LinkedList → modification.


Q48. Difference between List, Set, and Map?

Explanation

List allows duplicate elements and maintains order.
Set does not allow duplicates.
Map stores key-value pairs.
Each serves different use cases.
Used together in real projects.

Example

List<Integer> list = new ArrayList<>(); Set<Integer> set = new HashSet<>(); Map<Integer,String> map = new HashMap<>();

Tip

Map is not part of Collection interface.


Q49. What is HashMap?

Explanation

HashMap stores data in key-value format.
It allows one null key and multiple null values.
Does not maintain insertion order.
Used for fast searching.
Widely used in caching systems.

Example

HashMap<String,Integer> map = new HashMap<>(); map.put("Age", 30);

Tip

HashMap is not synchronized.


Q50. Difference between HashMap and Hashtable?

Explanation

HashMap is not thread-safe.
Hashtable is synchronized.
HashMap allows null key.
Hashtable does not.
HashMap is faster.

Example

HashMap<String,String> hm = new HashMap<>(); Hashtable<String,String> ht = new Hashtable<>();

Tip

Modern apps prefer ConcurrentHashMap.


Q51. What is Iterator?

Explanation

Iterator is used to traverse collections.
Allows safe removal while looping.
Avoids ConcurrentModificationException.
Works with all collections.
Essential for clean iteration.

Example

Iterator it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()); }

Tip

Iterator replaces traditional loops in backend systems.


Q52. What is Comparable vs Comparator?

Explanation

Comparable sorts objects naturally.
Comparator provides custom sorting logic.
Comparable modifies class.
Comparator is external.
Used heavily in sorting APIs.

Example

Collections.sort(list);

Tip

Comparable = single logic, Comparator = multiple logic.


Q53. What is Stream API?

Explanation

Stream API processes collections functionally.
Introduced in Java 8.
Supports filter, map, reduce.
Improves readability.
Used in data pipelines.

Example

list.stream().filter(x -> x>10).forEach(System.out::println);

Tip

Streams don’t store data, they process it.


Q54. What is ConcurrentModificationException?

Explanation

Occurs when collection is modified during iteration.
Common beginner mistake.
Solved using Iterator remove.
Seen in multithreaded apps.
Understanding this is important.

Example

// modifying list during loop causes exception

Tip

Always use iterator for removal.


Q55. What is Queue?

Explanation

Queue follows FIFO principle.
Used in scheduling systems.
Supports add, poll, peek.
PriorityQueue sorts elements.
Common in messaging systems.

Example

Queue<Integer> q = new LinkedList<>();

Tip

FIFO = First In First Out.


Q56. What is Stack?

Explanation

Stack follows LIFO principle.
Used in undo operations.
Supports push and pop.
Java provides Stack class.
Also implemented via Deque.

Example

Stack<Integer> s = new Stack<>();

Tip

LIFO = Last In First Out.


Q57. What is Fail-fast vs Fail-safe?

Explanation

Fail-fast throws exception immediately.
Fail-safe works on cloned copy.
Iterator is fail-fast.
Concurrent collections are fail-safe.
Important in concurrency.

Example

CopyOnWriteArrayList list = new CopyOnWriteArrayList();

Tip

Fail-safe doesn’t throw ConcurrentModificationException.


Q58. What is TreeMap?

Explanation

TreeMap stores sorted key-value pairs.
Uses Red-Black tree.
Does not allow null key.
Used when sorted data needed.
Slower than HashMap.

Example

TreeMap<Integer,String> tm = new TreeMap<>();

Tip

TreeMap maintains natural ordering.


Q59. What is Collections utility class?

Explanation

Provides static helper methods.
Used for sorting and reversing.
Improves productivity.
Works with all collections.
Part of java.util.

Example

Collections.sort(list);

Tip

Collections ≠ Collection.


Q60. Real-world use of Collections?

Explanation

Used in user lists, cart systems, caching.
Backend APIs depend heavily on maps and lists.
Streams help filter records.
Queues manage requests.
Collections power microservices.

Example

List<User> users = new ArrayList<>();

Tip

Say: Collections are backbone of Java backend.

SECTION 4 – Multithreading & Concurrency in Java (Q61–Q80)


Q61. What is Multithreading in Java?

Explanation

Multithreading allows multiple threads to run concurrently inside a single program.
Each thread performs a separate task, improving application performance.
Java supports multithreading using the Thread class and Runnable interface.
It is heavily used in backend servers, APIs, and real-time systems.
Multithreading maximizes CPU utilization.

Example

class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } MyThread t = new MyThread(); t.start();

Tip

Say: Multithreading improves performance and responsiveness.


Q62. What is a Thread?

Explanation

A thread is a lightweight sub-process.
It shares memory with other threads in same process.
Threads execute independently.
They are cheaper than processes.
Used for parallel tasks.

Example

Thread t = new Thread(); t.start();

Tip

Thread = smallest unit of execution.


Q63. Difference between Process and Thread?

Explanation

Process has separate memory.
Threads share memory.
Processes are heavier.
Threads are lightweight.
Thread communication is faster.

Example

// Threads run inside same JVM process

Tip

Threads share heap memory.


Q64. Ways to create Thread?

Explanation

Extend Thread class.
Implement Runnable interface.
Use ExecutorService.
Runnable is preferred for scalability.
Executors used in enterprise apps.

Example

Runnable r = () -> System.out.println("Running"); new Thread(r).start();

Tip

Runnable > Thread.


Q65. What is Runnable?

Explanation

Runnable represents task logic.
It separates job from thread.
Allows multiple inheritance.
Preferred in production systems.
Cleaner design.

Example

class Job implements Runnable { public void run() { System.out.println("Task"); } }

Tip

Runnable promotes loose coupling.


Q66. What is Thread Lifecycle?

Explanation

New → Runnable → Running → Waiting → Terminated.
Thread moves through multiple states.
Managed by JVM scheduler.
Understanding lifecycle prevents bugs.
Interview favorite.

Example

Thread.State

Tip

Mention all five states.


Q67. What is Synchronization?

Explanation

Synchronization prevents data inconsistency.
Allows only one thread to access resource.
Used in shared memory.
Avoids race condition.
Crucial for banking systems.

Example

synchronized void display() { System.out.println("Safe"); }

Tip

Synchronization avoids race conditions.


Q68. What is Deadlock?

Explanation

Deadlock happens when threads wait forever.
Occurs due to circular dependency.
System freezes.
Hard to debug.
Must be avoided.

Example

// Thread A locks X, Thread B locks Y

Tip

Always follow lock ordering.


Q69. What is Volatile?

Explanation

Ensures visibility across threads.
Prevents caching issues.
Used for flags.
Does not guarantee atomicity.
Lightweight synchronization.

Example

volatile boolean running = true;

Tip

Volatile ensures visibility, not locking.


Q70. What is ExecutorService?

Explanation

Manages thread pool.
Improves performance.
Avoids manual thread creation.
Enterprise standard.
Supports task scheduling.

Example

ExecutorService ex = Executors.newFixedThreadPool(5); ex.submit(() -> System.out.println("Task"));

Tip

Always shutdown executor.


Q71. What is Callable?

Explanation

Callable returns result.
Runnable does not.
Supports exception.
Used with Future.
Powerful async programming.

Example

Callable<Integer> c = () -> 10;

Tip

Callable + Future.


Q72. What is Future?

Explanation

Future represents async result.
Blocks until value available.
Used with Executor.
Important for microservices.
Supports cancellation.

Example

Future<Integer> f = ex.submit(c);

Tip

Future.get() blocks.


Q73. What is Thread Pool?

Explanation

Reuses threads.
Reduces creation overhead.
Improves scalability.
Used in servers.
Provided by Executors.

Example

Executors.newFixedThreadPool(3);

Tip

Thread pool avoids resource exhaustion.


Q74. What is CountDownLatch?

Explanation

Synchronizes multiple threads.
Waits until count reaches zero.
Used in startup systems.
Part of java.util.concurrent.
Advanced interview topic.

Example

CountDownLatch latch = new CountDownLatch(2);

Tip

Latch is one-time use.


Q75. What is Semaphore?

Explanation

Controls access to resource.
Allows limited threads.
Used in connection pools.
Advanced concurrency tool.
Improves throughput.

Example

Semaphore s = new Semaphore(2);

Tip

Semaphore manages permits.


Q76. What is ReentrantLock?

Explanation

Advanced locking mechanism.
More flexible than synchronized.
Supports fairness.
Interruptible lock.
Used in high-performance apps.

Example

Lock lock = new ReentrantLock();

Tip

Provides tryLock.


Q77. What is ConcurrentHashMap?

Explanation

Thread-safe Map.
High performance.
Segmented locking.
Used in caching.
Replaces Hashtable.

Example

ConcurrentHashMap map = new ConcurrentHashMap();

Tip

Preferred over Hashtable.


Q78. What is Atomic class?

Explanation

Provides lock-free thread safety.
Uses CAS operations.
Used for counters.
Fast.
Part of java.util.concurrent.atomic.

Example

AtomicInteger ai = new AtomicInteger(0);

Tip

Atomic avoids synchronization.


Q79. What is Race Condition?

Explanation

Occurs when multiple threads modify same data.
Results unpredictable output.
Hard to debug.
Solved via synchronization.
Common interview question.

Example

// Two threads increment same variable

Tip

Race condition = timing issue.


Q80. Real-world Multithreading usage?

Explanation

Used in APIs, microservices, gaming engines.
Background jobs run async.
Payment processing uses threads.
File uploads are parallelized.
Concurrency improves UX.

Example

ExecutorService pool = Executors.newCachedThreadPool();

Tip

Mention web servers use thread pools.

SECTION 5 – JVM, Memory Management & Performance (Q81–Q100)


Q81. What is JVM?

Explanation

JVM (Java Virtual Machine) executes Java bytecode.
It converts bytecode into machine code.
JVM provides platform independence.
It manages memory and garbage collection.
Every Java application runs inside JVM.

Example

public class Main { public static void main(String[] args){ System.out.println("Runs on JVM"); } }

Tip

Say: JVM = runtime engine.


Q82. JVM Architecture?

Explanation

JVM has Class Loader, Memory Areas, Execution Engine.
Class Loader loads .class files.
Memory areas store data.
Execution engine runs instructions.
Garbage Collector cleans memory.

Example

// conceptual

Tip

Mention: ClassLoader + Heap + Stack + GC.


Q83. What is Heap Memory?

Explanation

Heap stores objects.
Shared across threads.
Garbage collected automatically.
Largest memory area.
Used heavily in backend systems.

Example

User u = new User();

Tip

Objects go to heap.


Q84. What is Stack Memory?

Explanation

Stack stores method calls and local variables.
Each thread has its own stack.
Fast access.
Automatically freed.
Overflow causes StackOverflowError.

Example

int x = 5;

Tip

Local variables live in stack.


Q85. Difference between Heap and Stack?

Explanation

Heap stores objects.
Stack stores methods.
Heap is shared.
Stack is thread-specific.
Heap is slower.

Example

String s = "Hello";

Tip

Heap = objects, Stack = execution.


Q86. What is Garbage Collection?

Explanation

GC removes unused objects.
Frees memory automatically.
Runs in background.
Prevents memory leaks.
Handled by JVM.

Example

obj = null;

Tip

GC cannot be forced.


Q87. Types of Garbage Collectors?

Explanation

Serial GC – small apps.
Parallel GC – throughput.
CMS – low latency.
G1 – modern default.
ZGC – ultra low latency.

Example

-XX:+UseG1GC

Tip

G1 GC is default.


Q88. What is Memory Leak?

Explanation

Unused objects remain referenced.
GC cannot clean them.
Memory increases.
App slows down.
Caused by static references.

Example

static List list = new ArrayList();

Tip

Always clear collections.


Q89. What is OutOfMemoryError?

Explanation

Heap becomes full.
Objects cannot be created.
Application crashes.
Caused by leaks or heavy load.
Solved by tuning JVM.

Example

-Xmx512m

Tip

Increase heap size.


Q90. What is ClassLoader?

Explanation

Loads Java classes.
Bootstrap loads core libs.
Extension loads extensions.
Application loads user classes.
Part of JVM.

Example

ClassLoader cl = Main.class.getClassLoader();

Tip

Three class loaders.


Q91. What is JIT Compiler?

Explanation

Just-In-Time compiler.
Converts bytecode to native code.
Improves performance.
Part of JVM execution engine.
Runs hot code faster.

Example

// automatic

Tip

JIT improves speed.


Q92. What is PermGen / Metaspace?

Explanation

Old Java used PermGen.
Java 8 replaced with Metaspace.
Stores class metadata.
Grows dynamically.
Prevents class loader leaks.

Example

-XX:MaxMetaspaceSize

Tip

Java 8 removed PermGen.


Q93. What is Profiling?

Explanation

Analyzes memory and CPU.
Finds bottlenecks.
Used in production.
Tools: JVisualVM, JProfiler.
Improves performance.

Example

jvisualvm

Tip

Profiling finds leaks.


Q94. What is JVM Tuning?

Explanation

Adjusting heap size.
Changing GC type.
Optimizing thread stacks.
Improves speed.
Critical in enterprise.

Example

-Xms512m -Xmx1g

Tip

Initial heap = max heap.


Q95. What is Warm-up Phase?

Explanation

JVM optimizes code after start.
JIT compiles hot paths.
Performance improves over time.
Important in benchmarks.
Microservices affected.

Example

// warmup runs

Tip

Never benchmark cold JVM.


Q96. What is Escape Analysis?

Explanation

Determines object scope.
Moves objects to stack.
Improves performance.
Automatic optimization.
Java 8+ feature.

Example

// handled internally

Tip

Reduces heap allocation.


Q97. What is Native Memory?

Explanation

Memory outside heap.
Used by JVM internals.
Direct buffers.
Can cause leaks.
Hard to monitor.

Example

ByteBuffer.allocateDirect(1024);

Tip

Native memory ≠ heap.


Q98. What is Soft/Weak Reference?

Explanation

Special reference types.
Soft cleared under pressure.
Weak cleared immediately.
Used in caches.
Advanced memory management.

Example

WeakReference obj = new WeakReference(new User());

Tip

Used in caching.


Q99. What tools monitor JVM?

Explanation

JConsole.
VisualVM.
JProfiler.
Flight Recorder.
Used in production debugging.

Example

jconsole

Tip

Monitoring prevents outages.


Q100. How Java achieves high performance?

Explanation

JIT compilation.
Garbage collection.
Thread pools.
Escape analysis.
Modern JVM optimizations.

Example

ExecutorService pool = Executors.newFixedThreadPool(5);

Tip

Say: JVM optimizes dynamically.

Scroll to Top