Java Fundamentals

***1. Why is Java platform independent?

Java is called platform independent because Java code can run on any operating system without recompilation.

How it works:

  1. Java source code (.java) is compiled into bytecode (.class).
  2. Bytecode is not machine-specific.
  3. The JVM (Java Virtual Machine) converts bytecode into machine code for the specific OS.

This follows the principle:

“Write Once, Run Anywhere (WORA)”

Example:

A Java program compiled on Windows can run on:

  • Linux
  • macOS
  • Unix

as long as a JVM is installed.

Important Interview Point:

Java is platform independent because of the JVM and bytecode, not because of the compiler.


***2. What are the main features of Java?

Java provides many powerful features that make it popular.

Main Features of Java

1. Platform Independent

Runs on any OS using JVM.

2. Object-Oriented

Everything is based on classes and objects.

3. Simple

Easy syntax compared to C++.
Removes complex concepts like:

  • Pointer arithmetic
  • Multiple inheritance using classes

4. Secure

Java provides:

  • Bytecode verification
  • Security manager
  • No direct memory access

5. Robust

Strong memory management and exception handling.

6. Multithreaded

Supports concurrent execution using threads.

7. High Performance

JIT compiler improves execution speed.

8. Distributed

Supports distributed applications using:

  • RMI
  • Web services
  • Networking APIs

9. Dynamic

Classes can be loaded dynamically during runtime.

10. Automatic Garbage Collection

Unused memory is automatically cleaned.

Important Interview Point:

Interviewers often ask:

“Which feature of Java makes it secure?”

Answer:

  • No pointers
  • Bytecode verification
  • JVM sandbox environment

***3. What is JVM?

JVM stands for Java Virtual Machine.

It is a virtual environment that executes Java bytecode.

Responsibilities of JVM

  • Loads class files
  • Verifies bytecode
  • Executes code
  • Manages memory
  • Performs garbage collection

JVM Architecture Components

  • Class Loader
  • Method Area
  • Heap Memory
  • Stack Memory
  • Execution Engine
  • Garbage Collector

Important Interview Point:

JVM is platform dependent, while Java is platform independent.

Different OS have different JVM implementations.


***4. What is JRE?

JRE stands for Java Runtime Environment.

It provides everything required to run Java applications.

JRE Contains

  • JVM
  • Core libraries
  • Supporting files

JRE does NOT contain:

  • Java compiler (javac)

Usage:

Used only for running Java programs.

Formula:

JRE = JVM + Libraries

***5. What is JDK?

JDK stands for Java Development Kit.

It is used to develop, compile, and run Java applications.

JDK Contains

  • JRE
  • JVM
  • Compiler (javac)
  • Debugging tools
  • Development utilities

Formula:

JDK = JRE + Development Tools

Important Interview Point:

Developers install JDK because it includes both compiler and runtime environment.


***6. Difference between JVM, JRE, and JDK.

FeatureJVMJREJDK
Full FormJava Virtual MachineJava Runtime EnvironmentJava Development Kit
PurposeExecutes bytecodeRuns Java programsDevelops Java programs
Contains CompilerNoNoYes
Contains JVMYesYes
Used ByRuntime systemEnd usersDevelopers
Main FunctionExecutionRuntime environmentDevelopment + Execution

Relationship

JDK = JRE + Development Tools
JRE = JVM + Libraries

Interview Shortcut:

  • JVM → Executes
  • JRE → Runs
  • JDK → Develops

***7. What is JIT Compiler?

JIT stands for Just-In-Time Compiler.

It is part of the JVM that improves Java performance.

How JIT Works

Normally:

  • Bytecode is interpreted line by line.

JIT:

  • Converts frequently used bytecode into native machine code.
  • Stores compiled code for reuse.

This reduces repeated interpretation.

Benefits

  • Faster execution
  • Improved performance
  • Runtime optimization

Important Interview Point:

Without JIT, Java would be much slower because interpretation alone is slower than native execution.


**8. What is a ClassLoader?

ClassLoader is a JVM subsystem that loads .class files into memory.

Types of ClassLoaders

1. Bootstrap ClassLoader

Loads core Java classes like:

java.lang.*

2. Extension ClassLoader

Loads extension libraries.

3. Application ClassLoader

Loads application classes from classpath.

Class Loading Process

  1. Loading
  2. Linking
  3. Initialization

Important Interview Point:

Java uses dynamic class loading, meaning classes are loaded only when required.


***9. Explain public static void main(String args[]).

This is the entry point of a Java application.

public static void main(String args[])

Explanation of Each Keyword

public

Accessible from anywhere.
JVM must access it.

static

Can be called without creating an object.

void

Returns nothing.

main

Special method name recognized by JVM.

String args[]

Stores command-line arguments.

Example

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

Important Interview Point:

JVM starts program execution from the main() method.


***10. Why is the main method static in Java?

The main() method is static because JVM calls it directly without creating an object.

Reason

If main() were non-static:

  • JVM would first need to create an object.
  • Object creation itself may depend on code execution.

To avoid this dependency, Java keeps main() static.

Example

public static void main(String args[])

JVM can directly call:

ClassName.main();

Important Interview Point:

Static methods belong to the class, not objects.


**11. Can the main method be overloaded?

Yes, the main() method can be overloaded.

Example

class Test {

public static void main(String[] args) {
System.out.println("Original main");
}

public static void main(int a) {
System.out.println(a);
}
}

Important Point

JVM always calls:

public static void main(String[] args)

Other overloaded versions are called manually.

Interview Trap

Overloading is allowed.
Overriding static methods is not true runtime polymorphism.


**12. What happens if the main method is not static?

If main() is not static, the program compiles but JVM cannot execute it properly.

Example

public void main(String[] args)

Runtime Error

Error: Main method is not static

Reason

JVM calls main() without creating an object.

Non-static methods require object creation.

Important Interview Point:

main() must always be:

public static void main(String[] args)

*13. What are packages in Java?

Packages are used to organize related classes and interfaces.

They help avoid naming conflicts and improve code management.

Types of Packages

1. Built-in Packages

Provided by Java.

Examples:

java.lang
java.util
java.io

2. User-Defined Packages

Created by developers.

Example

package mypackage;

public class Test {
public void display() {
System.out.println("Hello");
}
}

Advantages

  • Better organization
  • Avoid class name conflicts
  • Access protection
  • Reusability

Important Interview Point:

java.lang package is imported automatically by Java.

*14. Advantages of Packages in Java

Packages in Java are used to organize related classes and interfaces into a structured namespace.

Advantages of Packages

1. Avoids Naming Conflicts

Two classes can have the same name if they belong to different packages.

Example

java.util.Date
java.sql.Date

2. Better Code Organization

Packages help organize large projects into modules.

Example:

com.company.service
com.company.model
com.company.controller

3. Provides Access Protection

