KEMBAR78
Java Week-1 Q&A - Complete Answers | PDF | Java Virtual Machine | Java (Programming Language)
0% found this document useful (0 votes)
66 views30 pages

Java Week-1 Q&A - Complete Answers

This document provides a comprehensive overview of Java fundamentals, including key concepts such as the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). It covers essential topics like memory management, platform independence, classes and objects, and advanced concepts, along with interview questions and answers. The document serves as a study guide for Java programming and interview preparation.

Uploaded by

divyavyas003
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)
66 views30 pages

Java Week-1 Q&A - Complete Answers

This document provides a comprehensive overview of Java fundamentals, including key concepts such as the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). It covers essential topics like memory management, platform independence, classes and objects, and advanced concepts, along with interview questions and answers. The document serves as a study guide for Java programming and interview preparation.

Uploaded by

divyavyas003
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
You are on page 1/ 30

Java Week-1 Interview Questions & Answers

Table of Contents
1. Java Fundamentals
2. JVM, JRE, JDK

3. Memory Management
4. Platform Independence

5. Classes and Objects


6. Compilation and Execution

7. Advanced Concepts

Java Fundamentals

Q1: What is Java?


Answer: Java is a high-level, object-oriented, platform-independent programming language developed
by James Gosling at Sun Microsystems in 1995 (now owned by Oracle). Java follows the "Write Once, Run
Anywhere" (WORA) principle, meaning Java programs can run on any platform that has a Java Virtual
Machine (JVM) installed.

Key characteristics:

Object-oriented programming language


Platform-independent

Strongly typed
Automatic memory management

Secure and robust


Multithreaded support

Q2: What is the difference between C, C++, and Java?


Feature C C++ Java

Programming Paradigm Procedural Procedural + OOP Pure OOP

Platform Independence Platform-dependent Platform-dependent Platform-independent

Memory Management Manual (malloc/free) Manual (new/delete) Automatic (Garbage Collection)

Pointers Explicit pointers Explicit pointers No pointers (references only)

Multiple Inheritance Not applicable Supported Not supported (interfaces instead)

Compilation Direct to machine code Direct to machine code Bytecode compilation

Runtime Environment OS-dependent OS-dependent JVM

Security No built-in security Limited security Built-in security features


 

Q3: What are data types other than primitives?


Answer: Non-primitive (Reference) data types in Java include:

1. Classes: User-defined data types that encapsulate data and methods

java

class Student {
String name;
int age;
}

2. Interfaces: Contracts that define method signatures

java

interface Drawable {
void draw();
}

3. Arrays: Collections of elements of the same type

java

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


String[] names = new String[10];

4. Enums: Named constants

java

enum Color {
RED, GREEN, BLUE
}

5. Strings: Sequence of characters (special reference type)


java

String text = "Hello World";

Q4: What is the Volatile keyword?


Answer: The volatile keyword in Java is used to indicate that a variable's value may be modified by
multiple threads simultaneously. It ensures:

Key Features:

Visibility: Changes made by one thread are immediately visible to other threads
No Caching: Variable values are always read from and written to main memory

Atomic Operations: Simple read/write operations are atomic


Prevents Reordering: Compiler optimizations that might reorder instructions are prevented

Example:

java

public class SharedResource {


private volatile boolean flag = false;

public void setFlag() {


flag = true; // Immediately visible to all threads
}

public boolean isFlag() {


return flag; // Always reads from main memory
}
}

When to use:

Flag variables in multithreaded applications


Status indicators

Simple state variables shared between threads

JVM, JRE, JDK

Q5: What is JVM?


Answer: Java Virtual Machine (JVM) is a runtime environment that executes Java bytecode. It acts as an
intermediary layer between Java applications and the operating system.
Key Functions:

Loads Java class files

Verifies bytecode for security

Executes bytecode through interpretation or compilation

Manages memory (heap, stack, method area)

Handles garbage collection


Provides platform independence

JVM Components:

1. Class Loader Subsystem

2. Memory Areas (Heap, Stack, Method Area)

3. Execution Engine (Interpreter, JIT Compiler)

4. Garbage Collector

Q6: What is JRE?


Answer: Java Runtime Environment (JRE) is a software package that provides the runtime environment
for executing Java applications.

