[Go to site: main page, start]

0% found this document useful (0 votes)
3 views30 pages

Java Guide

Uploaded by

varunbotcha777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Java Guide

Uploaded by

varunbotcha777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Why is Java called Platform Independent?

Answer:
Java code is compiled into bytecode, which runs on the JVM (Java Virtual Machine).
Since JVM exists for di erent operating systems, the same bytecode can run anywhere.

Keyword: Write Once, Run Anywhere (WORA)

2. Di erence Between JDK, JRE, and JVM

JDK JRE JVM

Development Kit Runtime Environment Executes bytecode

Contains compiler Contains libraries Converts bytecode to machine code

Easy answer:

JDK = JRE + Development Tools


JRE = JVM + Libraries

3. Why is Java Not 100% Object-Oriented?

Because Java has primitive data types:

int
char
float
double
boolean

These are not objects.

4. What is JVM?

JVM is responsible for:

 Loading classes

 Verifying bytecode

 Memory management

 Garbage collection

 Executing Java programs

5. What is Garbage Collection?


Automatic memory cleanup performed by JVM.

Objects that are no longer referenced are removed from memory.

Questions:

 Why use Garbage Collection?

 Can we force it?

[Link]();

Request only; JVM decides.

OOP Concepts (Very Important)

6. What is a Class?

Blueprint of an object.

Example:

class Student{
}

7. What is an Object?

Instance of a class.

Student s = new Student();

8. Four Pillars of OOP

Encapsulation

Binding data and methods together.

Example:

private int salary;

Access via getters/setters.

Inheritance

Acquiring properties from another class.

class A {}
class B extends A {}

Benefits:
 Reusability

 Reduced code duplication

Polymorphism

One action, many forms.

Compile-Time Polymorphism

Method Overloading

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

Runtime Polymorphism

Method Overriding

class Animal{
void sound(){}
}

Abstraction

Showing essential details and hiding implementation.

Achieved using:

 Abstract Classes

 Interfaces

Frequently Asked Interview Question

9. Di erence Between Overloading and Overriding

Overloading Overriding

Same method name Same method name

Di erent parameters Same parameters

Compile-time Runtime

Same class Parent-child class

10. Abstract Class vs Interface


Abstract Class

 Can have abstract and concrete methods

 Supports constructors

 Supports instance variables

Interface

 Provides complete abstraction

 Supports multiple inheritance

 Variables are public static final

Modern Java interfaces can also have:

 default methods

 static methods

String Concepts

11. Di erence Between String, StringBu er, StringBuilder

String

Immutable

String s="Hello";

Cannot be modified.

StringBu er

Mutable

Thread-safe

Slower

StringBuilder

Mutable

Not thread-safe

Faster

Interview favorite:

Which is faster, StringBu er or StringBuilder?


Answer:
StringBuilder.

12. Why are Strings Immutable?

Benefits:

 Security

 Thread safety

 Hashing optimization

 String pool usage

13. What is String Pool?

Special memory area where string literals are stored.

String a="Hello";
String b="Hello";

Both point to the same object.

Constructor Concepts

14. What is a Constructor?

Special method called automatically during object creation.

Student(){
}

15. Constructor vs Method

Constructor Method

Same name as class Any name

No return type Has return type

Auto called Explicitly called

Static Keyword

16. What is Static?


Belongs to class rather than object.

static int count;

Only one copy exists.

17. Why is Main Method Static?

public static void main(String[] args)

JVM can call it without creating an object.

Exception Handling

18. What is Exception?

An abnormal condition that interrupts program execution.

Examples:

 Divide by zero

 File not found

 Null pointer

19. Di erence Between Checked and Unchecked Exception

Checked

Checked at compile time

Examples:

 IOException

 SQLException

Unchecked

Checked at runtime

Examples:

 NullPointerException

 ArithmeticException

 ArrayIndexOutOfBoundsException
20. Di erence Between throw and throws

throw

Used to explicitly throw an exception.

throw new Exception();

throws