Packages work with access modifiers like:

  • protected
  • default

to control visibility.


4. Improves Code Reusability

Reusable classes can be grouped into packages and imported where needed.


5. Easier Maintenance

Structured code is easier to:

  • debug
  • test
  • maintain

6. Supports Modular Development

Different teams can work on separate packages independently.


Important Interview Point:

Java follows a hierarchical package structure using dot notation.

Example:

java.util.Scanner

Data Types & Variables

***15. Difference between primitive and non-primitive data types

Primitive Data Types

Primitive types store actual values directly.

Types

byte, short, int, long,
float, double,
char, boolean

Example

int x = 10;

Non-Primitive Data Types

Non-primitive types store references to objects.

Examples

  • String
  • Array
  • Class
  • Interface

Example

String name = "Java";

Difference Table

FeaturePrimitiveNon-Primitive
StoresActual valueReference/address
Memory SizeFixedVariable
Null AllowedNoYes
Default ValueDepends on typenull
Object SupportNoYes
Methods AvailableNoYes

Important Interview Point:

String is non-primitive in Java even though it behaves like a basic type.


***16. Difference between instance variable, local variable, and class variable

1. Instance Variable

Declared inside class but outside methods.

Each object gets its own copy.

Example

class Test {
int x = 10;
}

Features

  • Belongs to object
  • Stored in heap memory
  • Has default values

2. Local Variable

Declared inside methods or blocks.

Example

void show() {
int a = 5;
}

Features

  • Scope limited to method/block
  • No default value
  • Stored in stack memory

3. Class Variable (Static Variable)

Declared using static.

Shared among all objects.

Example

class Test {
static int count = 0;
}

Features

  • Single copy shared by all objects
  • Memory allocated once

Difference Table

FeatureInstance VariableLocal VariableClass Variable
DeclaredInside classInside methodInside class with static
ScopeObject levelMethod/blockClass level
MemoryHeapStackMethod Area
Default ValueYesNoYes
SharedNoNoYes

Important Interview Point:

Static variables are initialized only once during class loading.


***17. What are static variables?

Static variables are class-level variables shared among all objects of a class.

They are declared using the static keyword.

Example

class Employee {

static String company = "Google";

int id;
}

All objects share the same company variable.


Features of Static Variables

  • Belong to class, not object
  • Memory allocated once
  • Shared across all instances
  • Accessed using class name

Example

Employee.company

Use Cases

  • Counters
  • Constants
  • Shared configuration values

Important Interview Point:

Changing a static variable affects all objects.


**18. Default values of variables in Java

Java assigns default values only to:

  • instance variables
  • static variables

Local variables do NOT get default values.


Default Values Table

Data TypeDefault Value
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
booleanfalse
Object Referencenull

Example

class Test {
int x;
boolean flag;

public static void main(String[] args) {
Test t = new Test();

System.out.println(t.x);
System.out.println(t.flag);
}
}

Output:

0
false

Important Interview Point:

Using an uninitialized local variable causes a compile-time error.


**19. What is type casting?

Type casting means converting one data type into another.


Types of Type Casting

1. Widening Casting (Implicit)

Small type → Large type

Automatically done by Java.

Example

int a = 10;
double b = a;

2. Narrowing Casting (Explicit)

Large type → Small type

Must be done manually.

Example

double x = 10.5;
int y = (int)x;

Important Interview Point:

Narrowing may cause:

  • data loss
  • precision loss

*20. Explain widening and narrowing conversion

Widening Conversion

Converting smaller data type into larger data type.

Example

int a = 100;
long b = a;

Features

  • Automatic
  • Safe conversion
  • No data loss

Widening Order

byte → short → int → long → float → double

Narrowing Conversion

Converting larger data type into smaller data type.

Example

double x = 10.9;
int y = (int)x;

Output:

10

Features

  • Manual conversion required
  • Possible data loss

Difference Table

FeatureWideningNarrowing
ConversionSmall → LargeLarge → Small
AutomaticYesNo
Data LossNoPossible
Casting RequiredNoYes

Important Interview Point:

Interviewers often ask:

“Why is narrowing unsafe?”

Because data may be truncated or overflow may occur.


*21. What are wrapper classes?

Wrapper classes convert primitive data types into objects.

Each primitive type has a corresponding wrapper class.


Primitive to Wrapper Mapping

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Example

int x = 10;

Integer obj = Integer.valueOf(x);

Why Wrapper Classes Exist

Java collections work only with objects.

Example:

ArrayList<Integer>

Important Interview Point:

Wrapper classes are immutable in Java.


**22. Why do we need wrapper classes?

Wrapper classes are needed because many Java APIs and collections work only with objects, not primitive types.


Reasons for Using Wrapper Classes

1. Collections Framework Requires Objects

Example

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

Primitive types like int cannot be directly stored.


2. Utility Methods

Wrapper classes provide useful methods.

Example

Integer.parseInt("100")

3. Supports Null Values

Primitive types cannot store null.

Wrapper objects can.


4. Required in Generics

Generics work only with objects.

Example

List<Double>

5. Object-Oriented Features

Primitive types are not objects.

Wrapper classes allow:

  • method calls
  • object behavior

Important Interview Point:

Autoboxing automatically converts primitive types into wrapper objects.


*23. What is autoboxing and unboxing?

Autoboxing

Automatic conversion of primitive type into wrapper object.

Example

int x = 10;

Integer obj = x;

Java internally does:

Integer.valueOf(x)

Unboxing

Automatic conversion of wrapper object into primitive type.

Example

Integer obj = 20;

int x = obj;

Java internally does:

obj.intValue()

Example Program

class Test {
public static void main(String[] args) {

Integer a = 100; // Autoboxing

int b = a; // Unboxing

System.out.println(b);
}
}

Advantages

  • Cleaner code
  • Simplifies collection usage
  • Reduces manual conversions

Important Interview Point:

Autoboxing may create extra objects and impact performance in large loops.

Operators & Control Statements

Classes & Objects

***30. What is OOPs?

OOPs stands for:

Object-Oriented Programming System

It is a programming approach based on:

  • classes
  • objects

OOPs helps organize code using real-world entities.


Main Idea of OOPs

Instead of writing functions separately, OOPs combines:

  • data
  • methods

into a single unit called an object.


Example

class Car {

String color;

void start() {
System.out.println("Car Started");
}
}

Here:

  • Car → class
  • color → data
  • start() → behavior

Advantages of OOPs

  • Code reusability
  • Better security
  • Easy maintenance
  • Modularity
  • Scalability

Important Interview Point:

Java is called a purely object-oriented inspired language, but not fully pure because it supports primitive data types.


***31. What are the four pillars of OOPs?

The four pillars of OOPs are:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

1. Encapsulation

Binding data and methods together into a single unit.


2. Inheritance

Acquiring properties of one class into another class.


3. Polymorphism