Components of JRE:

JVM: Core runtime engine

Core Libraries: Standard Java libraries (rt.jar)

Supporting Files: Configuration files, property files

Other Libraries: Additional runtime libraries

Purpose:

End users need JRE to run Java applications

Does not include development tools

Smaller footprint compared to JDK

Q7: What is JDK?


Answer: Java Development Kit (JDK) is a complete software development environment for developing
Java applications.

Components of JDK:

JRE: Complete runtime environment


Development Tools:
javac (Java compiler)

java (Java interpreter)

javadoc (Documentation generator)

jar (Archive tool)

jdb (Debugger)

Documentation: API documentation

Source Code: Source code for standard libraries

Q8: What is the difference between JDK and JRE?


Aspect JDK JRE

Full Name Java Development Kit Java Runtime Environment

Purpose Development environment Runtime environment

Target Users Developers End users

Components JRE + Development tools JVM + Libraries

Size Larger (includes everything) Smaller (runtime only)

Functionality Compile and run Java programs Run Java programs only

Tools Included javac, javadoc, jar, etc. No development tools


 

Relationship:

JDK = JRE + Development Tools + Documentation


JRE = JVM + Standard Libraries + Supporting Files

Q9: JVM, JRE & JDK difference?


Answer:

Component JVM JRE JDK

Definition Virtual machine that runs bytecode Runtime environment Complete development kit

Platform Dependency Platform-specific Platform-specific Platform-specific

Contains Core execution engine JVM + Libraries JRE + Dev tools

Purpose Execute bytecode Run Java applications Develop Java applications

Required for Running Java Running Java Developing Java

Size Smallest Medium Largest


 
Hierarchy:

JDK (Complete Development Environment)


├── JRE (Runtime Environment)
│ ├── JVM (Execution Engine)
│ └── Standard Libraries
└── Development Tools

Memory Management

Q10: What are the memory areas of JVM?


Answer: JVM memory is divided into several distinct areas:

1. Heap Area

Purpose: Stores objects and instance variables


Shared: Among all threads
Garbage Collection: Occurs here

Subdivisions:
Young Generation: Eden space, Survivor spaces (S0, S1)

Old Generation: Long-lived objects


Metaspace: Class metadata (Java 8+)

2. Stack Area

Purpose: Stores method call frames, local variables, partial results

Thread-specific: Each thread has its own stack


Structure: LIFO (Last In, First Out)

Contents: Method parameters, local variables, return addresses

3. Method Area/Metaspace

Purpose: Stores class-level information


Contents: Method bytecode, constant pool, static variables

Shared: Among all threads


Note: Called Metaspace in Java 8+

4. PC (Program Counter) Register

Purpose: Stores address of currently executing instruction


Thread-specific: Each thread has its own PC register
Size: Very small memory area

5. Native Method Stack

Purpose: Supports native method calls (C/C++)

Thread-specific: Each thread has its own native method stack

Usage: JNI (Java Native Interface) calls

Q11: In which area of your machine are heap objects stored?


Answer: Heap objects are stored in the Random Access Memory (RAM) of the machine. More
specifically:

Physical Storage:

Primary Location: System RAM

Secondary Location: Virtual memory (if RAM is insufficient)


JVM Allocation: JVM allocates heap space from available system memory

Memory Hierarchy:

1. JVM Heap (logical memory area)

2. Process Memory (allocated by OS to JVM process)

3. System RAM (physical memory)

4. Virtual Memory (when RAM is full)

Important Points:

Objects are created in heap memory during runtime


Heap size can be configured using JVM parameters (-Xms, -Xmx)

Garbage collector manages heap memory automatically


Heap memory is shared among all threads

Q12: What is main memory, stack area, heap area?


Answer:

Main Memory

Definition: The primary storage (RAM) of the computer system


Purpose: Stores data and instructions currently being used

Characteristics: Volatile, fast access, limited in size


Relationship to JVM: JVM allocates memory from main memory for its operations

Stack Area

Definition: Memory area that stores method-specific data

Contents:
Method parameters

Local variables

Return addresses
Intermediate computations

Characteristics:
LIFO structure

Thread-specific (each thread has its own stack)


Automatic memory management

Fixed size per thread

Heap Area

