0% found this document useful (0 votes)
2 views23 pages

Java Guide 2

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)
2 views23 pages

Java Guide 2

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.

JDK vs JRE vs JVM

JVM (Java Virtual Machine)

 Executes Java bytecode.

 Converts bytecode into machine code.

 Platform dependent.

Responsibilities:

 Memory management

 Garbage collection

 Class loading

 Bytecode execution

JRE (Java Runtime Environment)

Contains:

JRE = JVM + Libraries

Used to run Java applications.

Cannot compile Java programs.

JDK (Java Development Kit)

Contains:

JDK = JRE + Development Tools

Tools include:

javac
javadoc
jar
jdb

Used for development.

Interview Follow-up

Can a machine have JRE without JVM?

No.
JRE itself contains JVM.
2. Why Java is Platform Independent?

Java source code:

[Link]

Compiled into

[Link]

(Bytecode)

JVM executes bytecode.

Since every OS has its own JVM:

Windows JVM
Linux JVM
Mac JVM

Same bytecode runs everywhere.

Hence:

Write Once Run Anywhere

3. OOP Concepts

Four pillars:

Encapsulation

Wrapping data and methods together.

class Employee{
private int salary;
}

Abstraction

Hiding implementation details.

interface Vehicle{
void start();
}

User knows what happens, not how.


Inheritance

Code reuse.

class Dog extends Animal

Polymorphism

One interface, many forms.

Animal a = new Dog();

4. Encapsulation vs Abstraction

Encapsulation Abstraction

Hides data Hides implementation

Achieved using private variables Achieved using abstract class/interface

Focus on security Focus on simplicity

Example:

ATM

Abstraction:

Withdraw Money

You don't know internal process.

Encapsulation:

Balance field is private

Cannot access directly.

5. Overloading vs Overriding

Overloading

Same method name.

Di erent parameters.
add(int a,int b)

add(int a,int b,int c)

Compile-time polymorphism.

Overriding

Child provides new implementation.

class Animal{
void sound(){}
}

class Dog extends Animal{


void sound(){}
}

Runtime polymorphism.

6. Abstract Class vs Interface

Abstract Class

Can have:

abstract method
normal method
constructors
instance variables

Interface

Designed for complete abstraction.

Supports:

multiple inheritance
default methods
static methods

When to Use?

Abstract class:

IS-A relationship
Interface:

CAN-DO relationship

7. String vs StringBu er vs StringBuilder

String

Immutable.

String s="Java";

Every modification creates new object.

StringBu er

Mutable.

Thread-safe.

Slower.

StringBuilder

Mutable.

Not thread-safe.

Faster.

Follow-up

Which one should you use?

Single thread:

StringBuilder

Multi-thread:

StringBu er

8. Why String is Immutable?

Reasons:

Security
Database URL
File Path

Cannot be changed.

String Pool

Allows reuse.

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

Both point to same object.

Thread Safety

Multiple threads can safely share String.

HashMap Optimization

Hashcode cached.

Faster lookup.

9. Constructor vs Method

Constructor Method

Same name as class Any name

No return type Has return type

Auto-called Explicitly called

Initializes object Performs actions

Example:

Student(){
}

Constructor.

10. Static Keyword


Belongs to class.

Not object.

Example:

class Student{
static int count;
}

Only one copy exists.

Shared among all objects.

Static Members

static variable
static method
static block
static nested class

11. Why main() is static?

public static void main(String[] args)

JVM calls:

[Link]()

without creating object.

If main wasn't static:

Main obj = new Main();

JVM would need object first.

Chicken-and-egg problem.

12. Exception Handling

Mechanism to handle runtime errors.

Keywords:

try
catch
finally
throw
throws

Flow:

try{
}
catch(Exception e){
}
finally{
}

13. Checked vs Unchecked Exception

Checked

Compiler forces handling.

Examples:

IOException
SQLException

Unchecked

Occurs during runtime.

Examples:

NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException

Interview Question

Why RuntimeException is unchecked?

Programmer error.

Compiler cannot always predict.

14. Array vs ArrayList


Array ArrayList

Fixed size Dynamic size

Faster Slight overhead

Can store primitives Stores objects

Length property size() method

Example:

int arr[] = new int[10];

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

15. List vs Set

List

 Ordered

 Duplicates allowed

Example:

[1,2,2,3]

Set

 Unique elements

 No duplicates

Example:

[1,2,3]

Popular implementations:

List:

ArrayList
LinkedList
Vector

Set:
HashSet
LinkedHashSet
TreeSet

16. HashMap vs HashTable

HashMap HashTable

Not synchronized Synchronized

Faster Slower

Allows null Doesn't allow null

Follow-up:

Why HashMap is faster?

No locking overhead.

17. HashMap vs TreeMap

HashMap

Uses hashing.

Average complexity:

O(1)

No ordering.

TreeMap

Uses Red-Black Tree.

Complexity:

O(log n)

Maintains sorted order.

Interview Question:

Which consumes more memory?

TreeMap.
18. Process vs Thread

Process

Independent execution unit.

Own memory space.

Examples:

Chrome
VS Code
Spotify

Thread

Lightweight unit inside process.

Shares process memory.

Example:

Chrome Process

Tab 1 Thread
Tab 2 Thread
Tab 3 Thread

19. Synchronization

Used to prevent race conditions.

Problem:

count++;

Actually:

Read
Increment
Write

Multiple threads may interfere.

Solution:
synchronized void increment(){
count++;
}

Only one thread enters at a time.

Follow-up:

What problems does synchronization solve?

 Race conditions

 Data inconsistency

 Visibility issues