One method behaving differently in different situations.


4. Abstraction

Hiding implementation details and showing only functionality.


Important Interview Point:

These four pillars make Java:

  • reusable
  • maintainable
  • secure

***32. What is a class and object?

Class

A class is a blueprint or template for creating objects.

It defines:

  • properties
  • behaviors

Example

class Student {

int id;
String name;

void display() {
System.out.println(name);
}
}

Object

An object is an instance of a class.

Memory is allocated only when an object is created.


Example

Student s1 = new Student();

Here:

  • Student → class
  • s1 → object

Real-Life Example

Real WorldJava
Car DesignClass
Actual CarObject

Important Interview Point:

A class does not consume memory until an object is created.


***33. What is encapsulation?

Encapsulation means wrapping:

  • data
  • methods

into a single unit.

It also means:

Data Hiding

How Encapsulation is Achieved

Using:

  • private variables
  • public getter/setter methods

Example

class Employee {

private int salary;

public void setSalary(int salary) {
this.salary = salary;
}

public int getSalary() {
return salary;
}
}

Advantages

  • Data security
  • Controlled access
  • Better maintainability

Important Interview Point:

Encapsulation is achieved using:

Access Modifiers

***34. What is inheritance?

Inheritance allows one class to acquire properties and methods of another class.

It promotes:

Code Reusability

Syntax

class Child extends Parent

Example

class Animal {

void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {

void bark() {
System.out.println("Barking");
}
}

Types of Inheritance in Java

Supported

  • Single
  • Multilevel
  • Hierarchical

Not Supported using Classes

  • Multiple inheritance

Java achieves multiple inheritance using interfaces.


Important Interview Point:

Inheritance represents:

IS-A Relationship

Example:

Dog IS-A Animal

***35. What is polymorphism?

Polymorphism means:

One name, many forms

The same method behaves differently depending on context.


Types of Polymorphism

1. Compile-Time Polymorphism

Achieved using:

Method Overloading

2. Runtime Polymorphism

Achieved using:

Method Overriding

Example

class Animal {

void sound() {
System.out.println("Animal Sound");
}
}

class Dog extends Animal {

void sound() {
System.out.println("Bark");
}
}

Advantages

  • Flexibility
  • Extensibility
  • Dynamic behavior

Important Interview Point:

Runtime polymorphism is achieved using:

Dynamic Method Dispatch

***36. What is abstraction?

Abstraction means hiding implementation details and showing only essential functionality.


Real-Life Example

When driving a car:

  • You use steering and brakes
  • Internal engine details are hidden

How Abstraction is Achieved in Java

Using:

  • abstract classes
  • interfaces

Example

abstract class Shape {

abstract void draw();
}

Advantages

  • Reduces complexity
  • Improves security
  • Focuses on essential features

Important Interview Point:

Abstraction focuses on:

What an object does

not:

How it does it

**37. Difference between abstraction and encapsulation

FeatureAbstractionEncapsulation
PurposeHides implementationHides data
FocusWhat to showHow to protect
Achieved UsingAbstract class/interfaceAccess modifiers
LevelDesign levelImplementation level

Example

Abstraction

ATM machine shows only required operations.

Encapsulation

Bank account balance is protected using private variables.


Important Interview Point:

  • Abstraction → hides complexity
  • Encapsulation → hides data

**38. Difference between method overloading and method overriding

Method Overloading

Same method name with different parameters in the same class.


Example

class Test {

void add(int a, int b) {}

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

Method Overriding

Child class provides a new implementation of parent method.


Example

class Animal {

void sound() {
System.out.println("Animal");
}
}

class Dog extends Animal {

void sound() {
System.out.println("Bark");
}
}

Difference Table

FeatureOverloadingOverriding
Occurs InSame classParent-child class
ParametersMust differMust be same
Return TypeMay differSame/covariant
Polymorphism TypeCompile-timeRuntime

Important Interview Point:

Overloading increases readability, while overriding enables runtime polymorphism.


***39. What is constructor?

A constructor is a special method used to initialize objects.


Features

  • Same name as class
  • No return type
  • Automatically called during object creation

Example

class Student {

Student() {
System.out.println("Constructor Called");
}
}

Object Creation

Student s = new Student();

Important Interview Point:

Constructors are invoked automatically when an object is created.


***40. Types of constructors in Java

1. Default Constructor

Constructor provided by compiler if no constructor exists.


Example

class Test {
}

Compiler creates default constructor internally.


2. No-Argument Constructor

Created explicitly without parameters.


Example

class Test {

Test() {
System.out.println("Hello");
}
}

3. Parameterized Constructor

Accepts parameters.


Example

class Student {

int id;

Student(int id) {
this.id = id;
}
}

Important Interview Point:

If you create any constructor manually, Java does not provide a default constructor automatically.


**41. What is constructor overloading?

Constructor overloading means multiple constructors with different parameter lists in the same class.


Example

class Student {

Student() {}

Student(int id) {}

Student(int id, String name) {}
}

Advantages

  • Multiple ways to initialize objects
  • Improves flexibility

Important Interview Point:

Constructor overloading supports compile-time polymorphism.


**42. What is a copy constructor?

A copy constructor creates a new object using values from another object.

Java does not provide built-in copy constructors like C++.

Programmers create them manually.


Example

class Student {

int id;

Student(int id) {
this.id = id;
}

Student(Student s) {
this.id = s.id;
}
}

Usage

Student s1 = new Student(101);

Student s2 = new Student(s1);

Important Interview Point:

Copy constructors help create duplicate objects safely.


**43. What is the this keyword?

this refers to the current object of the class.


Uses of this

1. Refer Current Object Variables

this.id = id;

2. Call Current Class Methods

this.display();

3. Invoke Constructor

this(10);

Example

class Student {

int id;

Student(int id) {
this.id = id;
}
}

Important Interview Point:

this resolves naming conflicts between local and instance variables.


***44. What is the super keyword?

super refers to the immediate parent class object.


Uses of super

1. Access Parent Variables

super.x;

2. Call Parent Methods

super.display();

3. Call Parent Constructor

super();

Example

class Animal {

void sound() {
System.out.println("Animal Sound");
}
}

class Dog extends Animal {

void sound() {
super.sound();
System.out.println("Dog Bark");
}
}

Important Interview Point:

super() must be the first statement inside a constructor.


**45. Can constructors be inherited?

No, constructors cannot be inherited in Java.


Reason

Constructors belong to the class itself, not to child classes.

However, child constructors can call parent constructors using:

super()

Example

class Parent {

Parent() {
System.out.println("Parent Constructor");
}
}

class Child extends Parent {

Child() {
super();
}
}

Important Interview Point:

Methods are inherited, constructors are not.


**46. What is runtime polymorphism?

Runtime polymorphism occurs when method execution is decided during runtime.

Achieved using:

Method Overriding

Example

class Animal {

void sound() {
System.out.println("Animal");
}
}

class Dog extends Animal {

void sound() {
System.out.println("Bark");
}
}

Runtime Decision

Animal a = new Dog();

a.sound();

Output:

Bark

JVM decides method at runtime.


Important Interview Point:

Runtime polymorphism is also called:

Dynamic Method Dispatch

**47. What is compile-time polymorphism?

Compile-time polymorphism occurs when method calls are resolved during compilation.

Achieved using:

Method Overloading

Example

class MathOperation {

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

int add(int a, int b, int c) {
return a + b + c;
}
}

Compiler decides which method to call based on parameters.


Advantages