Definition: Memory area where objects are allocated


Contents:
Object instances
Instance variables

Arrays

Characteristics:
Shared among all threads

Dynamic memory allocation


Garbage collection occurs here

Can be resized during runtime

Memory Interaction:

Main Memory (RAM)


├── JVM Process Memory
│ ├── Heap Area (Objects)
│ ├── Stack Area (Method calls)
│ ├── Method Area (Class data)
│ └── Other JVM areas
└── Other Process Memory
Q13: Heap area and stack area differences?

Aspect Heap Area Stack Area

Purpose Store objects and instance variables Store method calls and local variables

Memory Structure Random access LIFO (Last In, First Out)

Thread Safety Shared among all threads Thread-specific

Memory Management Garbage collection Automatic (method completion)

Size Large, configurable Smaller, fixed per thread

Access Speed Slower Faster

Memory Allocation Dynamic Static

Lifetime Until garbage collected Until method returns

Contents Objects, arrays, instance variables Local variables, method parameters

Fragmentation Can be fragmented No fragmentation


 

Platform Independence

Q14: Why is Java platform independent?


Answer: Java achieves platform independence through several key mechanisms:

1. Bytecode Compilation

Java source code (.java) compiles to bytecode (.class)

Bytecode is platform-neutral intermediate code


Same bytecode runs on any platform with JVM

2. Java Virtual Machine (JVM)

Each platform has its own JVM implementation

JVM translates bytecode to platform-specific machine code

Provides uniform runtime environment

3. Standard APIs

Consistent standard libraries across platforms

Abstract platform-specific operations


Uniform behavior regardless of underlying OS

4. No Platform-Specific Features

No direct hardware access


No platform-specific system calls
All operations go through JVM

Process Flow:

Java Source Code (.java)



Java Compiler (javac)

Bytecode (.class)

JVM (Platform-specific) → Machine Code → Operating System → Hardware

Benefits:

Write once, run anywhere (WORA)


Reduced development cost

Easier maintenance
Wider application deployment

Q15: JVM - Platform dependent or independent? Why?


Answer: JVM is platform-dependent, while Java bytecode is platform-independent.

Why JVM is Platform-Dependent:

1. Native Implementation: JVM is implemented in native code (C/C++) for each platform
2. OS Integration: Must interact with underlying operating system

3. Hardware Abstraction: Needs to understand platform-specific hardware


4. System Calls: Makes platform-specific system calls

Platform-Specific JVM Implementations:

Windows: JVM for Windows OS


Linux: JVM for Linux distributions
macOS: JVM for Apple systems

Solaris: JVM for Solaris OS

Why Java Bytecode is Platform-Independent:

Standard instruction set regardless of platform

JVM handles platform-specific translation


Same .class files work on all platforms

Architecture:

Platform 1 (Windows) Platform 2 (Linux) Platform 3 (macOS)


JVM JVM JVM
↑ ↑ ↑
└─────── Same Java Bytecode ──────────────────┘

Classes and Objects

Q16: What is class and object?


Answer:

Class

Definition: A class is a blueprint or template that defines the structure and behavior of objects.

Components of a Class:

Attributes/Fields: Variables that store data


Methods: Functions that define behavior

Constructors: Special methods for object initialization


Access Modifiers: Control visibility (public, private, protected)

Example:
java

public class Car {


// Attributes
private String brand;
private String model;
private int year;

// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}

// Methods
public void start() {
System.out.println("Car is starting...");
}

public void stop() {


System.out.println("Car is stopping...");
}
}

Object

Definition: An object is an instance of a class that has actual values for the attributes defined in the class.

Characteristics of an Object:

State: Current values of attributes

Behavior: Actions that can be performed (methods)


Identity: Unique reference in memory

Example:

java

// Creating objects
Car car1 = new Car("Toyota", "Camry", 2023);
Car car2 = new Car("Honda", "Civic", 2022);

// Using objects
car1.start(); // Behavior
car2.stop(); // Behavior
Relationship:

Class is a template; Object is an instance

One class can have multiple objects


Each object has its own memory space

Q17: From what exact processes can we make objects in Java?


Answer: Objects can be created in Java through several processes:

1. Using 'new' Keyword (Most Common)

java

// Standard object creation