Declares possible exceptions.

void test() throws IOException

Collections Framework

21. Di erence Between Array and ArrayList

Array ArrayList

Fixed size Dynamic size

Faster Slightly slower

Stores primitives Stores objects

22. List vs Set

List

 Ordered

 Duplicates allowed

Set

 No duplicates

23. HashMap vs HashTable

HashMap HashTable

Not synchronized Synchronized

Faster Slower

Allows null No null

24. HashMap vs TreeMap


HashMap

 No sorting

 O(1) average

TreeMap

 Sorted

 O(log n)

Multithreading

25. Process vs Thread

Process

Independent execution unit.

Thread

Lightweight subprocess.

Multiple threads can exist inside one process.

26. How to Create a Thread?

Method 1

extends Thread

Method 2

implements Runnable

Interview answer:
Runnable is preferred because Java supports single inheritance.

27. What is Synchronization?

Used to prevent multiple threads from accessing shared resources simultaneously.

Memory Management

28. Stack vs Heap Memory

Stack

Stores:
 Local variables

 Method calls

Heap

Stores:

 Objects

 Class instances

JVM Internals

1. What happens when you run a Java program?

public class Main {


public static void main(String[] args) {
[Link]("Hello");
}
}

Expected answer:

1. .java compiled by javac

2. Generates .class bytecode

3. ClassLoader loads Main class

4. Bytecode Verifier checks bytecode

5. JVM allocates memory

6. JIT compiles frequently used code

7. Execution Engine executes instructions

8. Garbage Collector manages memory

Interviewers love this question.

2. Explain JVM Memory Structure

Heap

Stores objects.

Stack

Stores:

 Local variables

 Method frames
 References

Method Area

Stores:

 Class metadata

 Static variables

 Runtime constant pool

PC Register

Tracks current instruction.

Native Method Stack

For JNI/native calls.

Question:

Which memory area causes OutOfMemoryError most frequently?

Answer:
Heap.

3. StackOverflowError vs OutOfMemoryError

StackOverflowError

void test() {
test();
}

Infinite recursion.

OutOfMemoryError

while(true){
[Link](new Object());
}

Heap exhausted.

Class Loading Deep Dive

4. Explain Class Loading Process

Three phases:

Loading
ClassLoader loads class bytecode.

Linking

 Verification

 Preparation

 Resolution

Initialization

Static variables initialized.

5. Types of Class Loaders

Bootstrap ClassLoader

Loads:

[Link].*
[Link].*

Extension ClassLoader

Loads extension libraries.

Application ClassLoader

Loads user classes.

Interview Question:

Why is String loaded before your classes?

Bootstrap ClassLoader.

String Internals

6. Why is String Immutable?

Reasons:

Security

Database URLs cannot be changed.

Thread Safety
Multiple threads can safely share strings.

HashMap Optimization

Hashcode can be cached.

String Pool

Reuse memory.

7. How does String Pool work?

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

Both point to same object.

String s3 = new String("Java");

Creates separate heap object.

Question:

String s1="Java";
String s2="Java";
[Link](s1==s2);

Output?

true

8. == vs equals()

==

Reference comparison.

equals()

Content comparison.

Most asked question.

Collections Internal Working

9. How does HashMap work internally?

This is one of the most important Java interview questions.

Steps:
1. Compute hashcode()

2. Determine bucket index

3. Store Entry in bucket

4. Collision handling

5. Retrieve using equals()

Question:

Why should hashCode() and equals() be overridden together?

Because HashMap first checks hashCode and then equals.

10. Collision Handling in HashMap

Before Java 8:

Linked List

After Java 8:

Red Black Tree

when bucket size > 8.

11. HashMap vs ConcurrentHashMap

HashMap

Not thread-safe.

ConcurrentHashMap

Thread-safe.

Uses finer-grained locking.

Question:

Why not use Hashtable?

Entire table locked → slower.

Concurrency

12. Volatile Keyword


Guarantees:

Visibility

Changes visible across threads.

Not Atomicity