  • Faster execution
  • Improved readability

Important Interview Point:

Compile-time polymorphism is also called:

Static Polymorphism

Strings in Java

***48. What is String Pool in Java?

String Pool is a special memory area inside the heap where Java stores string literals.

It is also called:

String Constant Pool (SCP)

Why String Pool Exists

To optimize memory usage by reusing string objects.


Example

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

Both s1 and s2 point to the same object in the String Pool.


Memory Behavior

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

Here:

  • "Java" literal goes to String Pool
  • new String("Java") creates a new object in heap memory

Advantages of String Pool

  • Saves memory
  • Improves performance
  • Avoids duplicate objects

Important Interview Point:

String literals are stored in the pool automatically, but objects created using new are stored separately in heap memory.


***49. Difference between String, StringBuffer, and StringBuilder

All three are used to handle text in Java, but they differ in mutability and thread safety.


1. String

String objects are immutable.

Any modification creates a new object.


Example

String s = "Java";

s.concat(" Programming");

Original string remains unchanged.


2. StringBuffer

StringBuffer is mutable and thread-safe.


Example

StringBuffer sb = new StringBuffer("Java");

sb.append(" Programming");

3. StringBuilder

StringBuilder is mutable but not thread-safe.

Faster than StringBuffer.


Example

StringBuilder sb = new StringBuilder("Java");

sb.append(" Programming");

Difference Table

FeatureStringStringBufferStringBuilder
MutableNoYesYes
Thread SafeYesYesNo
PerformanceSlowModerateFast
Memory UsageMoreLessLess
Introduced InJava 1.0Java 1.0Java 1.5

When to Use

SituationRecommended
Constant textString
Multithreaded modificationsStringBuffer
Single-threaded modificationsStringBuilder

Important Interview Point:

StringBuilder is preferred in most modern applications because it is faster than StringBuffer.


***50. Why are Strings immutable in Java?

String objects cannot be changed after creation.


Example

String s = "Java";

s.concat(" World");

A new object is created instead of modifying the original string.


Reasons Why Strings are Immutable

1. Security

Strings are widely used in:

  • database URLs
  • file paths
  • network connections

Immutability prevents accidental modification.


2. String Pool Optimization

Immutable strings can be safely shared in the String Pool.


3. Thread Safety

Immutable objects are naturally thread-safe.


4. HashCode Caching

Strings are used as keys in:

HashMap

Immutability ensures hashcode remains consistent.


Important Interview Point:

If strings were mutable, String Pool sharing would become unsafe.


**51. Difference between creating String using literal and new keyword

Using String Literal

Example

String s1 = "Java";

Behavior

  • Stored in String Pool
  • Reuses existing object if value already exists

Using new Keyword

Example

String s2 = new String("Java");

Behavior

  • Creates new object in heap memory
  • Always creates a separate object

Difference Table

FeatureString Literalnew String()
Memory LocationString PoolHeap
Object ReuseYesNo
Memory EfficientYesLess
Object CreationOnly if not existsAlways

Example

String a = "Java";
String b = "Java";

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

Output:

true

Because both references point to same pooled object.


Important Interview Point:

Using literals is more memory efficient than using new String().


**52. Why is StringBuffer mutable?

StringBuffer is mutable to allow efficient modification of strings without creating new objects repeatedly.


Example

StringBuffer sb = new StringBuffer("Java");

sb.append(" Programming");

The same object gets modified.


Why Mutability is Important

If strings were modified using immutable String:

  • multiple objects would be created
  • memory usage would increase
  • performance would decrease

Advantages of Mutable StringBuffer

  • Better performance
  • Lower memory consumption
  • Efficient concatenation

Internal Working

StringBuffer maintains a resizable character array internally.


Important Interview Point:

StringBuffer methods are synchronized, making it thread-safe.


*53. How can you reverse a string in Java?

There are multiple ways to reverse a string.


Method 1: Using StringBuilder

Example

String str = "Java";

String reversed = new StringBuilder(str)
.reverse()
.toString();

System.out.println(reversed);

Output:

avaJ

Method 2: Using Loop

Example

String str = "Java";

String rev = "";

for(int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}

System.out.println(rev);

Method 3: Using Character Array

Example

char[] arr = str.toCharArray();

Reverse manually using swapping.


Best Approach

StringBuilder.reverse()

because it is optimized and easy to read.


Important Interview Point:

Using + inside loops is inefficient because it creates multiple String objects.


*54. Why is char array preferred for passwords over String?

char[] is preferred for passwords because it provides better security than String.


Problem with String Passwords

Strings are immutable.

Once created:

  • they stay in memory until garbage collected
  • cannot be modified manually

This increases security risk.


Example

String password = "admin123";

Password may remain in memory for a long time.


Advantage of char[]

Character arrays are mutable.

Password data can be cleared immediately after use.


Example

char[] password = {'a','d','m','i','n'};

After usage:

Arrays.fill(password, ' ');

Memory gets cleared.


Difference Table

FeatureStringchar[]
MutableNoYes
SecurityLess secureMore secure
Memory CleanupAutomatic onlyManual possible
Stored in String PoolPossibleNo

Important Interview Point:

Security-sensitive applications prefer char[] because passwords can be erased manually from memory.

Arrays

***55. What is an array?

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

Arrays are used to store multiple values using a single variable name.


Features of Arrays

  • Fixed size
  • Stores homogeneous data
  • Fast access using index
  • Index starts from 0

Syntax

datatype[] arrayName;

Example

int[] numbers = {10, 20, 30, 40};

Accessing Array Elements

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

Output:

10

Memory Representation

Index :  0   1   2   3
Value : 10 20 30 40

Important Interview Point:

Arrays in Java are objects stored in heap memory.


***56. Difference between array and ArrayList

Both arrays and ArrayList are used to store collections of data, but they differ in flexibility and functionality.


Array

An array has fixed size.

Example

int[] arr = new int[5];

ArrayList

ArrayList is a resizable collection class from:

java.util

Example

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

Difference Table

FeatureArrayArrayList
SizeFixedDynamic
PackageBuilt-in language featurejava.util
Data TypesPrimitive + ObjectsObjects only
PerformanceFasterSlightly slower
Memory UsageLessMore
Methods AvailableLimitedMany utility methods

Example

list.add(10);
list.remove(0);

When to Use

SituationRecommended
Fixed-size dataArray
Dynamic dataArrayList

Important Interview Point:

ArrayList internally uses arrays.


**57. Why does array indexing start from 0?

Array indexing starts from 0 because of memory address calculation efficiency.


Internal Formula

Address Calculation

Address = Base Address + (Index × Size of Element)

Example

int[] arr = {10, 20, 30};

If:

  • base address = 100
  • size of int = 4 bytes

Then:

arr[0] = 100 + (0 × 4) = 100
arr[1] = 100 + (1 × 4) = 104

Advantages of Zero-Based Indexing

  • Faster calculations
  • Simpler memory access
  • Efficient implementation

Important Interview Point:

Most programming languages use zero-based indexing for performance optimization.


**58. Types of arrays in Java

Java supports multiple types of arrays.


1. Single-Dimensional Array

Stores data in one row.


Example

int[] arr = {10, 20, 30};

2. Multidimensional Array

Array of arrays.


Example

int[][] matrix = {
{1, 2},
{3, 4}
};

3. Jagged Array

Rows contain different column sizes.


Example

int[][] arr = {
{1, 2},
{3, 4, 5},
{6}
};

Classification Based on Data Type

Primitive Arrays

int[] arr;
double[] marks;

Object Arrays

String[] names;
Student[] students;

Important Interview Point:

In Java, multidimensional arrays are internally implemented as arrays of arrays.


*59. What is a jagged array?

A jagged array is a multidimensional array where each row can have different lengths.

It is also called:

Ragged Array

Example

int[][] arr = new int[3][];

arr[0] = new int[2];
arr[1] = new int[4];
arr[2] = new int[1];

Memory Representation

Row 0 → 2 columns
Row 1 → 4 columns
Row 2 → 1 column

Advantages

  • Efficient memory usage
  • Flexible row sizes

Use Cases

  • Matrix representations
  • Dynamic table structures

Important Interview Point:

Java does not store multidimensional arrays as continuous memory blocks like C/C++.


*60. Difference between int[] arr and int arr[]

Both declarations are valid and create integer arrays.


Method 1

int[] arr;

Preferred Java style.


Method 2

int arr[];

Older C/C++ style syntax.


Difference

Featureint[] arrint arr[]
StyleJava styleC-style
ReadabilityBetterLess preferred
FunctionalitySameSame

Example

int[] a = new int[5];

int b[] = new int[5];

Both are equivalent.


Important Interview Point:

Most Java coding standards recommend:

int[] arr;

because it clearly associates array notation with the data type.


*61. Advantages and disadvantages of arrays

Advantages of Arrays

1. Fast Access

Elements can be accessed using index in:

O(1)

time complexity.


2. Easy Traversal

Arrays are simple to iterate using loops.


3. Memory Efficient

Stores elements in contiguous memory locations.


4. Supports Multiple Data Storage

Can store large amounts of similar data.


5. Better Performance

Faster than many dynamic collections.


Disadvantages of Arrays

1. Fixed Size

Size cannot be changed after creation.


2. Homogeneous Data Only

Stores same data type elements.


3. Insertion/Deletion is Costly

Requires shifting elements.


4. Memory Wastage

Unused allocated memory remains reserved.


5. No Built-in Methods

Unlike collections, arrays provide limited functionality.


Difference Summary

AdvantagesDisadvantages
Fast accessFixed size
Memory efficientCostly insertion/deletion
Simple structureLimited functionality

Important Interview Point:

Arrays are preferred when:

  • size is fixed
  • high performance is required
  • direct index access is important
Exception Handling

***62. What is exception handling?

Exception handling is a mechanism in Java used to handle runtime errors so that the normal flow of the program can continue.


What is an Exception?

An exception is an unwanted event that occurs during program execution.

Examples:

  • division by zero
  • file not found
  • invalid array index
  • null object access

Purpose of Exception Handling

  • Prevent program termination
  • Handle errors gracefully
  • Maintain normal application flow

Keywords Used

  • try
  • catch
  • finally
  • throw
  • throws

Example

class Test {

public static void main(String[] args) {

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

System.out.println("Program continues");
}
}

Output

Cannot divide by zero
Program continues

Important Interview Point:

Exception handling improves program reliability and user experience.


***63. Difference between checked and unchecked exceptions

Exceptions in Java are divided into:

  1. Checked Exceptions
  2. Unchecked Exceptions

Checked Exceptions

Checked exceptions are checked at compile time.

The compiler forces handling using:

  • try-catch
  • throws

Examples

  • IOException
  • SQLException
  • FileNotFoundException

Example

FileReader file = new FileReader("test.txt");

Compiler requires exception handling.


Unchecked Exceptions

Unchecked exceptions occur at runtime.

Compiler does not force handling.


Examples

  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException

Example

int x = 10 / 0;

Difference Table

FeatureChecked ExceptionUnchecked Exception
Checked ByCompilerJVM
Handling MandatoryYesNo
Occurs AtCompile timeRuntime
Parent ClassExceptionRuntimeException

Important Interview Point:

All unchecked exceptions are subclasses of:

RuntimeException

***64. Difference between Error and Exception

Both Error and Exception are subclasses of:

Throwable

But they represent different problems.


Exception

Exceptions are conditions that applications can handle.


Examples

  • IOException
  • NullPointerException

Error

Errors are serious system-level problems that applications usually cannot recover from.


Examples

  • OutOfMemoryError
  • StackOverflowError

Difference Table

FeatureExceptionError
RecoverableYesUsually No
Caused ByApplication issuesSystem/JVM issues
HandlingRecommendedRarely handled
TypeRuntime/Application problemCritical problem

Important Interview Point:

Errors usually indicate JVM or system failure and should not normally be caught.


***65. What is try-catch-finally?

These blocks are used for exception handling.


try Block

Contains code that may cause an exception.


catch Block

Handles the exception generated in the try block.


finally Block

Executes regardless of whether exception occurs or not.

Usually used for:

  • closing files
  • releasing resources
  • database cleanup

Example

try {

int x = 10 / 0;

}
catch(ArithmeticException e) {

System.out.println("Exception handled");

}
finally {

System.out.println("Finally block executed");
}

Output

Exception handled
Finally block executed

Important Interview Point:

finally block is mostly used for resource cleanup.


**66. Can finally block be skipped?

Normally, the finally block always executes.

However, it may be skipped in some special situations.


Cases Where finally May Not Execute

1. JVM Shutdown

System.exit(0);

2. System Crash

