Q1.
Java as an Object-Oriented Programming Language
Java is a high-level, class-based, and Object-Oriented Programming (OOP) language developed by Oracle
Corporation.
It is designed to create software using the concept of objects and classes. In Java, everything is organized in the
form of objects that contain data and methods.
Object-Oriented Programming helps programmers write secure, reusable, and easy-to-maintain programs. Java
follows the four main principles of OOP:
1. Encapsulation – Wrapping data and methods into a single unit (class).
2. Inheritance – One class can acquire properties of another class.
3. Polymorphism – One method can perform different tasks.
4. Abstraction – Hiding unnecessary details and showing only important features.
Java programs are compiled into bytecode, which runs on the Java Virtual Machine (JVM). This makes Java
platform-independent.
Java is widely used for:
• Web applications
• Mobile applications
• Desktop software
• Enterprise applications
• Cloud computing and games
Key Features of Java
1. Simple
Java has simple syntax similar to C/C++, making it easy to learn and use.
2. Object-Oriented
Java is completely based on objects and classes, which improves code reusability and modularity.
3. Platform Independent
Java follows the principle:
“Write Once, Run Anywhere (WORA)”
A Java program can run on any operating system that has JVM.
4. Secure
Java provides security features like:
• No pointer access
• Bytecode verification
• Automatic memory management
5. Robust
Java is reliable because it has:
• Exception handling
• Strong memory management
• Garbage collection
6. Portable
Java programs can easily move from one system to another without modification.
7. Multithreaded
Java supports multithreading, allowing multiple tasks to run simultaneously.
8. Distributed
Java supports distributed computing and networking through internet-based applications.
9. High Performance
Java uses Just-In-Time (JIT) compiler to improve execution speed.
10. Dynamic
Java can dynamically load classes during runtime, making programs flexible.
Conclusion
Java is a powerful Object-Oriented Programming language that provides security, portability, robustness, and
platform independence. Due to its advanced features and easy programming style, Java is widely used in modern
software development.
Q2. Features of Java
Java is one of the most popular programming languages because of its powerful and advanced features. These
features make Java suitable for developing web applications, mobile apps, enterprise software, and scientific
applications.
1. Simple
Java is easy to learn and understand because its syntax is similar to C and C++.
It removes complex features such as:
• Pointers
• Operator overloading
• Multiple inheritance
Java provides automatic memory management through garbage collection, which makes programming simpler.
Example:
class Hello {
public static void main(String args[]) {
[Link]("Hello Java");
2. Object-Oriented
Java is a fully Object-Oriented Programming language.
Everything in Java is based on classes and objects.
Java supports the four main OOP concepts:
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
Advantages:
• Code reusability
• Better security
• Easy maintenance
3. Platform Independent
Java follows the principle:
“Write Once, Run Anywhere” (WORA)
A Java program is compiled into bytecode, which can run on any operating system using the Java Virtual Machine
(JVM).
Process:
Source Code → Compiler → Bytecode → JVM → Output
This makes Java platform independent.
4. Portable
Java programs can easily move from one computer system to another without changing the code.
Java ensures portability because:
• Primitive data types have fixed sizes.
• Bytecode can run on any JVM.
5. Secure
Java provides high security features.
Security features:
• No pointers
• Bytecode verification
• Security manager
• Exception handling
Java is widely used in:
• Banking systems
• Online transactions
• Web applications
6. Robust
Robust means strong and reliable.
Java is robust because:
• It uses strong memory management.
• It has automatic garbage collection.
• It supports exception handling.
• It avoids memory leaks.
These features reduce program crashes.
7. Multithreaded
Java supports multithreading, which means multiple tasks can run simultaneously.
Example:
• Playing music while downloading a file.
Advantages:
• Better CPU utilization
• Faster execution
• Improved performance
Java provides built-in support through the Thread class.
8. Distributed
Java is designed for distributed computing.
It supports internet-based applications using:
• RMI (Remote Method Invocation)
• Networking APIs
• Web services
This feature helps applications communicate over networks.
9. High Performance
Java is faster than many traditional interpreted languages because of:
• Bytecode
• Just-In-Time (JIT) compiler
The JIT compiler converts bytecode into machine code during runtime, improving speed.
10. Dynamic
Java is dynamic because it can:
• Load classes during runtime
• Support dynamic memory allocation
This makes Java flexible and adaptable.
11. Architecture Neutral
Java does not depend on any specific processor architecture.
The compiler generates bytecode instead of machine-specific code, allowing Java programs to run on different
processors.
12. Interpreted
Java bytecode is interpreted by the JVM.
The JVM reads and executes the bytecode line by line, making Java highly portable.
Conclusion
Java provides many powerful features such as simplicity, security, portability, robustness, multithreading, and
platform independence. These features make Java a reliable and widely used programming language for modern
software development.
Q3. Access Specifiers in Java
Access specifiers (also called access modifiers) in Java are used to control the visibility and accessibility of classes,
variables, methods, and constructors.
They help in providing security and data hiding in Java programs.
Java provides four types of access specifiers:
1. Public
2. Private
3. Protected
4. Default (No modifier)
1. Public Access Specifier
The public access specifier allows a class member to be accessed from anywhere in the program.
Features:
• Accessible within the class
• Accessible within the package
• Accessible outside the package
• Accessible through inheritance
Example:
class Test {
public int num = 10;
class Demo {
public static void main(String args[]) {
Test t = new Test();
[Link]([Link]);
Output:
10
2. Private Access Specifier
The private access specifier allows members to be accessed only within the same class.
Features:
• Cannot be accessed outside the class
• Provides maximum security
• Used for data hiding
Example:
class Test {
private int num = 10;
void display() {
[Link](num);
class Demo {
public static void main(String args[]) {
Test t = new Test();
[Link]();
Output:
10
3. Protected Access Specifier
The protected access specifier allows access:
• Within the same package
• Outside the package through inheritance
Features:
• Mostly used in inheritance
• More accessible than private
Example:
class Parent {
protected int num = 20;
class Child extends Parent {
void show() {
[Link](num);
class Demo {
public static void main(String args[]) {
Child c = new Child();
[Link]();
Output:
20
4. Default Access Specifier
When no access specifier is used, it is called the default access specifier.
Features:
• Accessible only within the same package
• Cannot be accessed outside the package
Example:
class Test {
int num = 30;
class Demo {
public static void main(String args[]) {
Test t = new Test();
[Link]([Link]);
Output:
30
Table of Access Specifiers
AccessSame
Specifier
SameSubclass
Class
Outside
PackagePackage
Public Yes
Yes Yes
Yes
PrivateYes
No No
No
Protected
Yes
Yes Yes
No
DefaultYes
Yes No
No
Conclusion
Access specifiers in Java are important for controlling data accessibility and security.
They help programmers implement data hiding, encapsulation, and proper object-oriented design. Different access
specifiers are used according to the required level of accessibility in a program.
Q4. Why is the main Function Declared as
public static void main(String args[]) in Java?
In Java, the main() method is the entry point of a program.
The Java Virtual Machine (JVM) starts program execution from the main() method.
The general syntax of the main method is:
public static void main(String args[])
Each keyword in this declaration has a special meaning.
1. public
The keyword public is an access specifier.
It means the main() method can be accessed from anywhere.
Why public?
The JVM needs to call the main() method from outside the class.
If the method is not public, JVM cannot access it and the program will not execute.
2. static
The keyword static means the method belongs to the class rather than an object.
Why static?
The JVM calls the main() method before creating any object of the class.
If main() were not static, an object would be required first.
Therefore, main() is declared static so JVM can call it directly using the class name.
3. void
The keyword void indicates that the method does not return any value.
Why void?
The main() method only starts the execution of the program and does not return anything to JVM.
Hence, its return type is void.
4. main
main is the predefined method name recognized by JVM.
Why main?
The JVM searches specifically for a method named main() to begin execution.
If the method name is changed, the program will compile but will not run.
5. String args[]
String args[] is used to receive command-line arguments.
Why String array?
When a program is executed from the command line, values can be passed as arguments.
These arguments are stored as strings in the array args.
Example:
class Test {
public static void main(String args[]) {
[Link](args[0]);
If executed as:
java Test Hello
Output:
Hello
Complete Example
class Demo {
public static void main(String args[]) {
[Link]("Welcome to Java");
Output:
Welcome to Java
Conclusion
The declaration public static void main(String args[]) is used because:
• public → JVM can access it
• static → JVM can call it without creating an object
• void → It does not return any value
• main → Entry point of the program
• String args[] → Stores command-line arguments
Therefore, this declaration is necessary for successful execution of a Java program.
Q5. Uses of final, this, and super Keywords in Java
Java provides special keywords such as final, this, and super to perform important programming tasks. These
keywords help in achieving security, inheritance control, and proper object-oriented programming.
Part 1: Uses of final Keyword in Java
The final keyword is used to restrict modification.
It can be used with:
1. Variables
2. Methods
3. Classes
1. Final Variable
When a variable is declared as final, its value cannot be changed once assigned.
Example:
class Test {
final int x = 10;
void display() {
// x = 20; // Error
[Link](x);
Output:
10
Use:
• Used to create constant values.
2. Final Method
When a method is declared as final, it cannot be overridden by subclasses.
Example:
class Parent {
final void show() {
[Link]("Final Method");
}
class Child extends Parent {
// void show() {} // Error
Use:
• Prevents method overriding.
• Provides security and fixed implementation.
3. Final Class
When a class is declared as final, it cannot be inherited.
Example:
final class Test {
void display() {
[Link]("Final Class");
// class Demo extends Test {} // Error
Use:
• Prevents inheritance.
• Used for security purposes.
Example: String class in Java is final.
Conclusion of final Keyword
The final keyword is used to restrict changes:
• Final variable → value cannot change
• Final method → cannot be overridden
• Final class → cannot be inherited
Part 2: Use of this Keyword
The this keyword refers to the current object of a class.
Uses of this Keyword
1. To Refer Current Class Instance Variable
Used when local variables and instance variables have the same name.
Example:
class Student {
int id;
Student(int id) {
[Link] = id;
void display() {
[Link](id);
2. To Invoke Current Class Method
Example:
class Test {
void show() {
[Link]("Hello");
void display() {
[Link]();
}
3. To Invoke Current Class Constructor
Example:
class Demo {
Demo() {
this(10);
[Link]("Default Constructor");
Demo(int x) {
[Link](x);
4. To Pass Current Object as Argument
this can be passed as a parameter in methods or constructors.
Conclusion of this Keyword
The this keyword is mainly used to:
• Refer current object
• Resolve variable confusion
• Call constructors and methods
Part 3: Use of super Keyword
The super keyword refers to the immediate parent class object.
Uses of super Keyword
1. To Access Parent Class Variable
Example:
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
[Link](super.x);
Output:
10
2. To Invoke Parent Class Method
Example:
class Parent {
void show() {
[Link]("Parent Method");
class Child extends Parent {
void show() {
[Link]();
[Link]("Child Method");
3. To Invoke Parent Class Constructor
Example:
class Parent {
Parent() {
[Link]("Parent Constructor");
}
class Child extends Parent {
Child() {
super();
[Link]("Child Constructor");
Difference Between this and super
this super
Refers to current class
Refers
object
to parent class object
Used within same class
Used in inheritance
Calls current class constructor
Calls parent class constructor
Final Conclusion
• final keyword restricts modification.
• this keyword refers to the current class object.
• super keyword refers to the parent class object.
These keywords are important in Java for implementing inheritance, security, and object-oriented programming
concepts effectively.
Q6. Difference Between int and Integer in Java
In Java, both int and Integer are used to store integer values, but they are different in many ways.
Definition
int
int is a primitive data type in Java used to store whole numbers.
Example:
int a = 10;
Integer
Integer is a wrapper class in Java that wraps an int value into an object.
Example:
Integer b = 10;
Difference Between int and Integer
Basis int Integer
Type Primitive data typeWrapper class (Object)
Memory Uses less memory Uses more memory
Speed Faster Slightly slower
Default Value 0 null
Can Store Null No Yes
Object Support Not an object Object type
Used In Collections
Not allowed directlyAllowed
Methods Available
No methods Many utility methods
Package Built-in primitive Part of [Link] package
Example of int
class Demo {
public static void main(String args[]) {
int a = 5;
[Link](a);
Output:
Example of Integer
class Demo {
public static void main(String args[]) {
Integer b = 15;
[Link](b);
Output:
15
Autoboxing and Unboxing
Java automatically converts:
• int → Integer (Autoboxing)
• Integer → int (Unboxing)
Example:
class Test {
public static void main(String args[]) {
int a = 10;
Integer obj = a; // Autoboxing
int b = obj; // Unboxing
[Link](b);
Output:
10
When to Use int?
Use int when:
• Only numeric calculations are needed
• Better performance is required
• No object functionality is needed
When to Use Integer?
Use Integer when:
• Working with collections like ArrayList
• Null values are needed
• Utility methods are required
Example:
ArrayList<Integer> list = new ArrayList<Integer>();
Conclusion
int is a primitive data type used for fast and memory-efficient calculations, while Integer is a wrapper class that
provides object functionality and utility methods. Both are important in Java and are used according to
programming requirements.
Garbage Collection in Java
Garbage Collection (GC) is a memory management process in Java that automatically removes unused objects
from memory.
It helps free memory space and improves program performance.
In Java, memory management is handled automatically by the Java Virtual Machine (JVM).
Programmers do not need to manually delete objects.
Definition
Garbage Collection is the process of identifying and destroying unused objects that are no longer required by the
program.
The component responsible for this task is called the Garbage Collector.
Why Garbage Collection is Needed
Garbage collection is important because it:
• Frees unused memory
• Prevents memory leaks
• Improves performance
• Reduces program crashes
• Provides automatic memory management
How Garbage Collection Works
Java stores objects in Heap Memory.
When an object is created, memory is allocated in the heap.
If the object is no longer referenced by any variable, it becomes eligible for garbage collection.
The Garbage Collector automatically detects such unused objects and removes them from memory.
Steps of Garbage Collection
1. Object Creation
Objects are created and stored in heap memory.
Example:
Test t = new Test();
2. Object Becomes Unused
An object becomes eligible for garbage collection when:
• Reference variable becomes null
• Reference variable points to another object
• Object is created anonymously
• Method finishes execution
Example:
Test t = new Test();
t = null;
Now the object has no reference and becomes garbage.
3. Garbage Collector Runs
The JVM automatically calls the Garbage Collector to destroy unused objects and free memory.
Ways an Object Becomes Eligible for Garbage Collection
1. Nullifying Reference Variable
Test t = new Test();
t = null;
2. Reassigning Reference Variable
Test t1 = new Test();
Test t2 = new Test();
t1 = t2;
The first object becomes unused.
3. Anonymous Object
new Test();
Since no reference variable exists, the object becomes eligible immediately.
Requesting Garbage Collection
Programmers can request JVM to run garbage collection using:
[Link]();
or
[Link]().gc();
However, JVM does not guarantee immediate execution.
finalize() Method
Before destroying an object, JVM may call the finalize() method.
Example:
class Test {
protected void finalize() {
[Link]("Object destroyed");
The finalize() method is used for cleanup activities.
Example Program of Garbage Collection
class Demo {
public static void main(String args[]) {
Demo d1 = new Demo();
Demo d2 = new Demo();
d1 = null;
d2 = null;
[Link]();
protected void finalize() {
[Link]("Garbage Collected");
Possible Output:
Garbage Collected
Garbage Collected
Advantages of Garbage Collection
1. Automatic memory management
2. Prevents memory leaks
3. Improves application efficiency
4. Reduces programmer workload
5. Enhances security and reliability
Disadvantages of Garbage Collection
1. Consumes CPU time
2. Execution timing is unpredictable
3. Slightly affects performance in large applications
Conclusion
Garbage Collection in Java is an automatic memory management mechanism that removes unused objects from
heap memory. It is handled by the JVM and helps improve memory utilization, program reliability, and overall
performance.
How Can a Derived Class Constructor Pass Arguments to Base Class Constructor in Java?
In Java, a derived class (subclass) can pass arguments to the constructor of its base class (superclass) using the
super() keyword.
The super() constructor call is used to invoke the parent class constructor from the child class constructor.
Why is it Needed?
When a subclass object is created:
1. The constructor of the superclass executes first.
2. Then the constructor of the subclass executes.
If the superclass constructor requires arguments, the subclass must pass those arguments using super().
Syntax
super(arguments);
The super() statement must be the first statement inside the child class constructor.
Example Program
class Parent {
int x;
Parent(int a) {
x = a;
[Link]("Parent Constructor: " + x);
class Child extends Parent {
int y;
Child(int a, int b) {
super(a); // Passing argument to parent constructor
y = b;
[Link]("Child Constructor: " + y);
class Demo {
public static void main(String args[]) {
Child c = new Child(10, 20);
Output
Parent Constructor: 10
Child Constructor: 20
Explanation
• Parent(int a) is the constructor of the base class.
• Child(int a, int b) is the constructor of the derived class.
• super(a) passes the value 10 to the parent constructor.
• The parent constructor executes first, followed by the child constructor.
Important Points About super()
1. super() is used to call the parent class constructor.
2. It must be written as the first statement in the subclass constructor.
3. If no super() is written, Java automatically calls the default constructor of the parent class.
4. It helps initialize parent class data members properly.
Another Example
class Animal {
Animal(String name) {
[Link]("Animal Name: " + name);
class Dog extends Animal {
Dog() {
super("Tommy");
[Link]("Dog Constructor");
class Test {
public static void main(String args[]) {
Dog d = new Dog();
Output:
Animal Name: Tommy
Dog Constructor
Conclusion
A derived class constructor passes arguments to the base class constructor using the super() keyword. This ensures
that the parent class constructor executes first and initializes inherited data members correctly.
Difference Between Abstract Class and Interface in Java
Both abstract class and interface are used to achieve abstraction in Java.
They help define common behavior for classes, but they are different in many ways.
Abstract Class
An abstract class is a class declared with the abstract keyword.
It may contain:
• Abstract methods
• Concrete (normal) methods
• Constructors
• Instance variables
An abstract class cannot be instantiated directly.
Example:
abstract class Animal {
abstract void sound();
void eat() {
[Link]("Animal eats food");
Interface
An interface is a blueprint of a class that contains abstract methods and constants.
A class uses the implements keyword to inherit an interface.
Example:
interface Animal {
void sound();
Difference Between Abstract Class and Interface
Basis Abstract Class Interface
Keyword abstract interface
Methods Can contain abstract and concreteContains
methodsabstract methods by default
Variables Can have normal variables Variables are public static final by default
ConstructorAllowed Not allowed
Basis Abstract Class Interface
Multiple Inheritance
Not supported Supported
Access Modifiers
Methods can have any access modifier
Methods are public by default
Implementation
Partial implementation possible Full abstraction (traditionally)
Inheritanceextends
Keyword implements
Object Creation
Cannot create object directly Cannot create object directly
Speed Faster than interface Slightly slower
Use When classes share common behavior
When unrelated classes need same functionality
Example of Abstract Class
abstract class Shape {
abstract void draw();
void message() {
[Link]("Shape Class");
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
Output:
Drawing Circle
Example of Interface
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
[Link]("Drawing Circle");
Output:
Drawing Circle
When to Use Abstract Class?
Use abstract class when:
• Classes share common properties
• Partial implementation is needed
• Constructors are required
Example:
• Vehicle, Animal, Employee
When to Use Interface?
Use interface when:
• Multiple inheritance is needed
• Only behavior specification is required
• Unrelated classes need common functionality
Example:
• Printable, Runnable, Drawable
Conclusion
Abstract class and interface both provide abstraction in Java, but they are used in different situations.
An abstract class is used when classes share common behavior and implementation, while an interface is used to
define common functionality that can be implemented by multiple unrelated classes.
Why Do We Need Both run() and start() Methods in Multithreading?
In Java multithreading, both start() and run() methods are important, but they perform different tasks.
• start() → creates a new thread
• run() → contains the code executed by the thread
Both methods work together to achieve multithreading.
1. run() Method
The run() method contains the actual task or code that the thread will execute.
Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
The code inside run() defines the work of the thread.
2. start() Method
The start() method is used to start a new thread.
When start() is called:
1. JVM creates a new thread.
2. The thread enters runnable state.
3. JVM automatically calls the run() method.
Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
public static void main(String args[]) {
MyThread t = new MyThread();
[Link]();
}
}
Output:
Thread is running
What Happens if We Call run() Directly?
If run() is called directly:
[Link]();
then:
• No new thread is created.
• The method behaves like a normal method call.
• Multithreading does not occur.
Difference Between start() and run()
start() run()
Creates a new thread
Executes thread code
Calls run() internally
Contains actual task
Performs multithreading
Does not create thread itself
Executed by JVM
Written by programmer
Why Both Methods Are Needed
Need of start()
start() is needed because:
• It creates a separate execution path.
• It allows concurrent execution.
• JVM handles thread scheduling.
Without start(), multithreading cannot happen.
Need of run()
run() is needed because:
• It defines what the thread should do.
• It contains the task logic.
Without run(), the thread has no work to perform.
Execution Flow
start() → JVM creates new thread → run() executes
Example Showing Difference
class Demo extends Thread {
public void run() {
[Link]("Thread executed");
public static void main(String args[]) {
Demo t1 = new Demo();
[Link](); // Normal method call
[Link](); // Creates new thread
Conclusion
Both start() and run() methods are necessary in Java multithreading because:
• start() creates and starts a new thread.
• run() contains the code executed by that thread.
The start() method internally calls the run() method, enabling true concurrent execution in Java.
Uses of super and this Keywords in Java
In Java, this and super are special reference keywords used in Object-Oriented Programming.
• this → refers to the current class object
• super → refers to the immediate parent class object
These keywords are mainly used in constructors, methods, and inheritance.
1. this Keyword in Java
The this keyword refers to the current object of the class.
It is used when the current class variables, methods, or constructors need to be accessed.
Uses of this Keyword
1. To Refer Current Class Instance Variable
Used when local variables and instance variables have the same name.
Example:
class Student {
int id;
Student(int id) {
[Link] = id;
void display() {
[Link](id);
Explanation:
[Link] refers to the instance variable, while id refers to the constructor parameter.
2. To Invoke Current Class Method
this can call another method of the same class.
Example:
class Test {
void show() {
[Link]("Hello");
}
void display() {
[Link]();
3. To Invoke Current Class Constructor
this() is used to call another constructor in the same class.
Example:
class Demo {
Demo() {
this(10);
[Link]("Default Constructor");
Demo(int x) {
[Link](x);
Output:
10
Default Constructor
4. To Pass Current Object as Argument
The current object can be passed to methods or constructors using this.
5. To Return Current Class Object
Example:
class Test {
Test get() {
return this;
}
Conclusion of this
The this keyword is used to:
• Refer current object
• Resolve variable confusion
• Call constructors and methods
• Pass or return current object
2. super Keyword in Java
The super keyword refers to the immediate parent class object.
It is mainly used in inheritance.
Uses of super Keyword
1. To Access Parent Class Variable
Used when parent and child class variables have the same name.
Example:
class Parent {
int x = 10;
class Child extends Parent {
int x = 20;
void show() {
[Link](super.x);
Output:
10
2. To Invoke Parent Class Method
Example:
class Parent {
void show() {
[Link]("Parent Method");
class Child extends Parent {
void show() {
[Link]();
[Link]("Child Method");
Output:
Parent Method
Child Method
3. To Invoke Parent Class Constructor
super() is used to call the constructor of the parent class.
Example:
class Parent {
Parent() {
[Link]("Parent Constructor");
class Child extends Parent {
Child() {
super();
[Link]("Child Constructor");
Output:
Parent Constructor
Child Constructor
Difference Between this and super
this super
Refers to current class Refers
object to parent class object
Used within same classUsed in inheritance
Calls current class constructor
Calls parent class constructor
Accesses current class Accesses
membersparent class members
Final Conclusion
• this keyword is used to refer to the current class object and its members.
• super keyword is used to refer to the parent class object and its members.
Both keywords are important in Java for implementing constructors, inheritance, and object-oriented
programming concepts effectively.
JVM, JRE and JDK in Java
Java is a platform-independent programming language.
Its platform independence is achieved through three important components:
1. JVM (Java Virtual Machine)
2. JRE (Java Runtime Environment)
3. JDK (Java Development Kit)
These components work together to develop and run Java programs.
1. JVM (Java Virtual Machine)
Definition
JVM is a virtual machine that executes Java bytecode.
It acts as an interface between Java program and operating system.
The JVM converts bytecode into machine code so that the computer can understand and execute it.
Working of JVM
Java Source Code (.java)
Compiler
Bytecode (.class)
JVM
Machine Code
Output
Functions of JVM
1. Loads Class Files
JVM loads .class files into memory.
2. Verifies Bytecode
Checks whether bytecode is secure and valid.
3. Executes Bytecode
Converts bytecode into machine language.
4. Memory Management
Allocates and manages memory.
5. Garbage Collection
Removes unused objects automatically.
6. Provides Platform Independence
Same bytecode can run on different operating systems.
Main Components of JVM
JVM
------------------------------------------------
| | | |
Class Loader Memory Area Execution Engine GC
Components Explanation
1. Class Loader
Loads class files into JVM memory.
2. Memory Area
Stores objects, methods, and variables.
3. Execution Engine
Executes bytecode using interpreter and JIT compiler.
4. Garbage Collector
Removes unused objects from heap memory.
2. JRE (Java Runtime Environment)
Definition
JRE is the environment required to run Java programs.
It contains:
• JVM
• Library classes
• Supporting files
JRE does not contain development tools like compiler.
Diagram of JRE
JRE
-------------------------
| |
JVM Java Libraries
Functions of JRE
1. Provides Runtime Environment
Allows Java programs to execute.
2. Contains JVM
Uses JVM for execution.
3. Provides Libraries
Includes predefined Java classes and packages.
4. Supports Platform Independence
Runs Java applications on any operating system.
3. JDK (Java Development Kit)
Definition
JDK is a complete software package used for developing Java applications.
It contains:
• JRE
• JVM
• Development tools
JDK is mainly used by programmers.
Diagram of JDK
JDK
---------------------
| |
JRE Development Tools
JVM
Development Tools in JDK
Tool
Function
javac
Compiles Java source code
java
Runs Java programs
javadoc
Generates documentation
jar
Creates archive files
debugger
Finds errors in programs
Functions of JDK
1. Program Development
Provides tools for writing programs.
2. Compilation
Converts source code into bytecode.
3. Execution
Runs Java applications using JRE and JVM.
4. Debugging
Helps detect and remove errors.
5. Documentation
Generates program documentation.
Relationship Between JVM, JRE and JDK
JDK = JRE + Development Tools
JRE = JVM + Library Files
Complete Architecture Diagram
JDK
--------------------------------
| |
Development Tools JRE
|
-------------------
| |
JVM Java Libraries
Difference Between JVM, JRE and JDK
Feature JVM JRE JDK
Full FormJava VirtualJava
Machine
Runtime Environment
Java Development Kit
Purpose Executes bytecode
Provides runtime environment
Develops Java programs
ContainsExecution engine
JVM + Libraries JRE + Development tools
Used By JVM internally
Users to run apps Programmers
CompilerNo
Included No Yes
Conclusion
JVM, JRE, and JDK are the core components of Java technology.
• JVM executes Java bytecode.
• JRE provides the environment to run Java programs.
• JDK provides tools for developing Java applications.
Together, they make Java secure, portable, and platform independent.
Exception Handling in Java
Exception handling is a mechanism in Java used to handle runtime errors so that the normal flow of the program
can continue.
An exception is an unwanted event that occurs during program execution and interrupts the normal flow of the
program.
Java provides a powerful exception handling mechanism using:
• try
• catch
• finally
• throw
• throws
What is an Exception?
An exception is a runtime error that occurs during execution of a program.
Examples:
• Division by zero
• Array index out of bounds
• File not found
• Null pointer access
Need of Exception Handling
Exception handling is important because it:
• Prevents program termination
• Maintains normal program flow
• Improves reliability
• Helps identify errors properly
Exception Handling Keywords
Keyword
Purpose
try
Contains risky code
catch
Handles exception
finally
Executes always
throw
Explicitly throws exception
throws
Declares exceptions
Flow of Exception Handling
try → Exception Occurs → catch → finally
Example Program of Exception Handling
class Demo {
public static void main(String args[]) {
try {
int a = 10 / 0;
[Link](a);
catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
finally {
[Link]("Program Ended");
Output
Cannot divide by zero
Program Ended
Explanation
try Block
Contains code that may generate exception.
try {
int a = 10 / 0;
catch Block
Handles the exception.
catch (ArithmeticException e)
finally Block
Always executes whether exception occurs or not.
finally {
[Link]("Program Ended");
Types of Exceptions
1. Checked Exceptions
Checked at compile time.
Examples:
• IOException
• SQLException
2. Unchecked Exceptions
Occur at runtime.
Examples:
• ArithmeticException
• NullPointerException
throw Keyword in Java
Definition
The throw keyword is used to explicitly throw an exception.
It is mainly used to create custom exceptions or manually generate exceptions.
Syntax
throw new ExceptionName();
Example of throw
class Test {
public static void main(String args[]) {
int age = 15;
if(age < 18) {
throw new ArithmeticException("Not eligible for voting");
else {
[Link]("Eligible");
Output
Exception in thread "main"
[Link]:
Not eligible for voting
Features of throw
1. Used to throw exception manually
2. Used inside method or block
3. Only one exception can be thrown at a time
4. Used mainly with unchecked exceptions
throws Keyword in Java
Definition
The throws keyword is used to declare exceptions in a method signature.
It informs the programmer that a method may generate certain exceptions.
Syntax
returnType methodName() throws ExceptionName
Example of throws
import [Link].*;
class Demo {
static void readFile() throws IOException {
FileReader f = new FileReader("[Link]");
public static void main(String args[]) {
try {
readFile();
catch(IOException e) {
[Link]("File not found");
Output
File not found
Features of throws
1. Declares exception information
2. Used with method declaration
3. Can declare multiple exceptions
4. Mainly used for checked exceptions
Difference Between throw and throws
throw throws
Used to explicitly throw exception
Used to declare exception
Used inside method body Used in method declaration
Throws single exception at a Can
timedeclare multiple exceptions
Followed by object Followed by class names
Used mainly for unchecked exceptions
Used mainly for checked exceptions
Example Combining throw and throws
class Demo {
static void check(int age) throws ArithmeticException {
if(age < 18) {
throw new ArithmeticException("Under Age");
else {
[Link]("Allowed");
public static void main(String args[]) {
try {
check(15);
catch(ArithmeticException e) {
[Link]([Link]());
}
}
Output
Under Age
Advantages of Exception Handling
1. Prevents abnormal termination
2. Maintains program flow
3. Improves readability
4. Separates error handling code
5. Makes debugging easier
Conclusion
Exception handling in Java is used to manage runtime errors effectively.
Java provides keywords like try, catch, finally, throw, and throws to detect and handle exceptions.
The throw keyword is used to explicitly generate exceptions, while throws is used to declare exceptions in method
definitions.
Role of Stack in Exception Handling in Java
In Java, the stack plays an important role in exception handling.
It helps the Java Virtual Machine (JVM) keep track of method calls, local variables, and exceptions during program
execution.
When an exception occurs, the JVM uses the call stack to locate and handle the exception.
What is Stack?
A stack is a memory area used to store:
• Method calls
• Local variables
• Function execution details
Java uses a structure called the Call Stack or Runtime Stack.
The stack follows the LIFO (Last In, First Out) principle.
Role of Stack in Exception Handling
During exception handling, the stack performs the following functions:
1. Stores method calls
2. Tracks execution flow
3. Searches for exception handlers
4. Performs stack unwinding
How Stack Works During Exception Handling
Step 1: Method Calls are Stored in Stack
Whenever a method is called, a stack frame is created.
Example:
main()
method1()
method2()
Each method is stored in the call stack.
Step 2: Exception Occurs
Suppose an exception occurs inside method2().
Example:
int a = 10 / 0;
An ArithmeticException is generated.
Step 3: JVM Searches for Exception Handler
The JVM checks whether the current method contains a matching catch block.
• If found → exception is handled.
• If not found → exception is passed to the calling method.
Step 4: Stack Unwinding
If no handler exists in the current method, the JVM removes the method from the stack and moves backward.
This process is called stack unwinding.
Diagram:
Before Exception:
main()
method1()
method2()
After Exception:
method2() removed
method1() checked
main() checked
Example Program
class Demo {
static void method1() {
method2();
static void method2() {
int a = 10 / 0;
public static void main(String args[]) {
try {
method1();
}
catch(ArithmeticException e) {
[Link]("Exception Handled");
Output
Exception Handled
Explanation of Stack Working
Stack Execution Flow
main()
method1()
method2()
• Exception occurs in method2()
• JVM checks method2() → no catch block
• Removes method2() from stack
• Checks method1() → no catch block
• Removes method1()
• Checks main() → catch block found
• Exception handled
Stack Trace in Exception Handling
When an exception is not handled, JVM prints a stack trace.
A stack trace shows:
• Exception type
• Method names
• Line numbers
• Sequence of method calls
Example:
Exception in thread "main"
[Link]: / by zero
at Demo.method2([Link])
at Demo.method1([Link])
at [Link]([Link])
Importance of Stack in Exception Handling
1. Tracks method execution
2. Helps locate exception source
3. Supports stack unwinding
4. Assists debugging using stack trace
5. Maintains program execution order
Conclusion
The stack plays a vital role in Java exception handling. It stores method calls and helps the JVM trace exceptions
through stack unwinding. If an exception occurs, the JVM searches the call stack for a matching handler, making
exception management efficient and organized.
Array in Java and Its Working
An array in Java is a collection of similar types of elements stored in contiguous memory locations.
Arrays are used to store multiple values in a single variable instead of declaring separate variables.
Definition of Array
An array is a data structure that stores a fixed number of elements of the same data type.
Example:
Instead of writing:
int a = 10;
int b = 20;
int c = 30;
we can use an array:
int arr[] = {10, 20, 30};
Features of Arrays
1. Stores multiple values of same type
2. Elements are stored in contiguous memory
3. Array size is fixed
4. Accessed using index numbers
5. Index starts from 0
Syntax of Array Declaration
1. Declaration
datatype arrayName[];
or
datatype[] arrayName;
2. Memory Allocation
arrayName = new datatype[size];
3. Combined Declaration and Creation
int arr[] = new int[5];
Example Program of Array
class Demo {
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
for(int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
}
Output
10
20
30
40
50
Working of Array in Java
Step 1: Array Declaration
int arr[];
This creates a reference variable for the array.
Step 2: Array Creation
arr = new int[5];
Memory for 5 integer elements is allocated in heap memory.
Step 3: Initialization
arr[0] = 10;
arr[1] = 20;
Values are stored using index positions.
Internal Working of Array
Index: 0 1 2 3 4
Value: 10 20 30 40 50
Each element is accessed using its index.
Accessing Array Elements
Example:
[Link](arr[2]);
Output:
30
Types of Arrays in Java
1. Single Dimensional Array
Stores elements in one row.
Example:
int arr[] = {1,2,3,4};
2. Multidimensional Array
Stores data in rows and columns.
Example:
int arr[][] = {
{1,2},
{3,4}
};
Example of 2D Array
class Test {
public static void main(String args[]) {
int arr[][] = {
{1,2},
{3,4}
};
for(int i=0; i<2; i++) {
for(int j=0; j<2; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
Output
12
34
Advantages of Arrays
1. Easy storage of multiple values
2. Fast access using index
3. Reduces code size
4. Efficient memory usage
Disadvantages of Arrays
1. Fixed size
2. Stores only same type of elements
3. Insertion and deletion are difficult
Applications of Arrays
• Storing marks of students
• Searching and sorting operations
• Matrix operations
• Implementing data structures like stacks and queues
Conclusion
An array in Java is a collection of similar data elements stored in contiguous memory locations. Arrays help manage
large amounts of data efficiently and allow quick access using indexes. They are widely used in programming for
storing and processing data systematically.
Daemon Thread in Java
A daemon thread is a background thread that runs continuously to provide support services to other threads.
It works in the background and does not prevent the JVM from terminating the program.
When all user threads finish execution, the JVM automatically stops daemon threads.
Definition
A daemon thread is a low-priority thread that runs in the background to perform tasks such as:
• Garbage collection
• Memory management
• Monitoring services
Example:
• Garbage Collector thread in Java is a daemon thread.
Features of Daemon Thread
1. Runs in background
2. Provides services to user threads
3. JVM terminates it automatically
4. Has low priority
5. Cannot keep program alive alone
Creating a Daemon Thread
The method used is:
setDaemon(true);
This method must be called before starting the thread.
Example Program of Daemon Thread
class MyThread extends Thread {
public void run() {
if([Link]().isDaemon()) {
[Link]("Daemon Thread");
else {
[Link]("User Thread");
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link](true);
[Link]();
[Link]();
Output
Daemon Thread
User Thread
Important Points About Daemon Thread
1. setDaemon(true) makes a thread daemon.
2. Must be called before start().
3. isDaemon() checks whether thread is daemon or not.
4. JVM stops daemon threads automatically after all user threads end.
Thread Priority in Java
Every thread in Java has a priority that helps the thread scheduler decide the execution order.
Higher priority threads generally get more CPU time.
Priority Range
Thread priority ranges from:
1 → Minimum Priority
5 → Normal Priority
10 → Maximum Priority
Constant Values
Constant Value
Thread.MIN_PRIORITY
1
Thread.NORM_PRIORITY
5
Thread.MAX_PRIORITY
10
Setting Thread Priority
The method used is:
setPriority(int priority);
Syntax
[Link](value);
Example Program of Thread Priority
class MyThread extends Thread {
public void run() {
[Link](
[Link]().getName()
+ " Priority: "
+ [Link]().getPriority()
);
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
[Link](2);
[Link](5);
[Link](8);
[Link]();
[Link]();
[Link]();
Possible Output
Thread-0 Priority: 2
Thread-1 Priority: 5
Thread-2 Priority: 8
Getting Thread Priority
Use:
getPriority();
Example
[Link]([Link]().getPriority());
Advantages of Thread Priority
1. Better CPU scheduling
2. Improves performance
3. Important tasks can execute earlier
Conclusion
A daemon thread is a background service thread that supports user threads and terminates automatically when all
user threads finish execution. Thread priority determines the importance of a thread and can be set using the
setPriority() method to control thread scheduling and execution order.
String Class in Java
The String class in Java is used to create and manipulate sequences of characters.
A string represents textual data such as names, messages, or sentences.
In Java, strings are objects of the String class available in the [Link] package.
Definition
A String is a collection of characters enclosed within double quotation marks.
Example:
String name = "Java";
Features of String Class
1. Strings are objects in Java
2. Strings are immutable (cannot be changed)
3. Stored in String Constant Pool
4. Provides many built-in methods
5. Used widely for text processing
Creating Strings in Java
1. Using String Literal
String s1 = "Hello";
2. Using new Keyword
String s2 = new String("Hello");
Immutable Nature of String
Once a string object is created, its value cannot be modified.
Example:
String s = "Java";
[Link](" Programming");
[Link](s);
Output:
Java
The original string remains unchanged.
Common Methods of String Class
The String class contains many useful methods for string manipulation.
1. length() Method
Purpose
Returns the total number of characters in a string.
Syntax
[Link]();
Example
class Demo {
public static void main(String args[]) {
String s = "Java";
[Link]([Link]());
Output
4
2. toUpperCase() Method
Purpose
Converts all characters of a string into uppercase.
Syntax
[Link]();
Example
class Test {
public static void main(String args[]) {
String s = "java";
[Link]([Link]());
Output
JAVA
3. toLowerCase() Method
Purpose
Converts all characters into lowercase.
Example
class Demo {
public static void main(String args[]) {
String s = "JAVA";
[Link]([Link]());
Output
java
4. charAt() Method
Purpose
Returns the character present at a specified index.
Syntax
[Link](index);
Example
class Demo {
public static void main(String args[]) {
String s = "Java";
[Link]([Link](2));
Output
5. concat() Method
Purpose
Joins two strings together.
Syntax
[Link](string2);
Example
class Demo {
public static void main(String args[]) {
String s1 = "Java";
String s2 = " Programming";
[Link]([Link](s2));
}
Output
Java Programming
Other Important String Methods
Method
Purpose
equals()
Compares two strings
compareTo()
Compares strings lexicographically
substring()
Extracts part of string
trim()
Removes extra spaces
replace()
Replaces characters
contains()
Checks specific text
Example Program Using Multiple Methods
class StringDemo {
public static void main(String args[]) {
String s = "Java Programming";
[Link]("Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Character at 5: " + [Link](5));
[Link]("Substring: " + [Link](5));
Output
Length: 16
Uppercase: JAVA PROGRAMMING
Lowercase: java programming
Character at 5: P
Substring: Programming
Advantages of String Class
1. Easy text manipulation
2. Provides many built-in methods
3. Secure due to immutability
4. Widely used in applications
Conclusion
The String class in Java is used to handle textual data efficiently. It provides many built-in methods for string
manipulation such as length(), charAt(), concat(), toUpperCase(), and toLowerCase(). Because strings are
immutable, they are secure and reliable for programming applications.
Difference Between Method Overloading and Method Overriding in Java
Method Overloading and Method Overriding are important concepts of Polymorphism in Java.
• Method Overloading → Same method name with different parameters in the same class.
• Method Overriding → Same method in parent and child class with same parameters.
Both improve code reusability and flexibility, but they work differently.
1. Method Overloading
Definition
Method Overloading occurs when multiple methods in the same class have:
• Same method name
• Different parameter lists
The difference may be in:
• Number of parameters
• Type of parameters
• Order of parameters
Example of Method Overloading
class Addition {
int add(int a, int b) {
return a + b;
int add(int a, int b, int c) {
return a + b + c;
double add(double a, double b) {
return a + b;
public static void main(String args[]) {
Addition obj = new Addition();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
Output
30
60
31.0
Explanation
Here:
• add(int,int)
• add(int,int,int)
• add(double,double)
all have the same name but different parameters.
This is called method overloading.
Features of Method Overloading
1. Occurs within same class
2. Same method name
3. Different parameter list
4. No inheritance required
5. Achieves compile-time polymorphism
2. Method Overriding
Definition
Method Overriding occurs when a child class provides a new implementation of a method already defined in the
parent class.
The method must have:
• Same name
• Same parameters
• Same return type
Example of Method Overriding
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
Output
Dog barks
Explanation
• Parent class method: sound()
• Child class method: sound()
The child class changes the implementation of the parent method.
This is called method overriding.
Features of Method Overriding
1. Requires inheritance
2. Same method signature
3. Same return type
4. Achieves runtime polymorphism
5. Child class provides new implementation
Difference Between Method Overloading and Method Overriding
Method Overloading Method Overriding
Same method name with different parameters
Same method name and same parameters
Occurs in same class Occurs in parent and child class
Inheritance not required Inheritance required
Compile-time polymorphism Runtime polymorphism
Methods can have different return types
Return type should be same
Increases readability Provides specific implementation
Key Points
Method Overloading
• Improves code readability
• Supports multiple ways to perform same task
Method Overriding
• Supports dynamic method dispatch
• Provides runtime flexibility
Conclusion
Method Overloading and Method Overriding are both forms of polymorphism in Java.
• Method Overloading allows multiple methods with the same name but different parameters
within the same class.
• Method Overriding allows a subclass to redefine a parent class method with the same
signature.
Both concepts are essential for flexible and reusable object-oriented programming in Java.
Constructor in Java
A constructor in Java is a special member function used to initialize objects of a class.
It is automatically called when an object is created.
The main purpose of a constructor is to initialize data members of the object.
Characteristics of Constructor
1. Constructor name must be same as class name
2. It has no return type, not even void
3. Called automatically when object is created
4. Used to initialize objects
5. Constructors can be overloaded
Syntax of Constructor
class ClassName {
ClassName() {
// constructor body
Example of Constructor
class Student {
int id;
String name;
Student() {
id = 101;
name = "Rahul";
void display() {
[Link](id + " " + name);
public static void main(String args[]) {
Student s = new Student();
[Link]();
Output
101 Rahul
Types of Constructors in Java
Java mainly provides two types of constructors:
1. Default Constructor
2. Parameterized Constructor
Additionally:
• Copy constructor concept can also be implemented manually.
1. Default Constructor
Definition
A constructor with no parameters is called a default constructor.
It initializes objects with default values.
Example of Default Constructor
class Demo {
int x;
Demo() {
x = 10;
void show() {
[Link](x);
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
Output
10
2. Parameterized Constructor
Definition
A constructor that accepts parameters is called a parameterized constructor.
It initializes objects using user-defined values.
Example of Parameterized Constructor
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
void display() {
[Link](id + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student(101, "Aman");
Student s2 = new Student(102, "Rahul");
[Link]();
[Link]();
Output
101 Aman
102 Rahul
3. Copy Constructor (User Defined)
Java does not provide built-in copy constructors like C++, but we can create one manually.
Example of Copy Constructor
class Test {
int id;
String name;
Test(int i, String n) {
id = i;
name = n;
Test(Test t) {
id = [Link];
name = [Link];
void display() {
[Link](id + " " + name);
public static void main(String args[]) {
Test t1 = new Test(101, "Java");
Test t2 = new Test(t1);
[Link]();
[Link]();
Output
101 Java
101 Java
Does Java Provide a Default Constructor?
Yes, Java provides a default constructor automatically.
If the programmer does not create any constructor, the Java compiler automatically creates a default constructor.
This constructor:
• Has no parameters
• Initializes variables with default values
Example Showing Compiler-Provided Default Constructor
class Demo {
int x;
String name;
void display() {
[Link](x);
[Link](name);
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
Output
null
Explanation
Since no constructor is written:
• Java compiler automatically provides a default constructor.
• int gets default value 0
• String gets default value null
Important Point
If the programmer creates any constructor manually, the compiler does not provide the default constructor
automatically.
Difference Between Default and Parameterized Constructor
Default Constructor Parameterized Constructor
No parameters Has parameters
Initializes default values Initializes user-defined values
Created automatically if no constructor
Mustexists
be created by programmer
Advantages of Constructors
1. Automatically initializes objects
2. Reduces code complexity
3. Improves readability
4. Supports object-oriented programming
Conclusion
A constructor in Java is a special method used to initialize objects. Java supports default and parameterized
constructors, and copy constructors can also be created manually. If no constructor is defined, Java automatically
provides a default constructor to initialize objects with default values.
Purpose of Static Block, Static Variable, and Static Method in Java
In Java, the static keyword is used for memory management and sharing common data among objects.
When a member is declared static, it belongs to the class rather than individual objects.
static can be used with:
1. Variables
2. Methods
3. Blocks
1. Static Variable in Java
Definition
A variable declared with the static keyword is called a static variable or class variable.
Only one copy of the static variable is created and shared among all objects of the class.
Purpose of Static Variable
• To save memory
• To share common data among all objects
• To store class-level information
Example of Static Variable
class Student {
int rollno;
String name;
static String college = "ABC College";
Student(int r, String n) {
rollno = r;
name = n;
void display() {
[Link](rollno + " " + name + " " + college);
public static void main(String args[]) {
Student s1 = new Student(1, "Rahul");
Student s2 = new Student(2, "Aman");
[Link]();
[Link]();
}
Output
1 Rahul ABC College
2 Aman ABC College
Explanation
The variable college is static, so:
• Only one memory location is created.
• All objects share the same value.
Features of Static Variable
1. Shared among all objects
2. Memory allocated only once
3. Created when class loads
4. Accessed using class name
2. Static Method in Java
Definition
A method declared with the static keyword is called a static method.
It belongs to the class and can be called without creating an object.
Purpose of Static Method
• To access static data directly
• To perform common operations
• To avoid object creation for utility methods
Example of Static Method
class Demo {
static void show() {
[Link]("Static Method");
}
public static void main(String args[]) {
[Link]();
Output
Static Method
Features of Static Method
1. Called using class name
2. No object required
3. Can access only static members directly
4. Main method is static
Important Rule
A static method cannot directly access non-static members because non-static members belong to objects.
3. Static Block in Java
Definition
A block declared with the static keyword is called a static block.
It executes automatically when the class is loaded into memory.
Purpose of Static Block
• To initialize static variables
• To perform one-time setup operations
• To execute code before main() method
Example of Static Block
class Test {
static {
[Link]("Static Block Executed");
public static void main(String args[]) {
[Link]("Main Method Executed");
Output
Static Block Executed
Main Method Executed
Explanation
The static block executes first because it runs during class loading.
Features of Static Block
1. Executes automatically
2. Runs before main() method
3. Executes only once
4. Used for static initialization
Order of Execution in Java
Static Variable → Static Block → main() Method
Difference Between Static Variable, Method, and Block
Static Variable
Static Method Static Block
Stores shared
Performs
data class-level operations
Initializes static data
Static Variable
Static Method Static Block
Shared by all
Called
objects
without objectExecutes automatically
Created once
Belongs to class Runs once during class loading
Advantages of Static Members
1. Saves memory
2. Improves performance
3. Easy access using class name
4. Useful for common operations
Conclusion
The static keyword in Java is used to create class-level members shared by all objects.
• Static variables store common data.
• Static methods perform class-related operations.
• Static blocks initialize static resources during class loading.
These features improve memory efficiency and program organization in Java.
Method Overriding with Covariant Return Type in Java
Method overriding occurs when a subclass provides its own implementation of a method already defined in the
parent class.
Normally, while overriding:
• Method name must be same
• Parameters must be same
• Return type should also be same
However, Java allows a special feature called Covariant Return Type.
What is Covariant Return Type?
A covariant return type means that the overridden method in the child class can return:
• The same return type, or
• A subclass type of the parent method’s return type
This feature was introduced in Java 5.
Definition
Covariant return type allows an overriding method to return an object of the child class instead of the parent class
type.
Syntax
ParentClass methodName()
can be overridden as:
ChildClass methodName()
where ChildClass is derived from ParentClass.
Example Without Covariant Return Type
class A {
A show() {
return this;
class B extends A {
A show() {
return this;
Here both methods return type A.
Example With Covariant Return Type
class Animal {
Animal get() {
[Link]("Animal Class");
return this;
class Dog extends Animal {
Dog get() {
[Link]("Dog Class");
return this;
void message() {
[Link]("Covariant Return Type");
class Test {
public static void main(String args[]) {
Dog d = new Dog();
[Link]().message();
Output
Dog Class
Covariant Return Type
Explanation
• Parent class method get() returns type Animal
• Child class method get() returns type Dog
• Since Dog is a subclass of Animal, overriding is valid
This is called covariant return type.
How Method Overriding is Achieved with Covariant Return Type
Step 1: Create Parent Class Method
Animal get()
Step 2: Override in Child Class
Dog get()
Step 3: Return Child Class Object
The child method returns its own object type.
This provides:
• More specific return values
• Better readability
• Improved flexibility
Advantages of Covariant Return Type
1. Improves code readability
2. Reduces type casting
3. Provides specific object return
4. Enhances runtime polymorphism
Important Rules
1. Applicable only in method overriding
2. Return types must have inheritance relationship
3. Primitive data types are not allowed
4. Works only with object references
Example Showing Inheritance Relationship
Animal
Dog
Since Dog is derived from Animal, returning Dog is allowed.
Difference Between Normal Return Type and Covariant Return Type
Normal Return Type
Covariant Return Type
Same return type Child
required
return type allowed
Less flexible More flexible
Requires casting sometimes
Reduces casting
Conclusion
Covariant return type is a feature in Java that allows an overridden method in a subclass to return a subclass type
instead of the parent class type. It improves flexibility, readability, and supports better implementation of runtime
polymorphism in method overriding.
Characteristics of Abstract Class in Java
An abstract class in Java is a class declared using the abstract keyword.
It is used to achieve abstraction, which means hiding implementation details and showing only essential features.
An abstract class may contain:
• Abstract methods
• Normal methods
• Constructors
• Variables
Abstract classes are mainly used as base classes in inheritance.
Definition
An abstract class is a class that cannot be instantiated directly and may contain abstract as well as non-abstract
methods.
Syntax of Abstract Class
abstract class ClassName {
abstract void methodName();
void display() {
[Link]("Normal Method");
Characteristics of Abstract Class
1. Declared Using abstract Keyword
An abstract class must be declared using the abstract keyword.
Example:
abstract class Animal {
2. Cannot Be Instantiated
Objects of abstract classes cannot be created directly.
Invalid Example:
Animal a = new Animal(); // Error
Reason:
Abstract classes are incomplete classes.
3. Can Contain Abstract Methods
An abstract class may contain abstract methods (methods without body).
Example:
abstract void sound();
These methods must be implemented by subclasses.
4. Can Contain Concrete Methods
Abstract classes can also contain normal methods with body.
Example:
void eat() {
[Link]("Animal eats");
5. Supports Constructors
Abstract classes can have constructors.
Constructors are called when subclass objects are created.
Example:
abstract class Animal {
Animal() {
[Link]("Abstract Class Constructor");
6. Supports Variables
Abstract classes can contain:
• Instance variables
• Static variables
• Final variables
Example:
abstract class Test {
int x = 10;
}
7. Supports Method Overriding
Subclasses override abstract methods of abstract class.
8. Used for Partial Abstraction
Abstract classes provide partial abstraction because:
• Some methods may have body
• Some methods may be abstract
9. Supports Inheritance
Abstract classes are inherited using the extends keyword.
Example:
class Dog extends Animal {
10. May or May Not Contain Abstract Methods
An abstract class can exist without abstract methods.
Example:
abstract class Demo {
void show() {
[Link]("Hello");
Complete Example of Abstract Class
abstract class Shape {
abstract void draw();
void message() {
[Link]("This is Shape Class");
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
public static void main(String args[]) {
Circle c = new Circle();
[Link]();
[Link]();
Output
Drawing Circle
This is Shape Class
Explanation of Program
• Shape is an abstract class.
• draw() is an abstract method.
• message() is a concrete method.
• Circle class inherits Shape.
• Circle provides implementation of draw().
Real-Life Example of Abstract Class
Vehicle → abstract class
Car, Bike → child classes
Common features are defined in abstract class, while specific behavior is implemented in subclasses.
Advantages of Abstract Class
1. Achieves abstraction
2. Improves code reusability
3. Supports inheritance
4. Reduces code duplication
5. Provides partial abstraction
Limitations of Abstract Class
1. Cannot create objects directly
2. Does not support multiple inheritance completely
Difference Between Abstract Class and Concrete Class
Abstract Class Concrete Class
Cannot be instantiated
Can be instantiated
May contain abstractContains
methodsonly complete methods
Used for abstraction Used for object creation
Conclusion
An abstract class in Java is used to achieve abstraction and inheritance. It acts as a blueprint for other classes and
can contain both abstract and concrete methods. Abstract classes improve code organization, reusability, and
flexibility in object-oriented programming.
Inheritance in Java
Inheritance is an important feature of Object-Oriented Programming (OOP) in Java.
It allows one class to acquire the properties and behaviors of another class.
The class whose properties are inherited is called the Parent/Base/Super class, and the class that inherits those
properties is called the Child/Derived/Sub class.
Java uses the extends keyword for inheritance.
Definition
Inheritance is the process by which one class acquires the data members and methods of another class.
Advantages of Inheritance
1. Code reusability
2. Reduces code duplication
3. Improves maintainability
4. Supports method overriding
5. Helps achieve polymorphism
Syntax of Inheritance
class Parent {
class Child extends Parent {
Types of Inheritance in Java
Java mainly supports the following types of inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (through interfaces)
5. Hybrid Inheritance (through interfaces)
1. Single Inheritance
Definition
When one child class inherits one parent class, it is called single inheritance.
Diagram
Parent
Child
Example
class Animal {
void eat() {
[Link]("Animal eats food");
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
Output
Animal eats food
Dog barks
2. Multilevel Inheritance
Definition
When a class inherits another class, and that class is further inherited by another class, it is called multilevel
inheritance.
Diagram
Grandparent
Parent
Child
Example
class Animal {
void eat() {
[Link]("Animal eats");
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
class Puppy extends Dog {
void weep() {
[Link]("Puppy weeps");
public static void main(String args[]) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
Output
Animal eats
Dog barks
Puppy weeps
3. Hierarchical Inheritance
Definition
When multiple child classes inherit the same parent class, it is called hierarchical inheritance.
Diagram
Animal
/ \
Dog Cat
Example
class Animal {
void eat() {
[Link]("Animal eats");
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
class Cat extends Animal {
void meow() {
[Link]("Cat meows");
class Test {
public static void main(String args[]) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output
Animal eats
Dog barks
Animal eats
Cat meows
4. Multiple Inheritance in Java
Definition
When one class inherits more than one parent class, it is called multiple inheritance.
Java does not support multiple inheritance using classes because of ambiguity problems.
However, Java supports multiple inheritance through interfaces.
Diagram
Parent1 Parent2
\ /
Child
Example Using Interfaces
interface A {
void show();
interface B {
void display();
class Demo implements A, B {
public void show() {
[Link]("Interface A");
public void display() {
[Link]("Interface B");
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
[Link]();
Output
Interface A
Interface B
5. Hybrid Inheritance
Definition
Hybrid inheritance is a combination of two or more inheritance types.
Java supports hybrid inheritance only through interfaces.
Diagram
/ \
B C
\ /
D
Important Points About Inheritance
1. Java uses extends keyword for class inheritance.
2. Constructors are not inherited.
3. Private members are not directly accessible.
4. Inheritance supports method overriding.
Use of super Keyword in Inheritance
The super keyword is used to access parent class members.
Example:
[Link]();
Real-Life Example of Inheritance
Vehicle
Car
SportsCar
Conclusion
Inheritance in Java is a mechanism through which one class acquires the properties and methods of another class.
It improves code reusability, maintainability, and supports polymorphism. Java supports single, multilevel,
hierarchical, multiple (through interfaces), and hybrid inheritance.