Important distinction.

Example:

volatile boolean running=true;

13. synchronized vs volatile

synchronized

 Visibility

 Atomicity

volatile

 Visibility only

14. Race Condition

count++;

Actually:

Read
Increment
Write

Not atomic.

Multiple threads cause inconsistency.

15. Deadlock

Example:

Thread A:

lock1 -> lock2

Thread B:

lock2 -> lock1


Both wait forever.

Question:

How to avoid deadlock?

 Lock ordering

 Timeouts

 ReentrantLock

Exception Internals

16. Why are Exceptions Expensive?

Creating Exception:

new Exception();

Captures stack trace.

Stack trace generation is costly.

17. Di erence Between Error and Exception

Error

JVM level problem.

Examples:

OutOfMemoryError
StackOverflowError

Exception

Application level issue.

OOP Deep Concepts

18. Why Java Doesn't Support Multiple Inheritance?

Diamond Problem.

A
|\
BC
\|
D

Ambiguity.

Java uses Interfaces instead.

19. Runtime Polymorphism Internals

Animal a = new Dog();


[Link]();

Method resolution happens at runtime using:

Dynamic Method Dispatch

20. Can Constructor be Overridden?

No.

Reason:

Constructors are not inherited.

Advanced Keywords

21. final vs finally vs finalize()

final

Prevents modification.

finally

Executes after try-catch.

finalize()

Garbage collection hook.

Deprecated.

Interview favorite.

22. Why Main Method is Static?

JVM invokes it without object creation.


Java 8+ Questions

23. Functional Interface

Contains exactly one abstract method.

Example:

Runnable
Comparator
Callable

24. Lambda Expression

(a,b) -> a+b

Reduces boilerplate code.

Question:

Why Lambda was introduced?

Enable functional programming and Stream API.

25. Stream vs Collection

Collection

Stores data.

Stream

Processes data.

Design Pattern Questions

26. Singleton Pattern

Only one object exists.

Question:

Make Singleton thread-safe.

Answer:

private static volatile Singleton instance;

Double-checked locking.
Frequently Asked "Trap" Questions

Q1

String s = null;
[Link](s);

Output?

null

No exception.

Q2

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


[Link](10);

Valid?

Yes.

final reference cannot change;


object can.

Q3

Integer a = 127;
Integer b = 127;
[Link](a==b);

Output?

true

Integer cache.

Q4

Integer a = 128;
Integer b = 128;
[Link](a==b);

Output?

false

Outside cache range.


1. JVM Architecture

High-Level Flow

.java File

javac Compiler

.class (Bytecode)

Class Loader

Runtime Data Areas

Execution Engine

Machine Code

Components

Class Loader Subsystem

Loads .class files into JVM memory.

Types:

1. Bootstrap ClassLoader

2. Platform/Extension ClassLoader

3. Application ClassLoader

Runtime Data Areas

Heap

Stores objects.

Student s = new Student();

Student object lives in Heap.

Stack

Stores:

 Local variables

 Method calls
 References

int x = 10;
Student s;

Stored in Stack Frame.

Method Area

Stores:

 Class metadata

 Static variables

 Runtime Constant Pool

PC Register

Stores current instruction being executed.

Each thread has its own PC Register.

Native Method Stack

Used when calling C/C++ native code.

Execution Engine

Responsible for executing bytecode.

Contains:

Interpreter

Executes line by line.

Slow.

JIT Compiler

Converts frequently used bytecode into machine code.

Faster.

Interview Question
Why JVM has both Interpreter and JIT?

Interpreter starts execution immediately.

JIT optimizes frequently executed code.

Best of both worlds.

2. Java Memory Model (JMM)

JMM defines:

How threads interact with memory

and guarantees:

Visibility
Ordering
Atomicity

Problem

Thread A:

flag = true;

Thread B:

while(!flag)

Without JMM:

CPU cache may keep stale value.

Thread B may never see update.

Solution

volatile boolean flag;

Guarantees visibility.

Key Terms