  • Power failure
  • JVM crash

Example

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

Output:

(No output)

Important Interview Point:

Except for abnormal JVM termination, finally almost always executes.


**67. Difference between throw and throws

Both are used in exception handling but serve different purposes.


throw Keyword

Used to explicitly throw an exception.


Example

throw new ArithmeticException("Invalid");

throws Keyword

Used in method declaration to indicate possible exceptions.


Example

void readFile() throws IOException

Difference Table

Featurethrowthrows
PurposeExplicitly throws exceptionDeclares exception
Used InMethod bodyMethod signature
Followed ByException objectException class name
Number of ExceptionsOne at a timeMultiple possible

Important Interview Point:

throw is used by programmers, while throws informs the compiler and caller about exceptions.


**68. What is exception propagation?

Exception propagation means passing an exception from one method to another until it is handled.


Flow

If a method does not handle an exception:

  • JVM passes it to the calling method
  • continues until handled

Example

class Test {

void method1() {
method2();
}

void method2() {
int x = 10 / 0;
}

public static void main(String[] args) {

try {
new Test().method1();
}
catch(Exception e) {
System.out.println("Handled");
}
}
}

Output

Handled

Important Interview Point:

Unchecked exceptions propagate automatically in Java.


*69. What is NullPointerException?

NullPointerException occurs when we try to use an object reference that points to null.


Example

String s = null;

System.out.println(s.length());

Runtime Error

NullPointerException

Common Causes

  • Calling method on null object
  • Accessing field of null object
  • Using null arrays

How to Avoid

  • Null checks
  • Proper object initialization
  • Using Optional (Java 8+)

Example

if(s != null) {
System.out.println(s.length());
}

Important Interview Point:

NullPointerException is one of the most common runtime exceptions in Java interviews and real projects.


*70. What happens if exception is not handled?

If an exception is not handled:

  1. JVM stops normal execution
  2. JVM creates exception object
  3. Stack trace is printed
  4. Program terminates abnormally

Example

class Test {

public static void main(String[] args) {

int x = 10 / 0;

System.out.println("Hello");
}
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

Hello will not print.


JVM Behavior

JVM searches for matching catch block:

  • current method
  • caller method
  • propagation chain

If not found:

Program terminates

Important Interview Point:

Unchecked exceptions may compile successfully but can crash the application at runtime if not handled properly.

Collections Basics

***71. What is Collection Framework?

The Java Collection Framework (JCF) is a set of classes and interfaces used to store and manipulate groups of objects.

It provides:

  • dynamic data structures
  • reusable algorithms
  • utility methods

Main Components of Collection Framework

1. Interfaces

Define structure and behavior.

Examples:

  • List
  • Set
  • Queue
  • Map

2. Classes

Implement collection interfaces.

Examples:

  • ArrayList
  • LinkedList
  • HashSet
  • HashMap

3. Algorithms

Utility methods provided by:

Collections

Examples:

  • sorting
  • searching
  • reversing

Hierarchy Overview

Iterable
|
Collection
├── List
├── Set
└── Queue

Map (separate hierarchy)

Advantages

  • Dynamic resizing
  • Ready-made data structures
  • Better performance
  • Reduces coding effort

Important Interview Point:

Map is part of the Collection Framework but does NOT extend the Collection interface.


***72. Difference between List, Set, and Map

These are core interfaces in Java Collections.


List

Stores ordered elements.

Features

  • Maintains insertion order
  • Allows duplicates
  • Index-based access

Example

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

Set

Stores unique elements.

Features

  • No duplicates allowed
  • No index-based access

Example

Set<Integer> set = new HashSet<>();

Map

Stores data as:

key-value pairs

Features

  • Keys are unique
  • Values may duplicate

Example

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

Difference Table

FeatureListSetMap
StoresElementsUnique elementsKey-value pairs
DuplicatesAllowedNot allowedKeys not allowed
Order MaintainedYesDepends on implementationDepends on implementation
Index AccessYesNoNo

Important Interview Point:

HashSet internally uses HashMap.


***73. Difference between ArrayList and LinkedList

Both implement the List interface but use different internal data structures.


ArrayList

Uses dynamic array internally.


Features

  • Fast random access
  • Slower insertion/deletion in middle

Example

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

LinkedList

Uses doubly linked list internally.


Features

  • Faster insertion/deletion
  • Slower random access

Example

LinkedList<Integer> list = new LinkedList<>();

Difference Table

FeatureArrayListLinkedList
Internal StructureDynamic ArrayDoubly Linked List
Access SpeedFastSlow
Insertion/DeletionSlowFast
Memory UsageLessMore
TraversalBetter cache performanceMore pointer traversal

Time Complexity

OperationArrayListLinkedList
GetO(1)O(n)
Insert/Delete MiddleO(n)O(1)

Important Interview Point:

Use:

  • ArrayList for frequent searching
  • LinkedList for frequent insertion/deletion

***74. Difference between HashMap and Hashtable

Both store key-value pairs but differ in synchronization and performance.


HashMap

  • Not synchronized
  • Faster
  • Allows one null key and multiple null values

Example

HashMap<Integer, String> map = new HashMap<>();

Hashtable

  • Synchronized
  • Slower
  • Does NOT allow null keys or values

Example

Hashtable<Integer, String> table = new Hashtable<>();

Difference Table

FeatureHashMapHashtable
SynchronizationNoYes
PerformanceFasterSlower
Null KeysAllowedNot allowed
Null ValuesAllowedNot allowed
IntroducedJava 1.2Java 1.0

Important Interview Point:

ConcurrentHashMap is preferred over Hashtable in modern multithreaded applications.


***75. Difference between HashSet and TreeSet

Both implement the Set interface but differ in storage and ordering.


HashSet

Uses hashing internally.


Features

  • Unordered
  • Faster operations
  • Allows one null value

Example

HashSet<Integer> set = new HashSet<>();

TreeSet

Uses balanced tree structure (Red-Black Tree).


Features

  • Sorted elements
  • Slower than HashSet
  • No null values

Example

TreeSet<Integer> set = new TreeSet<>();

Difference Table

FeatureHashSetTreeSet
OrderingNoSorted
Internal StructureHash TableRed-Black Tree
PerformanceFasterSlower
Null ValuesOne allowedNot allowed

Time Complexity

OperationHashSetTreeSet
Add/Search/DeleteO(1)O(log n)

Important Interview Point:

Use TreeSet when sorted data is required.


**76. Difference between Iterator and ListIterator

Both are used to traverse collections.


Iterator

Used for traversing collections in forward direction only.


Features

  • Forward traversal
  • Remove elements
  • Works with all collections

Example

Iterator<Integer> it = list.iterator();

ListIterator

Used only with List implementations.


Features