MyClass obj = new MyClass();

// With constructor parameters


Person person = new Person("John", 25);

2. Using newInstance() Method (Reflection)

java

// Class.newInstance() - Deprecated in Java 9


MyClass obj = MyClass.class.newInstance();

// Constructor.newInstance() - Preferred approach


Constructor<MyClass> constructor = MyClass.class.getConstructor();
MyClass obj = constructor.newInstance();

3. Using clone() Method

java

// Object must implement Cloneable interface


public class MyClass implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

// Creating object through cloning


MyClass original = new MyClass();
MyClass cloned = (MyClass) original.clone();
4. Using Deserialization

java

// Object must implement Serializable interface


// Reading object from file/stream
FileInputStream fis = new FileInputStream("object.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
MyClass obj = (MyClass) ois.readObject();
ois.close();

5. Using Factory Methods

java

// Static factory methods


String str = String.valueOf(123);
List<String> list = Arrays.asList("a", "b", "c");

6. Using Builder Pattern

java

// Custom builder pattern


StringBuilder sb = new StringBuilder()
.append("Hello")
.append(" ")
.append("World");

Compilation and Execution

Q18: What is JIT Compiler?


Answer: Just-In-Time (JIT) Compiler is a component of the JVM that improves Java application
performance by compiling frequently executed bytecode into native machine code during runtime.

How JIT Works:

1. Initial Execution: Java bytecode is interpreted by JVM


2. Profiling: JIT monitors code execution and identifies "hotspots"

3. Compilation: Frequently executed code is compiled to native machine code


4. Optimization: Applied various optimizations during compilation

5. Caching: Compiled code is cached for future use


Key Features:

Adaptive Optimization:

Monitors program behavior at runtime

Optimizes based on actual usage patterns


Can recompile code with better optimizations

Hotspot Detection:

Identifies frequently executed methods


Focuses optimization efforts on performance-critical code

Uses execution counters and profiling data

Optimization Techniques:

Inlining: Replaces method calls with method body


Dead Code Elimination: Removes unused code

Loop Optimization: Improves loop performance

Register Allocation: Optimizes CPU register usage

Benefits:

Significantly improves runtime performance

Better than pure interpretation


Adaptive to program behavior

No manual optimization required

Trade-offs:

Initial compilation overhead


Memory usage for compiled code

Startup time may be slower

Q19: How can we perform Java program on command prompt?


Answer: Running Java programs from command prompt involves two main steps: compilation and
execution.

Step-by-Step Process:

Step 1: Write Java Program

Create a file named HelloWorld.java :


java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Step 2: Compile the Program

bash

javac HelloWorld.java

What happens:

javac is the Java compiler

Compiles source code (.java) to bytecode (.class)

Creates HelloWorld.class file

Step 3: Run the Program

bash

java HelloWorld

What happens:

java is the Java interpreter

Executes the bytecode


Note: Use class name (without .class extension)

Advanced Command-Line Options:

Compilation with Classpath:

bash

javac -cp /path/to/libraries HelloWorld.java

Running with Classpath:

bash

java -cp /path/to/classes HelloWorld


Memory Settings:

bash

java -Xms512m -Xmx1024m HelloWorld

Package Structure:

bash

# For packaged classes


javac com/example/HelloWorld.java
java com.example.HelloWorld

Common Commands:

javac -version : Check compiler version

java -version : Check runtime version

javac -help : Show compilation options

java -help : Show runtime options

Advanced Concepts

Q20: Which version to use for Java?


Answer: The choice of Java version depends on your project requirements, but here are current
recommendations:

Current Recommended Versions (2024-2025):

Java 21 LTS (Latest LTS - Recommended)

Release: September 2023

Support: Long-term support until 2030+


Features: Virtual threads, pattern matching, records

Best for: New projects, modern applications

Java 17 LTS (Stable Choice)

Release: September 2021

Support: Long-term support until 2029

Features: Sealed classes, text blocks, improved performance


Best for: Enterprise applications, production systems
Java 11 LTS (Legacy but Supported)

Release: September 2018


Support: Long-term support until 2026
Features: HTTP client, local variable type inference

Best for: Existing systems, conservative environments

Selection Criteria:

For New Projects:

Java 21 LTS: Best choice for new development


Modern features and performance improvements

Long-term support guarantee

For Enterprise:

Java 17 LTS: Mature, stable, widely adopted

Good balance of features and stability


Strong ecosystem support

For Legacy Systems:

Java 11 LTS: If upgrading from Java 8


Minimal migration effort

Still receives security updates

Avoid:

Java 8: No longer recommended for new projects

Non-LTS versions: Java 12, 13, 14, 15, 16, 18, 19, 20

Very old versions: Java 6, 7 (security risks)

Q21: What is J2EE?


Answer: Java 2 Platform, Enterprise Edition (J2EE), now known as Jakarta EE, is a platform for
developing and deploying enterprise-level applications in Java.

Evolution:

J2EE: Original name (1999-2006)

Java EE: Renamed version (2006-2017)


Jakarta EE: Current name (2017-present) under Eclipse Foundation
Key Components:

Web Technologies:

Servlets: Server-side Java programs handling HTTP requests

JSP (JavaServer Pages): Dynamic web pages with Java code

JSF (JavaServer Faces): Component-based web framework

WebSocket: Real-time communication

Business Logic:

EJB (Enterprise JavaBeans): Business component architecture


JPA (Java Persistence API): Object-relational mapping

JTA (Java Transaction API): Transaction management


Bean Validation: Data validation framework

Messaging and Integration:

JMS (Java Message Service): Asynchronous messaging


JAX-RS: RESTful web services

JAX-WS: SOAP web services

JCA (Java Connector Architecture): Enterprise system integration

Security:

JAAS (Java Authentication and Authorization Service)

Java EE Security API


Container-managed security

Architecture Patterns:

Multi-tier architecture
Model-View-Controller (MVC)
Dependency injection

Aspect-oriented programming

Benefits:

Scalable enterprise applications

Standard APIs and specifications


Container-managed services
Platform independence
Robust security features

Q22: What is rt.jar file?


Answer: rt.jar (Runtime JAR) is a crucial archive file that contains the core Java runtime classes and is
fundamental to Java application execution.

What rt.jar Contains:

Core Java Packages:

java.lang: Fundamental classes (Object, String, System)


java.util: Utility classes (Collections, Date, etc.)
java.io: Input/output classes

java.net: Networking classes


java.awt: Abstract Window Toolkit (GUI)

java.swing: Swing GUI components


javax.swing: Extended Swing components

System Classes:

Bootstrap classes loaded by JVM

Essential runtime classes


Standard library implementations

Platform-specific native method bindings

Characteristics:

Location:

Java 8 and earlier: JAVA_HOME/jre/lib/rt.jar

Java 9+: Replaced by module system (no rt.jar)

Loading:

Loaded by Bootstrap ClassLoader


First in classpath priority

Cannot be overridden by application classes

Size:

Typically 60-70 MB
Contains thousands of classes
Compressed archive format

Java 9+ Changes:

With Java 9's module system:

rt.jar eliminated: Replaced by modular runtime

Module path: Classes organized in modules


jrt filesystem: New way to access runtime classes
Smaller footprint: Only required modules loaded

Important Notes:

Never modify rt.jar: Can break Java installation


Classpath priority: rt.jar classes cannot be overridden

Version-specific: Each Java version has its own rt.jar


Essential for execution: Required for any Java program

Q23: Why Java is not 100% OOP?


Answer: Java is considered "hybrid" rather than purely object-oriented due to several non-OOP features:

1. Primitive Data Types

Java includes eight primitive types:

java

// These are not objects


int number = 42;
char letter = 'A';
boolean flag = true;
double price = 99.99;

Issues:

Primitives don't inherit from Object class

No methods can be called on primitives


Cannot be used with generics directly

Stored in stack, not heap

2. Static Methods and Variables


java

public class MathUtils {


public static double PI = 3.14159;

public static int add(int a, int b) {


return a + b;
}
}

// Can be called without creating objects


int result = MathUtils.add(5, 3);

3. Procedural Programming Support

java

public class Main {


public static void main(String[] args) {
// Procedural style programming
int a = 10;
int b = 20;
int sum = a + b;
System.out.println(sum);
}
}

4. Primitive Operations

java

// Arithmetic operations are not method calls


int result = 5 + 3; // Not 5.add(3)
boolean check = (a > b); // Not a.greaterThan(b)

5. Functional Programming Features (Java 8+)

java

// Lambda expressions and functional interfaces


List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(System.out::println); // Functional style

Comparison with Pure OOP Languages:

Smalltalk (Pure OOP):


Everything is an object

Even numbers have methods

All operations are message passing

Java (Hybrid):

Objects + primitives
Static methods exist
Procedural programming possible

Why This Design Choice:

Performance: Primitives are faster than objects


Simplicity: Familiar syntax for C/C++ developers

Memory efficiency: Primitives use less memory


Legacy compatibility: Integration with existing systems

Q24: Difference between Path and Classpath?


Answer:

Aspect PATH CLASSPATH

Purpose Locate executable files Locate Java class files and packages

Type OS environment variable Java-specific environment variable

Contents Directories containing executables Directories and JAR files containing classes

Scope System-wide (all applications) Java applications only

Default Behavior System searches current directory first Current directory (.) included by default
 

PATH Environment Variable:

Purpose:

Tells the operating system where to find executable programs


Used when you type commands in command prompt/terminal

Example:
bash

# Windows
set PATH=%PATH%;C:\Program Files\Java\jdk-17\bin

# Linux/Mac
export PATH=$PATH:/usr/lib/jvm/java-17/bin

What it enables:

bash

# These commands work from any directory


javac HelloWorld.java
java HelloWorld
jar -cf myapp.jar *.class

CLASSPATH Environment Variable:

Purpose:

Tells JVM where to find Java class files, packages, and libraries
Used during compilation and execution

Example:

bash

# Windows
set CLASSPATH=.;C:\myproject\classes;C:\libs\mylib.jar

# Linux/Mac
export CLASSPATH=.:$HOME/myproject/classes:/usr/local/libs/mylib.jar

What it enables:

bash

# JVM can find classes in specified locations


java MyApplication
javac -cp /path/to/libs/*.jar MyClass.java

Setting Classpath:

Method 1: Environment Variable


bash

export CLASSPATH=/path/to/classes:/path/to/lib.jar

Method 2: Command Line

bash

java -cp /path/to/classes:/path/to/lib.jar MyClass


javac -classpath /path/to/lib.jar MyClass.java

Method 3: Manifest File (for JAR)

Class-Path: lib/dependency1.jar lib/dependency2.jar

Common Issues:

PATH Problems:

'javac' is not recognized : Java tools not in PATH

Wrong Java version: Multiple Java installations in PATH

CLASSPATH Problems:

ClassNotFoundException : Class not in classpath

NoClassDefFoundError : Dependent classes not found

Package structure mismatch

Best Practices:

Set PATH for Java tools (javac, java, jar)


Use -cp option instead of CLASSPATH environment variable
Include current directory (.) in classpath when needed

Use absolute paths to avoid confusion


Document classpath requirements for your applications

Q25: Architecture of JVM?


Answer: The Java Virtual Machine (JVM) has a sophisticated architecture designed to execute Java
bytecode efficiently and securely.

Complete JVM Architecture:


┌─────────────────────────────────────────────────────────────┐
│ CLASS LOADER SUBSYSTEM │
├─────────────────┬─────────────────┬─────────────────────────┤
│ Bootstrap │ Extension │ Application │
│ Class Loader │ Class Loader │ Class Loader │
└─────────────────┴─────────────────┴─────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ NATIVE METHOD INTERFACE │
├─────────────────────────────────────────────────────────────┤
│ NATIVE METHOD LIBRARIES │
└─────────────────────────────────────────────────────────────┘

1. Class Loader Subsystem

Responsibilities:

Loading class files from various sources

Linking classes and interfaces


Initialization of classes

Components:

Bootstrap Class Loader:

Loads core Java classes (rt.jar)

Written in native code (C/C++)


Parent of all other class loaders
Loads classes from JAVA_HOME/jre/lib

Extension Class Loader:

Loads classes from extension directories

Loads from JAVA_HOME/jre/lib/ext

Child of Bootstrap Class Loader

Application Class Loader:

Loads classes from application classpath


Loads user-defined classes

Child of Extension Class Loader

Class Loading Process:


1. Loading: Reading .class files and creating Class objects

2. Linking:
Verification: Bytecode verification for security

Preparation: Allocating memory for static variables


Resolution: Converting symbolic references to direct references

3. Initialization: Executing static initializers and static blocks

2. Memory Areas

Method Area (Metaspace in Java 8+):

Stores class-level information

Method bytecode and metadata


Constant pool

Static variables
Shared among all threads

Heap Area:

Object storage area


Instance variables

Arrays

Garbage collection target


Shared among all threads

Subdivisions:

Young Generation:
Eden Space: New objects allocated here
Survivor Spaces (S0, S1): Objects that survived one GC cycle

Old Generation: Long-lived objects

Metaspace: Class metadata (Java 8+)

Stack Area:

Method call stack


Local variables
Method parameters

Return addresses
Thread-specific memory

PC (Program Counter) Register:

Current instruction pointer


Thread-specific

Points to currently executing instruction

Native Method Stack:

Supports native method calls

Used for JNI (Java Native Interface)


Thread-specific

3. Execution Engine

Interpreter:

Executes bytecode line by line


Slower but immediate execution

Platform-independent

JIT (Just-In-Time) Compiler:

Compiles hotspots to native code


Improves performance significantly

Adaptive optimization

Garbage Collector:

Automatic memory management

Reclaims unused object memory


Various algorithms available

Types of Garbage Collectors:

Serial GC: Single-threaded


Parallel GC: Multi-threaded

G1 GC: Low-latency collector


ZGC: Ultra-low latency collector

4. Native Method Interface (JNI)

Bridge between Java and native code


Allows calling C/C++ functions from Java
Enables platform-specific functionality

5. Native Method Libraries

Collection of native libraries

Platform-specific implementations

Required for JNI calls

JVM Execution Flow:

1. Class Loading: Load required classes


2. Bytecode Verification: Security checks

3. Memory Allocation: Allocate memory areas


4. Execution:
Interpret bytecode or
Compile to native code (JIT)

5. Memory Management: Garbage collection

6. Native Calls: Handle JNI if needed

Key Characteristics:

Platform Independence: Same bytecode runs on different JVMs

Security: Bytecode verification and sandbox execution


Performance: JIT compilation and optimization

Memory Management: Automatic garbage collection


Multithreading: Thread-safe execution environment

Summary
This comprehensive guide covers all the essential Java concepts and interview questions from Week-1.
Each answer provides both theoretical understanding and practical knowledge that's crucial for Java
developers and interview preparation.

Key Takeaways:
1. Java Fundamentals: Understanding Java's core principles and features
2. JVM Architecture: Deep knowledge of how Java programs execute
3. Memory Management: Critical for performance optimization

4. Platform Independence: Core advantage of Java technology


5. Object-Oriented Concepts: Foundation of Java programming
6. Development Tools: Essential for Java development workflow

Recommended Study Approach:


1. Understand Concepts: Focus on "why" not just "what"
2. Practice Coding: Implement examples for each concept

3. Memory Management: Pay special attention to heap/stack differences


4. JVM Internals: Understand the complete execution flow
5. Practical Application: Practice command-line compilation and execution

Note: This document serves as a comprehensive reference for Java Week-1 concepts. For deeper
understanding, practice implementing code examples and experimenting with JVM parameters and
memory settings.

Document Information:

Created: Java Week-1 Interview Preparation

Topics Covered: 25+ Essential Java Concepts


Suitable For: Beginners to Intermediate Java Developers

Format: Interview Question & Answer Style ▼


┌─────────────────────────────────────────────────────────────
┐ │ MEMORY AREAS │
├─────────────────┬─────────────────┬─────────────────────────
┤ │ Method Area │ Heap Area │ Stack Area │ │ (Metaspace) │ │ │
├─────────────────┼─────────────────┼─────────────────────────
┤ │ PC Register │ Native Method │ │ │ │ Stack │ │
└─────────────────┴─────────────────┴─────────────────────────
┘│▼
┌─────────────────────────────────────────────────────────────
┐ │ EXECUTION ENGINE │
├─────────────────┬─────────────────┬─────────────────────────
┤ │ Interpreter │ JIT Compiler │ Garbage Collector │
└─────────────────┴─────────────────┴─────────────────────────
┘│

You might also like