Visibility

Changes by one thread visible to another.

Atomicity
Operation completes entirely or not at all.

Example:

count++;

Not atomic.

Actually:

Read
Increment
Write

Happens-Before

Defines execution ordering.

Interviewers love this.

Example:

unlock happens-before lock

3. Class Loading

When JVM encounters:

new Student();

Student class must be loaded.

Phases

Loading

Read bytecode.

Linking

Verification

Checks bytecode validity.

Preparation

Allocates memory for static variables.

Default values assigned.


Resolution

Replace symbolic references.

Initialization

Static blocks execute.

static{
[Link]("Loaded");
}

Runs only once.

Interview Question

When is a class loaded?

Not when compiled.

Loaded when:

new Student()

or

[Link]()

or

[Link]()

4. Deadlock

Definition

Two or more threads waiting forever for each other.

Example

Thread 1

synchronized(lockA){
synchronized(lockB){
}
}
Thread 2

synchronized(lockB){
synchronized(lockA){
}
}

Scenario:

Thread1 holds lockA


Thread2 holds lockB

Thread1 waits for lockB


Thread2 waits for lockA

Deadlock

Four Necessary Conditions

Mutual Exclusion

Only one thread can access resource.

Hold and Wait

Holding one lock while waiting for another.

No Preemption

Cannot forcibly take lock.

Circular Wait

Circular dependency exists.

Break any one condition → no deadlock.

How to Avoid

Lock Ordering

Always acquire locks in same order.


Example:

Always lock A then B

5. Garbage Collection

Purpose

Automatically frees unused memory.

Example

Student s = new Student();

s = null;

Object becomes eligible for GC.

Eligible ≠ Immediately Collected

Common interview trap.

Generational GC

Heap divided into:

Young Generation
Old Generation
Metaspace

Young Generation

New objects created here.

Contains:

Eden
S0
S1

Minor GC

Cleans Young Generation.

Fast.
Major/Full GC

Cleans Old Generation.

Expensive.

Why GC Exists?

Without GC:

Memory leaks
Manual memory management
Dangling pointers

Like C/C++.

Can GC Collect Referenced Objects?

No.

As long as reachable from GC Roots.

GC Roots:

 Stack variables

 Static variables

 Active threads

6. Functional Interfaces

Introduced for Lambda Expressions.

Definition

Exactly one abstract method.

Example:

@FunctionalInterface
interface Calculator{
int add(int a,int b);
}
Valid

interface Test{
void run();
}

Invalid

interface Test{
void run();
void stop();
}

Two abstract methods.

Why Needed?

Before Java 8:

new Runnable(){
public void run(){}
}

Verbose.

After Java 8:

Runnable r = () -> {};

Cleaner.

Common Functional Interfaces

Predicate

boolean test(T t);

Function

R apply(T t);

Consumer

void accept(T t);


Supplier

T get();

7. Exception Internals

Hierarchy

Throwable

├── Error

└── Exception

├── Checked
└── RuntimeException

Error

JVM issues.

Examples:

OutOfMemoryError
StackOverflowError

Should generally not be handled.

Checked Exception

Compiler forces handling.

Examples:

IOException
SQLException

Unchecked Exception

Runtime exceptions.

Examples:

NullPointerException
ArithmeticException
Why Exceptions Are Expensive

Creating exception:

new Exception();

Captures stack trace.

Stack trace generation is costly.

Interview Question

Why not use exceptions for normal control flow?

Because exception creation is expensive.

8. Parent Class of Main Class

Suppose:

public class Main {


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

What is Main's parent?

Answer

[Link]

Every class in Java directly or indirectly extends Object.

Compiler treats it as:

public class Main extends Object{


}

Deep Follow-Up Question

If Object is parent of every class, who is parent of Object?

Answer:

No one.
Object is the root class.

Most Asked Follow-Up


public static void main(String[] args)

Why all three keywords?

public

JVM must access it.

static

JVM can call without creating object.

void

Returns nothing to JVM.

You might also like