  • Forward and backward traversal
  • Add, update, remove elements

Example

ListIterator<Integer> li = list.listIterator();

Difference Table

FeatureIteratorListIterator
TraversalForward onlyBoth directions
Applicable ToAll collectionsList only
Modification SupportRemove onlyAdd, set, remove
Index InformationNoYes

Important Interview Point:

ListIterator extends Iterator.


**77. What is Comparable and Comparator?

Both are used for sorting objects in Java.


Comparable

Used for:

Natural Sorting

Implemented inside the class itself.


Method

compareTo()

Example

class Student implements Comparable<Student> {

public int compareTo(Student s) {
return this.id - s.id;
}
}

Comparator

Used for:

Custom Sorting

Implemented in separate class.


Method

compare()

Example

class NameComparator implements Comparator<Student> {

public int compare(Student a, Student b) {
return a.name.compareTo(b.name);
}
}

Difference Table

FeatureComparableComparator
Packagejava.langjava.util
MethodcompareTo()compare()
Sorting TypeNaturalCustom
Class ModificationRequiredNot required

Important Interview Point:

Use:

  • Comparable for default sorting
  • Comparator for multiple sorting logics

*78. What is Vector in Java?

Vector is a legacy dynamic array class.

It is similar to ArrayList but synchronized.


Features

  • Dynamic resizing
  • Thread-safe
  • Maintains insertion order

Example

Vector<Integer> vector = new Vector<>();

Difference from ArrayList

FeatureVectorArrayList
SynchronizationYesNo
PerformanceSlowerFaster
Legacy ClassYesNo

Important Interview Point:

Vector is rarely used in modern applications because synchronized collections reduce performance.


*79. What is Stack in Java Collections?

Stack is a class that follows:

LIFO (Last In First Out)

Operations

MethodPurpose
push()Add element
pop()Remove top element
peek()View top element

Example

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

stack.push(10);
stack.push(20);

System.out.println(stack.pop());

Output:

20

Real-Life Example

Stack of plates:

  • Last plate added is removed first.

Important Interview Point:

Deque is preferred over Stack in modern Java applications.


*80. What is Queue interface?

Queue is an interface used to store elements for processing in a specific order.

It generally follows:

FIFO (First In First Out)

Common Queue Implementations

  • LinkedList
  • PriorityQueue
  • ArrayDeque

Basic Methods

MethodPurpose
add()Insert element
offer()Insert safely
remove()Remove element
poll()Remove safely
peek()View front element

Example

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

q.add(10);
q.add(20);

System.out.println(q.poll());

Output:

10

Applications

  • Task scheduling
  • Printer queue
  • CPU scheduling
  • Messaging systems

Important Interview Point:

PriorityQueue does not follow FIFO strictly because elements are ordered by priority.

Multithreading Basics

***81. What is multithreading?

Multithreading is a process of executing multiple threads simultaneously within a single program.

A thread is the smallest unit of execution.


Why Multithreading is Used

  • Improves performance
  • Better CPU utilization
  • Executes tasks concurrently
  • Reduces response time

Real-Life Example

In a web browser:

  • One thread loads images
  • Another handles user input
  • Another plays audio/video

All tasks run simultaneously.


Example

class MyThread extends Thread {

public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {

MyThread t1 = new MyThread();

t1.start();
}
}

Advantages

  • Faster execution
  • Better resource sharing
  • Supports background tasks

Important Interview Point:

Java supports multithreading through:

  • Thread class
  • Runnable interface
  • Executor Framework

***82. Difference between process and thread

Both process and thread are execution units, but they differ in memory and resource usage.


Process

A process is an independent program in execution.

Each process has:

  • separate memory
  • separate resources

Example

  • Browser
  • VS Code
  • Media Player

Thread

A thread is a lightweight subpart of a process.

Threads share:

  • memory
  • resources

within the same process.


Example

Tabs inside browser may use multiple threads.


Difference Table

FeatureProcessThread
DefinitionIndependent programSmallest execution unit
MemorySeparateShared
Resource UsageHeavyLightweight
CommunicationSlowerFaster
Creation TimeMoreLess

Important Interview Point:

Context switching between threads is faster than between processes.


***83. Two ways to create threads in Java

There are two main ways to create threads in Java.


1. Extending Thread Class

Create a class that extends:

Thread

Override:

run()

Example

class MyThread extends Thread {

public void run() {
System.out.println("Thread running");
}

public static void main(String[] args) {

MyThread t = new MyThread();

t.start();
}
}

2. Implementing Runnable Interface

Create a class implementing:

Runnable

Example

class MyRunnable implements Runnable {

public void run() {
System.out.println("Thread running");
}

public static void main(String[] args) {

MyRunnable obj = new MyRunnable();

Thread t = new Thread(obj);

t.start();
}
}

Difference Table

FeatureThread ClassRunnable Interface
InheritanceExtends ThreadImplements Runnable
Multiple InheritanceNot possiblePossible
Better ApproachLess preferredRecommended

Important Interview Point:

Implementing Runnable is preferred because Java supports single inheritance only.


**84. What is thread lifecycle?

A thread goes through multiple states during execution.


Thread Lifecycle States

1. New State

Thread object is created but not started.


Example

Thread t = new Thread();

2. Runnable State

After calling:

start()

Thread becomes ready to run.


3. Running State

Thread scheduler selects the thread for execution.


4. Blocked/Waiting State

Thread waits for:

  • lock
  • resource
  • signal
  • sleep completion

5. Terminated State

Thread finishes execution.


Lifecycle Diagram

NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED

Important Interview Point:

Calling:

start()

creates a new thread, while:

run()

executes normally like a method call.


**85. What is daemon thread?

A daemon thread is a background thread that supports user threads.

It runs in the background and automatically terminates when all user threads finish.


Examples of Daemon Threads

  • Garbage Collector
  • Background monitoring
  • Auto-save services

How to Create Daemon Thread

Use:

setDaemon(true)

before starting the thread.


Example

class Test extends Thread {

public void run() {
System.out.println("Daemon Thread");
}

public static void main(String[] args) {

Test t = new Test();

t.setDaemon(true);

t.start();
}
}

Features

  • Low-priority background tasks
  • JVM exits when only daemon threads remain

Important Interview Point:

setDaemon(true) must be called before:

start()

otherwise:

IllegalThreadStateException

occurs.


**86. Difference between sleep() and wait()

Both sleep() and wait() pause thread execution, but they work differently.


sleep()

Defined in:

Thread class

Pauses thread for a specific time.


Example

Thread.sleep(1000);

Features of sleep()

  • Does NOT release lock
  • Time-based pause
  • Static method

wait()

Defined in:

Object class

Used for inter-thread communication.


Example

obj.wait();

Features of wait()