20. Stack vs Heap Memory

Stack

Stores:

int x=10;

Method calls.

Local variables.

Characteristics:

Fast
Thread-specific
Automatically managed

Heap

Stores:

new Student()

Objects.

Shared among threads.

Managed by GC.

Example:
Student s = new Student();

Stack:
s (reference)

Heap:
Student Object

1. Why is String Immutable but StringBuilder Mutable?

Short Answer

String is immutable for:

 Security

 Thread safety

 String Pool optimization

 HashMap optimization

StringBuilder was introduced for e icient string modifications.

Example

String s = "Java";
[Link](" Programming");

Many freshers think:

Java Programming

Actually:

Java

because a new String object is created.

Why Not Make String Mutable?

Imagine:

String url = "jdbc:mysql://prod-db";

If one thread modifies it:

url = "jdbc:mysql://hack-db";

every reference may break.

Immutable objects eliminate this problem.


Then Why StringBuilder?

Suppose:

for(int i=0;i<1000;i++){
str += i;
}

Creates 1000+ String objects.

Huge memory waste.

StringBuilder modifies the same object:

StringBuilder sb = new StringBuilder();

No new object creation every time.

2. Can We Override a Static Method?

No

Static methods belong to the class.

Overriding requires runtime polymorphism.

Static methods are resolved at compile time.

Example:

class Parent{
static void show(){
[Link]("Parent");
}
}

class Child extends Parent{


static void show(){
[Link]("Child");
}
}

Parent p = new Child();


[Link]();

Output:

Parent
not Child.

This is called:

Method Hiding

not overriding.

3. Can Constructor Be Private?

Yes

Very common interview question.

Example:

class Test{
private Test(){
}
}

Now:

new Test();

outside class is impossible.

Why Use Private Constructor?

Singleton Pattern

class Singleton{
private Singleton(){}
}

Only one object allowed.

Utility Classes

Example:

Math
Collections

Object creation not needed.


4. Why Multiple Inheritance is Not Supported in Classes?

Because of the:

Diamond Problem

Example

A
/\
B C
\/
D

Suppose:

class A{
void display(){}
}

B and C inherit A.

D inherits B and C.

Now:

D d = new D();
[Link]();

Which display() should JVM call?

B's?

C's?

Ambiguity.

Java avoids this completely.

Then Why Multiple Interface Inheritance?

Interfaces originally had no implementation.

No ambiguity.

Even with Java 8 default methods, Java forces explicit resolution.


5. Why Should HashMap Key Be Immutable?

This is a very important question.

HashMap stores entries using:

hashCode()

Example

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

Suppose:

Student s = new Student(1);

hashCode:

100

stored in Bucket 100.

Now change:

[Link] = 2;

hashCode becomes:

250

HashMap still thinks object is in bucket 100.

Search happens in bucket 250.

Object becomes unreachable.

Hence keys should be:

Immutable

Examples:

String
Integer
Long
UUID
6. Why Must equals() and hashCode() Be Overridden Together?

HashMap internally:

Step 1

Compare hashCode()

Step 2

Compare equals()

Suppose:

Student s1 = new Student(1);


Student s2 = new Student(1);

Override only:

equals()

Now:

[Link](s2)

returns:

true

But:

[Link]()

and

[Link]()

di erent.

HashMap places them in di erent buckets.

Now equal objects behave di erently.

Contract breaks.

Rule:
Equal objects MUST have equal hashcodes.

7. Fail-Fast vs Fail-Safe Iterator

Fail-Fast

Collections:

ArrayList
HashMap
HashSet

Example:

for(Integer i : list){
[Link](100);
}

Throws:

ConcurrentModificationException

Reason:

Iterator detects structural modification.

Fail-Safe

Collections:

ConcurrentHashMap
CopyOnWriteArrayList

Iterator works on:

Copy of collection

No exception.

Comparison
Fail-Fast Fail-Safe

Original collection Copy

Faster More memory

Throws exception No exception

8. Why ConcurrentHashMap is Preferred Over Hashtable?

Hashtable

Every operation locks entire table.

put()
get()
remove()

all synchronized.

Only one thread works at a time.

Poor scalability.

ConcurrentHashMap

Uses:

Fine-grained locking
CAS operations

(Java 8 implementation)

Multiple threads can access di erent buckets simultaneously.

Much better performance.

Interview answer:

Thread-safe like Hashtable but highly scalable.

9. Why ArrayList is Not Synchronized?


Because synchronization has a cost.

Most applications:

Single Thread

or

Read Heavy

Making every operation synchronized:

add()
remove()
get()

would slow everything.

Java chose:

Performance First

If thread safety needed:

[Link]()

or

CopyOnWriteArrayList

10. What Exactly Happens in Memory When Creating an Object?

Example:

Student s = new Student();

Step 1

JVM checks:

Is Student class loaded?

If not:

Class Loader loads it.

Step 2
Memory allocated in Heap.

Heap
└── Student Object

Step 3

Instance variables initialized.

int age;

becomes:

default value.

Step 4

Constructor executes.

Student(){
age = 20;
}

Step 5

Reference variable created in Stack.

Stack
└── s

Final Memory Layout

Stack
------
s
|
| reference
v

Heap
------
Student Object
age = 20
Interview Killer Question

What happens first?

Student s = new Student();

1. Memory allocation?

2. Constructor call?

Answer:

1. Memory Allocation
2. Default Initialization
3. Constructor Execution
4. Reference Assignment

Because constructor needs an object to operate on, JVM must allocate memory first.

You might also like