  • Releases lock
  • Must be used inside synchronized block
  • Waits until notified

Difference Table

Featuresleep()wait()
ClassThreadObject
Releases LockNoYes
Used ForDelayThread communication
Requires synchronizedNoYes
Wake UpAutomatically after timenotify()/notifyAll()

Important Interview Point:

wait() is part of Java synchronization mechanism, while sleep() is mainly used for delays or pauses.

**87. What are thread priorities?

Thread priority is a value assigned to a thread that indicates its importance to the thread scheduler.

The scheduler may use priority to decide which thread should execute first.


Priority Range

Java thread priorities range from:

1 to 10

Constants in Thread Class

ConstantValue
MIN_PRIORITY1
NORM_PRIORITY5
MAX_PRIORITY10

Example

class Test extends Thread {

public void run() {
System.out.println(Thread.currentThread().getPriority());
}

public static void main(String[] args) {

Test t1 = new Test();

t1.setPriority(8);

t1.start();
}
}

Important Methods

Set Priority

setPriority(int priority)

Get Priority

getPriority()

Important Points

  • Higher priority threads may get more CPU time.
  • Thread scheduling behavior depends on JVM and operating system.
  • Priority does NOT guarantee execution order.

Important Interview Point:

Thread priority is only a scheduling hint, not a strict rule.

Garbage Collection

***88. What is Garbage Collection?

Garbage Collection (GC) is an automatic memory management process in Java.

It removes unused objects from heap memory.


Purpose

To free memory occupied by unreachable objects.


Example

Student s = new Student();

s = null;

The object becomes eligible for garbage collection.


Who Performs Garbage Collection?

JVM Garbage Collector automatically performs cleanup.


Advantages

  • Automatic memory management
  • Prevents memory exhaustion
  • Reduces manual memory errors

Important Interview Point:

Java developers cannot force garbage collection, they can only request it using:

System.gc();

***89. Why is Garbage Collection needed?

Garbage Collection is needed to manage memory automatically and efficiently.


Reasons for Garbage Collection

1. Prevent Memory Leaks

Unused objects are removed automatically.


2. Avoid Manual Memory Management

Unlike C/C++, Java developers do not manually free memory.


3. Improve Application Stability

Automatic cleanup prevents memory-related crashes.


4. Better Performance

Reclaims heap space for new objects.


Without Garbage Collection

Applications may suffer from:

  • memory leaks
  • OutOfMemoryError
  • poor performance

Important Interview Point:

Garbage Collection works mainly on:

Heap Memory

**90. Difference between Heap and Stack memory

Heap and Stack are two major memory areas in Java.


Heap Memory

Used for:

  • objects
  • instance variables

Shared among threads.


Example

Student s = new Student();

Object stored in heap.


Stack Memory

Used for:

  • method calls
  • local variables
  • function execution

Each thread has its own stack.


Example

int x = 10;

Local variable stored in stack.


Difference Table

FeatureHeap MemoryStack Memory
StoresObjectsLocal variables
SharedYesNo
Memory ManagementGarbage CollectorAutomatic
Access SpeedSlowerFaster
SizeLargerSmaller

Important Interview Point:

Objects live in heap, references may live in stack.


**91. What is memory leak?

A memory leak occurs when unused objects remain in memory and are not garbage collected.

As a result:

  • memory usage keeps increasing
  • application performance decreases

Common Causes

  • Unclosed resources
  • Static collections
  • Holding unnecessary references

Example

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

while(true) {
list.add(new Object());
}

Objects remain referenced and cannot be garbage collected.


Effects of Memory Leak

  • High memory consumption
  • Slow performance
  • OutOfMemoryError

Prevention

  • Remove unused references
  • Close resources properly
  • Use weak references when needed

Important Interview Point:

Java has garbage collection, but memory leaks can still occur if references are retained unnecessarily.


*92. What makes objects eligible for garbage collection?

An object becomes eligible for garbage collection when it is no longer reachable.


Common Cases

1. Null Reference

Student s = new Student();

s = null;

2. Reassigning Reference

Student s1 = new Student();

s1 = new Student();

Old object becomes unreachable.


3. Anonymous Objects

new Student();

No reference stored.


4. Objects Inside Method

Objects become eligible after method execution if no reference exists.


5. Island of Isolation

Objects referencing each other but unreachable externally.


Example

class Test {

Test t;

public static void main(String[] args) {

Test t1 = new Test();
Test t2 = new Test();

t1.t = t2;
t2.t = t1;

t1 = null;
t2 = null;
}
}

Both objects become eligible.


Important Interview Point:

Eligibility does NOT guarantee immediate garbage collection.


Java Keywords

***93. Difference between final, finally, and finalize

These three terms are different concepts in Java.


final

Keyword used to restrict modification.


finally

Block used in exception handling.


finalize()

Method called by garbage collector before object destruction.


Difference Table

Featurefinalfinallyfinalize()
TypeKeywordBlockMethod
PurposeRestrictionCleanupGC cleanup
Used WithVariable/method/classtry-catchObject class
ExecutionCompile-time ruleAlways executesBefore GC

Important Interview Point:

finalize() is deprecated in modern Java versions because it is unreliable.


***94. Uses of final keyword in variable, method, and class

The final keyword is used to apply restrictions.


1. final Variable

Value cannot be changed.


Example

final int x = 10;

2. final Method

Cannot be overridden.


Example

final void display() {
}

3. final Class

Cannot be inherited.


Example

final class Test {
}

Real Example

String

class is final.


Summary Table

UsageRestriction
final variableValue cannot change
final methodCannot override
final classCannot inherit

Important Interview Point:

Blank final variables must be initialized inside constructor.


**95. What is static keyword?

static is used for memory management in Java.

It makes members belong to the class instead of objects.


Static Members

  • static variables
  • static methods
  • static blocks
  • static nested classes

Example

class Test {

static int count = 0;
}

Features

  • Shared among all objects
  • Memory allocated once
  • Accessed using class name

Access Example

Test.count

Important Interview Point:

Static methods cannot directly access non-static members.


**96. Can static methods be overloaded?

Yes, static methods can be overloaded.


Example

class Test {

static void show() {
System.out.println("No arguments");
}

static void show(int x) {
System.out.println(x);
}
}

Why Allowed?

Because method overloading depends on:

  • method signature
  • parameter list

not on runtime behavior.


Important Interview Point:

Static method overloading is resolved at compile time.


**97. Can static methods be overridden?

No, static methods cannot be truly overridden.

They can only be:

Method Hidden

Example

class Parent {

static void display() {
System.out.println("Parent");
}
}

class Child extends Parent {

static void display() {
System.out.println("Child");
}
}

Method Call

Parent p = new Child();

p.display();

Output:

Parent

Because static methods are resolved using reference type.


Important Interview Point:

Static methods belong to class, not objects, so runtime polymorphism does not apply.


98. What is transient keyword?

transient is used in serialization to skip variables during object serialization.


Purpose

Sensitive or unnecessary data should not be saved.


Example

class Student implements Serializable {

int id;

transient String password;
}

Serialization Result

  • id gets serialized
  • password is skipped

Use Cases

  • Passwords
  • Security tokens
  • Temporary data

Important Interview Point:

Transient variables get default values during deserialization.