0% found this document useful (0 votes)
0 views79 pages

java

The document outlines the core concepts of Object-Oriented Programming (OOP) in Java, focusing on encapsulation, inheritance, polymorphism, and abstraction. It explains the structure and purpose of classes and objects, constructors, and methods, providing examples for clarity. Additionally, it discusses the use of the 'this' keyword and constructor overloading to enhance code functionality and maintainability.

Uploaded by

Gowtham Gowthu
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)
0 views79 pages

java

The document outlines the core concepts of Object-Oriented Programming (OOP) in Java, focusing on encapsulation, inheritance, polymorphism, and abstraction. It explains the structure and purpose of classes and objects, constructors, and methods, providing examples for clarity. Additionally, it discusses the use of the 'this' keyword and constructor overloading to enhance code functionality and maintainability.

Uploaded by

Gowtham Gowthu
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/ 79

Core Concepts of Java OOP

Java's OOP is built around four main pillars:

1. Encapsula on

o Bundles data (fields) and methods that operate on that data into a single unit
(class).

o Access modifiers (private, public, etc.) control visibility.

o Example: Using ge ers and se ers to access private fields.

2. Inheritance

o Enables a class (child) to inherit proper es and behaviors from another class
(parent).

o Promotes code reuse and logical hierarchy.

o Syntax: class Dog extends Animal

3. Polymorphism

o Allows objects to be treated as instances of their parent class.

o Two types: Compile- me (method overloading) and Run me (method


overriding).

o Example: A Shape class with a draw() method overridden by Circle, Square, etc.

4. Abstrac on

o Hides internal implementa on and shows only essen al features.

o Achieved using abstract classes and interfaces.

o Example: interface Vehicle { void accelerate(); }

Sample Java Class

java

class Student {

private String name;

private int age;


public Student(String name, int age) {

this.name = name;

this.age = age;

public void displayInfo() {

System.out.println("Name: " + name + ", Age: " + age);

This class demonstrates encapsula on and abstrac on. You can extend it to include inheritance
and polymorphism.

Java Classes & Objects

What Is a Class?

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

 It contains fields (variables) and methods (func ons).

 It does not consume memory un l an object is created.

 Example: A Car class might define a ributes like color, speed, and methods like drive() or
brake().

class Car {

String color;

int speed;

void drive() {

System.out.println("Driving at " + speed + " km/h");


}

What Is an Object?

An object is an instance of a class.

 It has a state (values of fields) and behavior (methods).

 You create objects using the new keyword.

 Example:

public class Main {

public sta c void main(String[] args) {

Car myCar = new Car();

myCar.color = "Red";

myCar.speed = 120;

myCar.drive(); // Output: Driving at 120 km/h

Key Differences

Feature Class Object

Defini on Blueprint/template Instance of a class

Memory No memory un l instan ated Occupies memory

Purpose Defines structure and behavior Represents real-world en ty

The Three OOPs Principle.

1. Encapsula on

 Defini on: Bundling data and methods that operate on that data within a single unit
(class).
 Purpose: Protects internal state by restric ng direct access—only exposing what’s
necessary.

 Example: Using private fields with public ge ers and se ers in Java.

 Benefit: Enhances security and reduces unintended interference.

2. Inheritance

 Defini on: Allows one class (child) to inherit fields and methods from another class
(parent).

 Purpose: Promotes code reuse and logical hierarchy.

 Example: class Dog extends Animal inherits behavior like eat() or sleep().

 Benefit: Reduces redundancy and simplifies code maintenance.

3. Polymorphism

 Defini on: Enables objects to take on many forms depending on context.

 Types:

o Compile- me: Method overloading (same method name, different parameters).

o Run me: Method overriding (subclass redefines parent method).

 Purpose: Allows flexibility in code behavior.

 Example: A Shape class with a draw() method overridden by Circle, Square, etc.

 Benefit: Makes code extensible and dynamic.

Introducing Classes: Class fundamentals, General form of a class, A simple class

Class Fundamentals

A class in Java is a blueprint for crea ng objects. It defines the state (fields/variables) and
behavior (methods/func ons) that the objects will have.

 State: Represented by variables (e.g., int age, String name)

 Behavior: Represented by methods (e.g., void speak(), int calculate())

General Form of a Class

Here’s the typical structure of a Java class:


java

access_modifier class ClassName {

// Fields (data members)

dataType variableName;

// Constructor

ClassName(parameters) {

// Ini aliza on code

// Methods (member func ons)

returnType methodName(parameters) {

// Method body

Components Explained:

 access_modifier: Usually public, private, or default (no modifier)

 ClassName: Should start with a capital le er by conven on

 Fields: Variables that hold data

 Constructor: Special method to ini alize objects

 Methods: Define ac ons or behaviors

A Simple Class Example

Let’s create a class called Student that stores a student’s name and age and displays their info.

java

public class Student {

// Fields
String name;

int age;

// Constructor

public Student(String studentName, int studentAge) {

name = studentName;

age = studentAge;

// Method

public void displayInfo() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

// Main method to run the program

public sta c void main(String[] args) {

Student s1 = new Student("Gowtham", 21);

s1.displayInfo();

What’s Happening Here:

 We define a class Student with two fields: name and age.

 The constructor ini alizes these fields when an object is created.

 The displayInfo() method prints the student’s details.

 In main(), we create an object s1 and call its method.


Declaring object, Assigning object reference variables

Declaring an Object

Declaring an object means crea ng a reference variable that can point to an instance of a class.

java

Class Name obj; // Declara on only

 This does not create the object itself.

 It simply tells the compiler that obj will refer to an object of type Class Name.

Assigning an Object (Instan a ng)

To actually create the object and assign it to the reference variable, use the new keyword:

java

obj = new Class Name(); // Assignment

Or combine both steps:

java

Class Name obj = new Class Name(); // Declara on + Assignment

This creates a new object in memory and assigns its reference to obj.

Assigning Object Reference Variables

You can assign one object reference to another:

java

ClassName obj1 = new ClassName();

ClassName obj2 = obj1; // obj2 now refers to the same object as obj1

 Both obj1 and obj2 point to the same memory loca on.

 Changes made through one reference affect the same object.

Example:

java

class Student {

String name;
}

public class Main {

public sta c void main(String[] args) {

Student s1 = new Student();

s1.name = "Gowtham";

Student s2 = s1; // s2 refers to the same object as s1

s2.name = "Raj"; // modifies the same object

System.out.println(s1.name); // Output: Raj

Key Concepts

Concept Descrip on

Declara on Creates a reference variable

Instan a on Allocates memory for the object using new

Assignment Links the reference variable to the object

Reference Sharing Mul ple variables can point to the same object

Null Reference A reference variable can be set to null to indicate no object is linked

Introducing methods, Adding a method to the box class, Returning a Value, Returning a method
that takes parameter

1. Introducing Methods in Java

A method is a block of code that performs a specific task. It helps organize code, promote reuse,
and improve readability.
Method Syntax

access_modifier return_type method_name(parameters) {

// method body

 access_modifier: public, private, etc.

 return_type: int, double, void, etc.

 method_name: descrip ve name (e.g., calculateVolume)

 parameters: input values (op onal)

2. Adding a Method to the Box Class

Let’s define a Box class and add a method to calculate its volume.

class Box {

double width;

double height;

double depth;

// Method to calculate volume

double volume() {

return width * height * depth;

This method uses the instance variables to compute and return the volume.

3. Returning a Value from a Method

A method can return a value using the return keyword. The returned value must match the
method’s declared return type.

Example

double volume() {
return width * height * depth;

 volume() returns a double value.

 You can use this value in other parts of your program:

java

Box b = new Box();

b.width = 2;

b.height = 3;

b.depth = 4;

System.out.println("Volume: " + b.volume()); // Output: Volume: 24.0

4. Returning a Method That Takes Parameters

You can define methods that accept parameters and return a value. This makes your class more
flexible.

Example: Method with Parameters

double calculateVolume(double w, double h, double d) {

return w * h * d;

 This method doesn’t rely on instance variables.

 You can call it like this:

Box b = new Box();

System.out.println("Calculated Volume: " + b.calculateVolume(2, 3, 4)); // Output: 24.0

Summary Table

Method Type Descrip on Example

No parameters, returns Uses instance variables double volume()


value
With parameters, returns Accepts input and computes double calculateVolume(w, h,
value result d)

Void method Performs ac on but returns void displayVolume()


nothing

// Box.java

class Box {

// Fields

double width;

double height;

double depth;

// Default Constructor

public Box() {

width = 0;

height = 0;

depth = 0;

// Parameterized Constructor

public Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}
// Method to calculate volume using instance variables

public double volume() {

return width * height * depth;

// Overloaded method to calculate volume using parameters

public double volume(double w, double h, double d) {

return w * h * d;

// Method to display dimensions and volume

public void displayInfo() {

System.out.println("Width: " + width);

System.out.println("Height: " + height);

System.out.println("Depth: " + depth);

System.out.println("Volume (instance): " + volume());

}// Main.java

public class Main {

public sta c void main(String[] args) {

// Create a Box using default constructor and assign values manually

Box box1 = new Box();

box1.width = 2.5;

box1.height = 3.0;

box1.depth = 4.0;
// Create a Box using parameterized constructor

Box box2 = new Box(5.0, 6.0, 7.0);

// Display info for box1

System.out.println("Box 1 Details:");

box1.displayInfo();

System.out.println();

// Display info for box2

System.out.println("Box 2 Details:");

box2.displayInfo();

System.out.println();

// Use overloaded method with parameters

double customVolume = box2.volume(1.5, 2.0, 3.5);

System.out.println("Custom volume using parameters: " + customVolume);

Constructor

What Is a Constructor?

A constructor is a special method in Java used to ini alize objects when they’re created. Unlike
regular methods:

 It has no return type (not even void)

 Its name matches the class name

 It’s automa cally called when an object is instan ated using new
Syntax of a Constructor

java

class ClassName {

ClassName() {

// constructor body

Why Use Constructors?

 To set ini al values for object a ributes

 To ensure the object is in a valid state before use

 To avoid wri ng separate ini aliza on methods

Types of Constructors

Type Descrip on Example Usage

Default Constructor No parameters; sets default values Box b = new Box();

Parameterized Accepts parameters to ini alize fields Box b = new Box(2,


Constructor 3, 4);

Copy Constructor Takes another object of the same class and Box b2 = new
copies its data Box(b1);

Example: Default & Parameterized Constructors

java

class Box {

double width, height, depth;

// Default constructor

Box() {

width = height = depth = 1;


}

// Parameterized constructor

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

double volume() {

return width * height * depth;

Copy Constructor Example

class Box {

double width, height, depth;

// Copy constructor

Box(Box b) {

width = b.width;

height = b.height;

depth = b.depth;

Java doesn’t provide a built-in copy constructor like C++, but you can define one manually as
shown above.
Constructor Overloading

You can define mul ple constructors in the same class with different parameter lists:

class Student {

String name;

int age;

Student() {

name = "Unknown";

age = 0;

Student(String n) {

name = n;

age = 18;

Student(String n, int a) {

name = n;

age = a;

This Keyword

In Java, the this keyword is a reference to the current object—the one whose method or
constructor is being invoked. It’s incredibly useful for resolving naming conflicts, chaining
constructors, and passing the current object as a parameter.
Let’s break it down with clarity and examples:

Why Use this?

 To dis nguish between instance variables and parameters with the same name

 To invoke another constructor in the same class

 To pass the current object to a method or constructor

 To return the current object from a method

1. Referring to Instance Variables

java

class Student {

String name;

Student(String name) {

this.name = name; // 'this.name' refers to the instance variable

Without this, name = name; would assign the parameter to itself—not the instance variable.

2. Constructor Chaining with this()

java

class Box {

double width, height, depth;

Box() {

this(1, 1, 1); // Calls the parameterized constructor

Box(double w, double h, double d) {


width = w;

height = h;

depth = d;

This avoids code duplica on and ensures consistent ini aliza on.

3. Passing this as a Method Argument

java

class Printer {

void print(Student s) {

System.out.println("Student name: " + s.name);

class Student {

String name = "Gowtham";

void show() {

Printer p = new Printer();

p.print(this); // Passes current object

4. Returning the Current Object

class Student {

String name;
Student setName(String name) {

this.name = name;

return this; // Enables method chaining

Limita ons

 You cannot use this in sta c methods, because sta c methods belong to the class, not
any object.

 Overusing this can clu er code if not needed.

Garbage Collec on

What Is Garbage Collec on?

Garbage Collec on is the process of reclaiming memory occupied by objects that are no longer
reachable or needed by the program.

 Java uses automa c memory management via the JVM.

 You don’t need to manually delete objects (unlike C/C++).

 GC runs in the background and frees up heap memory.

How It Works

Garbage Collec on typically follows these steps:

1. Marking

o JVM iden fies which objects are s ll in use (reachable).

2. Dele on/Sweeping

o Unreachable objects are removed from memory.

3. Compac ng

o Frees up fragmented memory blocks to op mize space.

Example
java

class Student {

String name;

Student(String name) {

this.name = name;

public class Demo {

public sta c void main(String[] args) {

Student s1 = new Student("Gowtham");

s1 = null; // s1 is now eligible for garbage collec on

System.gc(); // Requests GC (not guaranteed to run immediately)

Types of Garbage Collectors

Collector Type Descrip on

Serial GC Single-threaded, simple, pauses applica on during cleanup

Parallel GC Mul -threaded, good for throughput, may cause longer pauses

CMS (Concurrent) Minimizes pause me, deprecated in Java 14

G1 GC Default in Java 8+, balances pause me and performance

ZGC / Shenandoah Low-latency collectors for large heaps (Java 11+)

You can explore more on GeeksforGeeks' GC guide or Java Code Geeks' tutorial.

Making Objects Eligible for GC


 Nullifying references: obj = null;

 Reassigning references: obj = new Object();

 Objects created inside methods: Automa cally eligible a er method ends

 Island of Isola on: Group of objects referencing each other but not reachable from
outside

Deprecated: finalize() Method

 Used to perform cleanup before GC

 Deprecated since Java 9 due to unpredictability

 Prefer try-with-resources or AutoCloseable for cleanup

The finalize method

What Was finalize()?

 It was a protected method defined in the Object class.

 Automa cally called by the Garbage Collector (GC) when it determined an object was
unreachable.

 Used to release resources like file handles, database connec ons, or network sockets.

java

@Override

protected void finalize() throws Throwable {

System.out.println("Finalize method called");

super.finalize(); // Op onal: calls superclass finalize

Example Usage

java

class Demo {

String name;
Demo(String name) {

this.name = name;

@Override

protected void finalize() throws Throwable {

System.out.println("Cleaning up: " + name);

public class Test {

public sta c void main(String[] args) {

Demo d = new Demo("Gowtham");

d = null; // Eligible for GC

System.gc(); // Suggests GC to run

Output (if GC runs): Cleaning up: Gowtham

Why It Was Deprecated

 Unpredictable: No guarantee when or even if finalize() would be called.

 Performance hit: GC had to track finalizable objects separately.

 Risky: Excep ons in finalize() were ignored, and misuse could lead to memory leaks or
crashes.

 Be er alterna ves:

o try-with-resources for automa c cleanup


o AutoCloseable interface

o java.lang.ref.Cleaner (introduced in Java 9)

Overloading methods

What Is Method Overloading?

 Defini on: Mul ple methods in the same class share the same name but differ in:

o Number of parameters

o Type of parameters

o Order of parameters

 Purpose: To perform similar opera ons with different inputs, improving code readability
and reusability.

Example: Overloaded sum() Method

java

class Calculator {

// Sum of two integers

int sum(int a, int b) {

return a + b;

// Sum of three integers

int sum(int a, int b, int c) {

return a + b + c;

// Sum of two doubles

double sum(double a, double b) {


return a + b;

public class Main {

public sta c void main(String[] args) {

Calculator calc = new Calculator();

System.out.println(calc.sum(10, 20)); // Output: 30

System.out.println(calc.sum(10, 20, 30)); // Output: 60

System.out.println(calc.sum(10.5, 20.5)); // Output: 31.0

Ways to Overload Methods

Technique Example Signature

Change number of parameters sum(int a, int b) vs sum(int a, int b, int c)

Change data types of parameters sum(int a, int b) vs sum(double a, double b)

Change order of parameters print(String name, int age) vs print(int age, String name)

Note: You cannot overload methods by changing only the return type. The parameter list
must differ.

Common Pi alls

 Overloading with only different return types causes compile- me errors.

 Ambiguity can arise if type promo on (e.g., int to long) leads to mul ple valid matches.

Benefits

 Improves code clarity and organiza on

 Enables flexible method usage


 Supports polymorphic behavior at compile me

Overloading Constructor

What Is Constructor Overloading?

 It’s a form of compile- me polymorphism.

 You define mul ple constructors in the same class, each with a different signature.

 The Java compiler chooses the appropriate constructor based on the arguments passed
during object crea on.

Why Use Constructor Overloading?

 To create objects with different levels of detail.

 To provide default values or custom ini aliza on.

 To avoid wri ng mul ple ini aliza on methods.

Example: Overloaded Constructors in a Box Class

java

class Box {

double width, height, depth;

// Constructor with all dimensions

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

// Constructor for a cube

Box(double len) {
width = height = depth = len;

// Default constructor

Box() {

width = height = depth = 0;

double volume() {

return width * height * depth;

java

public class Main {

public sta c void main(String[] args) {

Box box1 = new Box(10, 20, 15); // Full dimensions

Box box2 = new Box(7); // Cube

Box box3 = new Box(); // Default

System.out.println("Volume of box1: " + box1.volume()); // 3000.0

System.out.println("Volume of box2: " + box2.volume()); // 343.0

System.out.println("Volume of box3: " + box3.volume()); // 0.0

Constructor Chaining with this()

You can use this() to call one constructor from another:


java

class Student {

String name;

int age;

Student() {

this("Unknown", 0); // Calls the parameterized constructor

Student(String name, int age) {

this.name = name;

this.age = age;

this() must be the first statement in the constructor body.

Benefits of Constructor Overloading

 Enhances code flexibility

 Improves readability and maintainability

 Supports mul ple ini aliza on paths

Recursion

What Is Recursion?

 A recursive method solves a problem by calling itself with modified parameters.

 It must include a base case to stop the recursion and prevent infinite loops.

 Think of it like Russian nes ng dolls—each call opens a smaller version of the same
problem.
Structure of a Recursive Method

java

returnType methodName(parameters) {

if (baseCondi on) {

return result; // stopping condi on

} else {

return methodName(modifiedParameters); // recursive call

Example 1: Factorial Using Recursion

java

public class RecursionDemo {

sta c int factorial(int n) {

if (n <= 1) return 1; // base case

return n * factorial(n - 1); // recursive call

public sta c void main(String[] args) {

System.out.println("Factorial of 5: " + factorial(5)); // Output: 120

Example 2: Fibonacci Series

java

sta c int fibonacci(int n) {

if (n <= 1) return n; // base case

return fibonacci(n - 1) + fibonacci(n - 2); // recursive call


}

How Recursion Works (Behind the Scenes)

 Each recursive call is placed on the call stack.

 When the base case is reached, the stack unwinds and returns values back up.

 If the base case is missing or unreachable, it leads to a StackOverflowError.

Recursion vs Itera on

Feature Recursion Itera on

Style Elegant, mathema cal Straigh orward, loop-based

Memory Uses more (stack frames) Uses less

Speed Slower (due to func on calls) Faster

Use Cases Trees, graphs, divide-and-conquer Simple loops, coun ng

When to Use Recursion

 When the problem can be broken into smaller subproblems.

 When working with hierarchical data (trees, graphs).

 When the itera ve solu on is complex or less readable.

Inheritance basics

Inheritance in Java is a founda onal concept in Object-Oriented Programming (OOP) that allows
one class to acquire the proper es and behaviors of another. It promotes code reuse,
modularity, and polymorphism, making your programs more organized and efficient.

What Is Inheritance?

 Superclass (Parent Class): The class whose members (fields and methods) are inherited.

 Subclass (Child Class): The class that inherits from the superclass.

 Keyword: extends is used to establish inheritance.

java

class Animal {
void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

In this example, Dog inherits the eat() method from Animal.

Benefits of Inheritance

 Code Reusability: Share common logic across mul ple classes.

 Method Overriding: Customize inherited methods in the subclass.

 Polymorphism: Treat objects of different subclasses uniformly.

 Hierarchy: Organize classes in a logical structure.

Types of Inheritance in Java

Java supports several inheritance types:

Type Descrip on

Single Inheritance One subclass inherits from one superclass

Mul level A subclass inherits from a class that itself inherits another class

Hierarchical Mul ple subclasses inherit from a single superclass

Mul ple Achieved via interfaces (not classes)

Hybrid Combina on of the above, using interfaces

single inheritance
Single inheritance in Java is the simplest form of inheritance, where one subclass inherits from
one superclass. It establishes an "is-a" rela onship, allowing the child class to reuse the
proper es and behaviors of the parent class.

What Is Single Inheritance?

 A child class inherits fields and methods from a single parent class.

 Promotes code reusability and modular design.

 Syntax:

java

class Parent {

void greet() {

System.out.println("Hello from Parent");

class Child extends Parent {

void sayHi() {

System.out.println("Hi from Child");

public class Main {

public sta c void main(String[] args) {

Child obj = new Child();

obj.greet(); // Inherited method

obj.sayHi(); // Child's own method

}
}

Key Concepts

Term Meaning

extends Keyword used to inherit a class

Superclass The parent class being inherited

Subclass The child class that inherits the superclass

super Keyword to refer to superclass members

mul level inheritance

Mul level inheritance in Java is a type of inheritance where a class inherits from a class that
itself inherits from another class—forming a chain of inheritance. It’s like a family tree:
Grandparent → Parent → Child. This structure promotes code reuse, hierarchical organiza on,
and method overriding across levels.

What Is Mul level Inheritance?

In mul level inheritance:

 Class C inherits from class B

 Class B inherits from class A

 Class C gets access to members of both A and B

java

class A {

void methodA() {

System.out.println("Class A method");

class B extends A {

void methodB() {
System.out.println("Class B method");

class C extends B {

void methodC() {

System.out.println("Class C method");

public class Demo {

public sta c void main(String[] args) {

C obj = new C();

obj.methodA(); // inherited from A

obj.methodB(); // inherited from B

obj.methodC(); // defined in C

Key Concepts

Term Meaning

extends Used to inherit a class

Constructor Chain Superclass constructors are called first, then subclass constructors

Method Overriding Subclass can redefine inherited methods

Access Control public and protected members are inherited; private are not

Hierarchical inheritance
Hierarchical inheritance in Java is a type of inheritance where mul ple subclasses inherit from
a single superclass. It’s like having one parent class that passes down its traits to several child
classes—each child gets the shared features but can also have its own unique behaviors.

What Is Hierarchical Inheritance?

 Superclass: Contains common proper es and methods.

 Subclasses: Each subclass extends the same superclass and inherits its members.

 Promotes code reuse, modularity, and polymorphism.

Example:

java

class Animal {

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks.");

class Cat extends Animal {

void meow() {

System.out.println("Cat meows.");

}
public class Main {

public sta c void main(String[] args) {

Dog d = new Dog();

d.eat(); // inherited from Animal

d.bark(); // Dog-specific

Cat c = new Cat();

c.eat(); // inherited from Animal

c.meow(); // Cat-specific

Key Benefits

 Code Reusability: Shared logic lives in the superclass.

 Scalability: Easy to add new subclasses without duplica ng code.

 Polymorphism: Subclasses can override superclass methods for custom behavior.

hybrid inheritance

Hybrid inheritance in Java is a combina on of two or more types of inheritance—like single,


mul level, hierarchical, or mul ple (via interfaces). While Java doesn’t support mul ple
inheritance with classes (to avoid ambiguity like the diamond problem), it does support hybrid
inheritance through a mix of classes and interfaces.

What Is Hybrid Inheritance?

Hybrid inheritance blends different inheritance models to create a complex class hierarchy. For
example:

 Class A is extended by Class B and Class C (hierarchical)

 Class D extends Class B (single)


 If interfaces are involved, it can simulate mul ple inheritance

This structure allows for maximum code reuse, modularity, and flexibility.

Example: Hybrid Inheritance Using Interfaces

java

interface Readable {

void read();

interface Writable {

void write();

class Document {

void open() {

System.out.println("Document opened.");

class TextDocument extends Document implements Readable, Writable {

public void read() {

System.out.println("Reading text document.");

public void write() {

System.out.println("Wri ng to text document.");

}
}

Here:

 TextDocument inherits from Document (single inheritance)

 Implements Readable and Writable (mul ple inheritance via interfaces)

 This is a hybrid inheritance structure

mul ple inheritance

Mul ple inheritance in Java is a nuanced topic—Java does not support mul ple inheritance
with classes, but it does support it through interfaces. Let’s break it down clearly and explore
why this design choice was made, how it works, and how you can implement it.

Why Java Doesn’t Support Mul ple Inheritance with Classes

Java’s creators inten onally rejected mul ple inheritance to avoid ambiguity and complexity,
especially the infamous diamond problem.

 Diamond Problem: If two parent classes have a method with the same signature, and a
child class inherits both, the compiler won’t know which method to use.

 This leads to confusion, method conflicts, and maintenance nightmares.

How Java Achieves Mul ple Inheritance Using Interfaces

Java allows a class to implement mul ple interfaces, which is a form of mul ple inheritance—
without the ambiguity.

java

interface Printable {

default void print() {

System.out.println("Prin ng...");

interface Scannable {
default void scan() {

System.out.println("Scanning...");

class Mul Func onMachine implements Printable, Scannable {

public void operate() {

print();

scan();

What Happens When Interfaces Have Conflic ng Default Methods?

If two interfaces have default methods with the same signature, the implemen ng class must
override the method to resolve the conflict.

java

interface A {

default void show() {

System.out.println("A");

interface B {

default void show() {

System.out.println("B");

}
class C implements A, B {

public void show() {

A.super.show(); // or B.super.show()

Method overriding

Method overriding in Java is a key feature of run me polymorphism, allowing a subclass to


provide a specific implementa on of a method already defined in its superclass. Let’s break it
down with clarity and examples:

What Is Method Overriding?

 A subclass redefines a method from its parent class.

 The method must have the same name, return type, and parameter list.

 The overridden method is called based on the object type, not the reference type.

java

class Animal {

void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

System.out.println("Dog barks");
}

java

public class Main {

public sta c void main(String[] args) {

Animal a = new Dog();

a.sound(); // Output: Dog barks

Rules of Method Overriding

 Must be in a subclass.

 Method signature must match exactly.

 Cannot override sta c, final, or private methods.

 Access modifier must be equal or more visible.

 Use @Override annota on to catch mistakes.

Dynamic method dispatch

Dynamic Method Dispatch in Java is the mechanism that enables run me polymorphism—
where the method that gets executed is determined at run me, not compile me. It’s a
cornerstone of Java’s object-oriented capabili es, especially when working with method
overriding and inheritance.

What Is Dynamic Method Dispatch?

 It allows a superclass reference to call overridden methods in a subclass.

 The actual method that gets executed depends on the object type, not the reference
type.

 This is also known as run me polymorphism.

java
class Animal {

void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

public class Demo {

public sta c void main(String[] args) {

Animal a = new Dog(); // superclass reference to subclass object

a.sound(); // Output: Dog barks

Even though a is of type Animal, the method from Dog is executed because the object is a Dog.

Using abstract classes

Using abstract classes in Java is a powerful way to enforce a common structure across related
classes while allowing flexibility in implementa on. Let’s break it down with clarity, examples,
and prac cal guidance.

What Is an Abstract Class?

An abstract class is a class that:


 Cannot be instan ated directly.

 Is declared using the abstract keyword.

 Can contain both abstract methods (without a body) and concrete methods (with a
body).

 Serves as a blueprint for subclasses.

java

abstract class Animal {

abstract void makeSound(); // abstract method

void sleep() { // concrete method

System.out.println("Sleeping...");

How to Use Abstract Classes

1. Define an abstract class with shared behavior.

2. Declare abstract methods that must be implemented by subclasses.

3. Extend the abstract class in concrete subclasses.

4. Implement the abstract methods in those subclasses.

java

class Dog extends Animal {

@Override

void makeSound() {

System.out.println("Dog barks");

Using final with inheritance


In Java, the final keyword plays a crucial role in controlling inheritance and method behavior.
When used with inheritance, it helps enforce immutability, security, and design constraints.
Let’s break it down clearly:

1. Final with Classes: Preven ng Inheritance

Declaring a class as final means no other class can extend it.

java

final class Vehicle {

void start() {

System.out.println("Vehicle star ng...");

// This will cause a compile- me error

class Car extends Vehicle { // ERROR: Cannot inherit from final class

void drive() {

System.out.println("Car driving...");

Final Keyword in Java Full Tutorial - Final Classes, Methods ... explains when and why to
use final classes, especially for security and immutability.

2. Final with Methods: Preven ng Overriding

A final method can be inherited but cannot be overridden in a subclass.

java

class Parent {

final void show() {

System.out.println("Final method in Parent");

}
}

class Child extends Parent {

// Cannot override final method

// void show() { System.out.println("Trying to override"); }

#57 Final keyword in java demonstrates how final methods block overriding and ensure
consistent behavior across subclasses.

Final Keyword In Java Tutorial #89 walks through final methods and shows how they
interact with inheritance.

3. Final with Variables: Preven ng Reassignment

Final variables cannot be changed once assigned—even in subclasses.

java

class Parent {

final String message = "Hello from Parent";

class Child extends Parent {

// Cannot reassign 'message'

// message = "Hello from Child"; // Compile- me error

Packages

In Java, packages are a way to organize classes and interfaces into logical groups, making your
codebase cleaner, more modular, and easier to manage. Think of them like folders in your
computer that separate different types of files.

What Are Packages?


A package is a namespace that groups related classes and interfaces. Java has two main types:

 Built-in packages: Provided by Java (e.g., java.u l, java.io, java.lang)

 User-defined packages: Created by developers to organize their own code

Packages help:

 Avoid naming conflicts

 Control access levels

 Improve code reusability

 Simplify project structure

How to Create a Package

java

package mypackage;

public class MyClass {

public void display() {

System.out.println("Hello from MyClass in mypackage");

 Save this file as MyClass.java inside a folder named mypackage

 Compile using: javac -d . MyClass.java

 Run using: java mypackage.MyClass

7.10 What are Packages in Java explains how to create packages, import them, and their
structure with clear visuals.

How to Import Packages

You can import packages using the import keyword:

java

import java.u l.Scanner; // imports Scanner class

import java.u l.*; // imports all classes in java.u l


Imports & Packages | Java | Tutorial 38 walks through impor ng classes from different
packages and using them in your code.

Example: Using Built-in Package

java

import java.u l.Scanner;

public class InputExample {

public sta c void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = sc.nextLine();

System.out.println("Hello, " + name);

Access Protec on

Access protec on in Java is all about controlling who can access what in your code. It’s a key
part of encapsula on, helping you safeguard internal data and expose only what’s necessary.
Java achieves this using access modifiers: private, default (package-private), protected, and
public.

The Four Access Modifiers

Modifier Accessible Within Same Subclass (Other Everywhere


Class Package Package)

private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes

Access Protec on in Prac ce

Let’s say you have a class BankAccount:


java

public class BankAccount {

private double balance; // Only accessible within this class

protected String accountType; // Accessible in subclasses and same package

String branchCode; // Default access (package-private)

public String accountHolder; // Accessible from anywhere

public double getBalance() {

return balance; // Controlled access via ge er

This setup ensures:

 Sensi ve data (balance) is hidden.

 Shared logic (accountType) is available to subclasses.

 Internal details (branchCode) stay within the package.

 Public info (accountHolder) is globally accessible.

Interfaces

In Java, an interface is like a contract that defines a set of methods a class must implement—
without specifying how those methods should work. It’s a powerful tool for achieving
abstrac on, mul ple inheritance, and loose coupling in your programs.

What Is an Interface?

 An interface contains abstract methods (no body) and constants.

 Classes use the implements keyword to adopt an interface.

 Interfaces cannot be instan ated directly.

 All methods are implicitly public and abstract; all variables are public sta c final.
java

interface Vehicle {

void start();

void stop();

Implemen ng an Interface

java

class Car implements Vehicle {

public void start() {

System.out.println("Car started");

public void stop() {

System.out.println("Car stopped");

Mul ple Inheritance with Interfaces

Java doesn’t support mul ple inheritance with classes, but it does with interfaces:

java

interface Flyable {

void fly();

interface Swimmable {

void swim();

}
class Duck implements Flyable, Swimmable {

public void fly() { System.out.println("Duck flies"); }

public void swim() { System.out.println("Duck swims"); }

Interface vs Abstract Class

Feature Interface Abstract Class

Instan a on Not allowed Not allowed

Method Types Abstract, default, sta c Abstract and concrete

Variables public sta c final only Instance and sta c allowed

Mul ple Inheritance Yes No

Default and Sta c Methods (Java 8+)

Interfaces can now include methods with bodies:

java

interface SmartDevice {

default void connect() {

System.out.println("Connec ng...");

sta c void reset() {

System.out.println("Rese ng...");

Default interface methods


Default interface methods in Java were introduced in Java 8 to solve a major problem: how to
add new methods to interfaces without breaking exis ng implementa ons. Before Java 8,
interfaces could only contain abstract methods, meaning every implemen ng class had to
define them. Default methods changed that.

What Is a Default Method?

A default method is a method in an interface that has a body—it provides a default


implementa on.

java

interface Vehicle {

void start(); // abstract method

default void horn() {

System.out.println("Beep beep!");

 start() must be implemented by any class that implements Vehicle.

 horn() is op onal—classes can use it as-is or override it.

Why Were Default Methods Introduced?

 To support backward compa bility when adding new methods to interfaces.

 To enable func onal programming features like lambda expressions.

 To avoid forcing all implemen ng classes to update when an interface changes.

Example: Using Default Methods

java

interface Printer {

void print();

default void status() {


System.out.println("Printer is online.");

class InkjetPrinter implements Printer {

public void print() {

System.out.println("Prin ng with inkjet...");

java

public class Main {

public sta c void main(String[] args) {

Printer p = new InkjetPrinter();

p.print(); // Output: Prin ng with inkjet...

p.status(); // Output: Printer is online.

Use sta c method interface.

In Java, sta c methods in interfaces were introduced in Java 8 to allow interfaces to include
u lity-style behavior without requiring implemen ng classes to define or override them.
These methods belong to the interface itself, not to any instance, and are called using the
interface name.

Syntax of a Sta c Method in an Interface

java

interface U lity {

sta c void greet() {


System.out.println("Hello from sta c method in interface!");

 You call it like this: U lity.greet();

 You cannot override it in implemen ng classes.

 It’s useful for helper methods, valida on, or calcula ons related to the interface.

Example: Sta c Method in Interface

java

interface MathOpera ons {

sta c int square(int x) {

return x * x;

void operate();

class Calculator implements MathOpera ons {

public void operate() {

System.out.println("Performing opera on...");

public class Main {

public sta c void main(String[] args) {

Calculator calc = new Calculator();

calc.operate();
// Calling sta c method from interface

int result = MathOpera ons.square(5);

System.out.println("Square of 5: " + result);

Excep on Handling Fundamentals

Excep on handling in Java is a core mechanism for managing run me errors gracefully,
ensuring your program doesn’t crash unexpectedly. Let’s break down the fundamentals with
clarity and prac cal examples:

What Is an Excep on?

An excep on is an event that disrupts the normal flow of a program. It typically occurs due to:

 Invalid user input

 File not found

 Division by zero

 Null references

 Array index out of bounds

Java categorizes excep ons into:

 Checked excep ons: Must be handled at compile me (e.g., IOExcep on,


SQLExcep on)

 Unchecked excep ons: Occur at run me and don’t require mandatory handling (e.g.,
NullPointerExcep on, Arithme cExcep on)

Basic Syntax: try-catch-finally

java

try {

// Code that might throw an excep on


} catch (Excep onType e) {

// Code to handle the excep on

} finally {

// Code that always runs (op onal)

 try: Wraps risky code

 catch: Handles specific excep ons

 finally: Executes cleanup code regardless of excep ons

Throwing and Declaring Excep ons

 throw: Used to explicitly throw an excep on

 throws: Declares excep ons a method might throw

java

void readFile(String path) throws IOExcep on {

throw new IOExcep on("File not found");

Example: Handling Arithme cExcep on

java

public class Demo {

public sta c void main(String[] args) {

try {

int result = 10 / 0;

} catch (Arithme cExcep on e) {

System.out.println("Cannot divide by zero!");

} finally {

System.out.println("Execu on complete.");

}
}

Best Prac ces

 Catch specific excep ons first

 Avoid empty catch blocks

 Use finally for resource cleanup

 Prefer custom excep ons for domain-specific errors

Excep on Types

Java excep ons are categorized into three main types: checked excep ons, unchecked
excep ons, and errors. Each plays a dis nct role in how your program handles unexpected
situa ons. Let’s break them down with examples and video tutorials to reinforce your
understanding:

1. Checked Excep ons

These are checked at compile me. If not handled properly, your code won’t compile.

Examples:

 IOExcep on: Issues during input/output opera ons

 SQLExcep on: Problems with database access

 FileNotFoundExcep on: File not found on disk

Sample:

java

public void readFile(String path) throws IOExcep on {

FileReader fr = new FileReader(path);

2. Unchecked Excep ons

These occur at run me and are not checked during compila on. They usually indicate
programming errors.
Examples:

 NullPointerExcep on: Accessing a method on a null object

 Arithme cExcep on: Division by zero

 ArrayIndexOutOfBoundsExcep on: Invalid array index

Sample:

java

int result = 10 / 0; // Arithme cExcep on

3. Errors

These are serious issues that applica ons should not try to catch. They o en indicate
problems with the JVM or system resources.

Examples:

 OutOfMemoryError: JVM runs out of memory

 StackOverflowError: Excessive recursion

 VirtualMachineError: JVM internal failure

Excep on Hierarchy Overview

Throwable

├── Excep on

│ ├── Checked Excep ons

│ └── Unchecked Excep ons (Run meExcep on)

└── Error

Uncaught Excep on

In Java, an uncaught excep on is an excep on that occurs during program execu on but is not
handled by any try-catch block. When this happens, the Java Virtual Machine (JVM) steps in
and typically:

 Prints a stack trace to the console


 Terminates the thread (or the en re program if it's the main thread)

Common Causes of Uncaught Excep ons

 Unchecked excep ons like NullPointerExcep on, Arithme cExcep on, or


ArrayIndexOutOfBoundsExcep on

 Missing or incomplete try-catch blocks

 Excep ons in threads that aren’t handled by the main thread

Java Excep on Handling-Finally Clause,Stack Trace,and ... explains how uncaught


excep ons behave when try-catch is missing and how the stack trace helps in debugging.

Uncaught Excep ons in Threads

In mul threaded applica ons, uncaught excep ons in a thread don’t crash the whole
program—but they do terminate that thread. To handle this, Java provides the
UncaughtExcep onHandler interface.

java

Thread.setDefaultUncaughtExcep onHandler(new Thread.UncaughtExcep onHandler() {

public void uncaughtExcep on(Thread t, Throwable e) {

System.out.println("Caught excep on from thread: " + t.getName());

e.printStackTrace();

});

Example: Uncaught Arithme cExcep on

java

public class Demo {

public sta c void main(String[] args) {

int result = 10 / 0; // Uncaught Arithme cExcep on

System.out.println("Result: " + result);

}
Using try and catch

Using try and catch in Java is the founda on of excep on handling, allowing you to gracefully
manage run me errors without crashing your program. Let’s break it down with examples,
rules, and video tutorials to make it crystal clear:

Basic Structure

java

try {

// Code that might throw an excep on

} catch (Excep onType e) {

// Code to handle the excep on

 try: Wraps risky code (e.g., division, file access, array indexing)

 catch: Handles the excep on if one occurs

Example: Handling Division by Zero

java

public class Demo {

public sta c void main(String[] args) {

try {

int result = 10 / 0;

} catch (Arithme cExcep on e) {

System.out.println("Cannot divide by zero!");

Mul ple Catch Blocks


You can catch different excep ons separately:

java

try {

int[] arr = new int[3];

System.out.println(arr[5]); // ArrayIndexOutOfBoundsExcep on

} catch (Arithme cExcep on e) {

System.out.println("Arithme c error");

} catch (ArrayIndexOutOfBoundsExcep on e) {

System.out.println("Array index error");

Nested Try-Catch

You can nest try-catch blocks to handle excep ons at different levels:

java

try {

try {

int res = 10 / 0;

} catch (Arithme cExcep on e) {

System.out.println("Inner catch: " + e);

String s = null;

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

} catch (NullPointerExcep on e) {

System.out.println("Outer catch: " + e);

}
Mul ple catch clauses

In Java, mul ple catch clauses allow you to handle different types of excep ons separately
within a single try block. This is essen al when your code might throw more than one kind of
excep on, and you want to respond differently depending on the error.

Syntax: Mul ple Catch Blocks

java

try {

// risky code

} catch (Arithme cExcep on e) {

System.out.println("Arithme c error");

} catch (ArrayIndexOutOfBoundsExcep on e) {

System.out.println("Array index error");

} catch (Excep on e) {

System.out.println("General error");

Only one catch block executes—the first one that matches the thrown excep on.

Example

java

public class Demo {

public sta c void main(String[] args) {

try {

int[] arr = new int[3];

arr[5] = 10 / 0; // May throw Arithme cExcep on or


ArrayIndexOutOfBoundsExcep on

} catch (Arithme cExcep on e) {

System.out.println("Arithme c Excep on");

} catch (ArrayIndexOutOfBoundsExcep on e) {
System.out.println("Array Index Out Of Bounds Excep on");

} catch (Excep on e) {

System.out.println("General Excep on");

Java 7+: Mul -Catch Block

You can combine mul ple excep ons in a single catch block using the | symbol:

java

try {

// risky code

} catch (Arithme cExcep on | ArrayIndexOutOfBoundsExcep on e) {

System.out.println("Excep on occurred: " + e);

Nested try Statements

Nested try statements in Java allow you to handle excep ons at mul ple levels of granularity,
making your code more robust and readable when dealing with complex opera ons. Let’s
break it down with examples, rules, and video tutorials to reinforce your understanding:

What Are Nested Try Statements?

A nested try block is a try block placed inside another try block. Each block can have its own
catch (and op onally finally) to handle excep ons specific to that level.

java

try {

// Outer try block

try {

// Inner try block


} catch (InnerExcep on e) {

// Handle inner excep on

} catch (OuterExcep on e) {

// Handle outer excep on

Example: File Reading and Parsing

java

try {

Scanner scanner = new Scanner(new File("data.txt"));

try {

String data = scanner.nextLine();

int value = Integer.parseInt(data); // May throw NumberFormatExcep on

System.out.println("Parsed value: " + value);

} catch (NumberFormatExcep on e) {

System.out.println("Invalid number format!");

} finally {

scanner.close(); // Always executed

} catch (FileNotFoundExcep on e) {

System.out.println("File not found!");

throws, finally, Java Built-in Excep ons

throws Keyword
The throws keyword is used in a method declara on to indicate that the method might throw
one or more excep ons. It’s a way of delega ng excep on handling to the method caller.

Syntax

java

public void readFile(String path) throws IOExcep on {

// risky code

Key Points

 Used for checked excep ons (e.g., IOExcep on, SQLExcep on)

 Appears in the method signature

 Forces the caller to handle or declare the excep on

Example

java

public class Demo {

public sta c void riskyMethod() throws InterruptedExcep on {

Thread.sleep(1000); // may throw InterruptedExcep on

public sta c void main(String[] args) {

try {

riskyMethod();

} catch (InterruptedExcep on e) {

System.out.println("Handled: " + e);

}
finally Block

The finally block is used to guarantee execu on of cleanup code, regardless of whether an
excep on occurs or not.

Syntax

java

try {

// risky code

} catch (Excep on e) {

// handle excep on

} finally {

// always executed

Use Cases

 Closing files, streams, or database connec ons

 Releasing resources

 Logging or final messages

Example

java

public class Demo {

public sta c void main(String[] args) {

try {

int result = 10 / 0;

} catch (Arithme cExcep on e) {

System.out.println("Caught: " + e);

} finally {

System.out.println("Cleanup done.");
}

Java Built-in Excep ons

Java provides a rich set of built-in excep ons to handle common error scenarios. These are
part of the java.lang package and are divided into:

Checked Excep ons

Handled at compile me:

 IOExcep on

 SQLExcep on

 ClassNotFoundExcep on

Unchecked Excep ons

Handled at run me:

 Arithme cExcep on

 NullPointerExcep on

 ArrayIndexOutOfBoundsExcep on

 NumberFormatExcep on

Example: NullPointerExcep on

java

public class Demo {

public sta c void main(String[] args) {

String str = null;

System.out.println(str.length()); // throws NullPointerExcep on

}
Crea ng Your Own Excep on Subclasses

Crea ng your own excep on subclasses in Java—also known as custom excep ons—is a
powerful way to handle applica on-specific errors with clarity and control. Let’s walk through
how and why to do it, with examples and tutorials to guide you:

Why Create Custom Excep ons?

 To represent domain-specific errors (e.g., InvalidAgeExcep on,


ItemNotFoundExcep on)

 To provide clear, descrip ve messages for debugging

 To encapsulate business logic viola ons in a meaningful way

How to Create a Custom Excep on

You can create a custom excep on by extending either:

 Excep on → for checked excep ons

 Run meExcep on → for unchecked excep ons

Example: Checked Excep on

java

class InvalidAgeExcep on extends Excep on {

public InvalidAgeExcep on(String message) {

super(message);

java

public class AgeValidator {

public sta c void validate(int age) throws InvalidAgeExcep on {

if (age < 18) {

throw new InvalidAgeExcep on("Age must be 18 or above.");

System.out.println("Valid age: " + age);


}

public sta c void main(String[] args) {

try {

validate(15);

} catch (InvalidAgeExcep on e) {

System.out.println("Caught Excep on: " + e.getMessage());

Example: Unchecked Excep on

java

class DivideByZeroExcep on extends Run meExcep on {

public DivideByZeroExcep on(String message) {

super(message);

public class Calculator {

public sta c void divide(int a, int b) {

if (b == 0) {

throw new DivideByZeroExcep on("Division by zero is not allowed.");

System.out.println("Result: " + (a / b));

}
public sta c void main(String[] args) {

divide(10, 0);

Chained Excep on

Chained excep ons in Java are a powerful feature that allow you to link one excep on to
another, helping you trace the root cause of an error more effec vely. This is especially useful
in complex applica ons where one failure leads to another.

What Is a Chained Excep on?

A chained excep on occurs when one excep on is caused by another. Instead of losing the
original error, you can a ach it to the new one using:

 Throwable(Throwable cause)

 Throwable(String message, Throwable cause)

 initCause(Throwable cause)

 getCause()

What Are Chained Excep ons?: Java Excep on Handling explains the concept clearly and
shows how chaining helps preserve the original excep on context.

Example: Chaining Excep ons

java

public class ChainedDemo {

public sta c void main(String[] args) {

try {

try {

int result = 10 / 0; // Arithme cExcep on

} catch (Arithme cExcep on e) {

throw new Run meExcep on("Calcula on failed", e);


}

} catch (Run meExcep on ex) {

System.out.println("Caught: " + ex);

System.out.println("Cause: " + ex.getCause());

Three Recently Added Excep on Features.

1. Try-With-Resources

This feature automates resource management—like closing files, streams, or sockets—


without needing a finally block.

How it works:

java

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {

System.out.println(br.readLine());

} catch (IOExcep on e) {

e.printStackTrace();

 The resource (br) is automa cally closed a er the try block.

 Works with any class that implements AutoCloseable.

Excep on Handling in Java explains how try-with-resources simplifies cleanup and


reduces boilerplate code.

2. Mul -Catch Block

Instead of wri ng mul ple catch blocks for different excep ons with iden cal handling logic,
you can combine them using the | operator.
Example:

java

try {

int result = 10 / 0;

int[] arr = new int[5];

System.out.println(arr[10]);

} catch (Arithme cExcep on | ArrayIndexOutOfBoundsExcep on e) {

System.out.println("Excep on caught: " + e);

 Reduces code duplica on.

 The excep on variable e is implicitly final.

[JAVA NEW FEATURE] handling mul ple excep ons inside a ... demonstrates how to use
mul -catch effec vely with real examples.

3. More Precise Rethrow (a.k.a. Final Rethrow)

This feature allows the compiler to infer the specific excep on types that can be rethrown
from a catch block, improving type safety.

Example:

java

void process() throws IOExcep on, SQLExcep on {

try {

// risky code

} catch (Excep on e) {

throw e; // compiler knows only IOExcep on or SQLExcep on can be thrown

 Works when the caught excep on is effec vely final (not reassigned).
 Helps avoid overly broad throws Excep on declara ons.

The Java Thread Model

The Java Thread Model is the founda on of Java’s mul threading capabili es, enabling
programs to perform mul ple tasks concurrently. It’s designed to be robust, efficient, and
scalable, especially in environments where responsiveness and resource sharing are cri cal.

Core Concepts of the Java Thread Model

 Thread: A lightweight sub-process that runs independently within a program.

 Mul threading: Running mul ple threads simultaneously to achieve parallelism.

 Thread Scheduler: Manages thread execu on based on priority and availability.

 Context Switching: The process of switching CPU control between threads.

Java Thread Model explains how Java’s run me system uses threads to eliminate polling
loops and improve CPU efficiency, especially in asynchronous environments.

Thread Life Cycle

Java threads transi on through several states:

State Descrip on

New Thread is created but not started

Runnable Thread is ready to run and wai ng for CPU me

Running Thread is ac vely execu ng

Blocked Wai ng to acquire a lock

Wai ng Wai ng indefinitely for another thread to signal

Timed Wai ng Wai ng for a specified me (e.g., sleep(), join( meout))

Terminated Thread has completed execu on or was stopped


The Main Thread

In Java, the main thread is the first thread that starts when a Java applica on begins
execu on. It’s the thread that runs the main() method and serves as the entry point for your
program’s logic. Think of it as the conductor of an orchestra—it kicks things off and can spawn
other threads to perform tasks concurrently.

Key Characteris cs of the Main Thread

 Automa cally created by the JVM when the program starts

 Executes the main() method

 Has a default priority of 5

 Can create and manage child threads

 O en the last to finish, handling shutdown tasks

Understanding of Main thread in Java explains how the main thread is ini alized and its
role in managing other threads.

Example: Accessing and Controlling the Main Thread

java

public class MainThreadDemo {

public sta c void main(String[] args) {

Thread t = Thread.currentThread();

System.out.println("Current thread: " + t.getName());

t.setName("SuperMainThread");
System.out.println("Thread name changed to: " + t.getName());

System.out.println("Thread priority: " + t.getPriority());

try {

System.out.println("Main thread sleeping...");

Thread.sleep(2000);

System.out.println("Main thread woke up!");

} catch (InterruptedExcep on e) {

System.out.println("Main thread interrupted!");

Lifecycle of the Main Thread

Phase Descrip on

Start JVM creates the main thread

Execute Runs the main() method

Spawn Can create child threads

Terminate Ends when main() completes or System.exit() is called

Crea ng a Thread

Crea ng a thread in Java is the gateway to mul threading, allowing your program to perform
mul ple tasks concurrently. Java offers several ways to create threads, each suited to different
use cases. Let’s break them down with examples and tutorials to guide you:

1. Extending the Thread Class

This is the most direct method. You create a class that extends Thread and override its run()
method.
java

class MyThread extends Thread {

public void run() {

System.out.println("Thread is running: " + Thread.currentThread().getName());

public class Demo {

public sta c void main(String[] args) {

MyThread t1 = new MyThread();

t1.start(); // starts the thread and calls run()

Crea ng Mul ple Threads


Crea ng mul ple threads in Java lets your program perform several tasks concurrently,
boos ng performance and responsiveness—especially in CPU-intensive or I/O-bound
applica ons. Let’s walk through the key techniques and examples, then explore some
excellent tutorials to reinforce your understanding.

1. Extending the Thread Class

You can create mul ple threads by defining a class that extends Thread and overriding its
run() method.

java

class MyThread extends Thread {

public void run() {

System.out.println("Thread " + Thread.currentThread().getId() + " is running");

}
}

public class Demo {

public sta c void main(String[] args) {

for (int i = 0; i < 5; i++) {

MyThread t = new MyThread();

t.start(); // starts a new thread

Using isAlive() and join()

In Java mul threading, isAlive() and join() are two essen al methods from the Thread class
that help you monitor and control thread execu on. Let’s break them down with examples,
use cases, and video tutorials that bring them to life:

isAlive() Method

 Purpose: Checks if a thread is s ll running.

 Returns: true if the thread has been started and hasn’t finished; false otherwise.

 Use Case: Useful for status checks or condi onal logic based on thread ac vity.

java

Thread t1 = new Thread(() -> {

System.out.println("Thread running...");

});

t1.start();

System.out.println(t1.isAlive()); // true (if thread is s ll running)


join() Method

 Purpose: Pauses the current thread un l the target thread finishes.

 Throws: InterruptedExcep on

 Use Case: Ensures sequen al execu on or waits for a thread to complete before
proceeding.

java

Thread t1 = new Thread(() -> {

System.out.println("Thread running...");

});

t1.start();

try {

t1.join(); // Waits for t1 to finish

} catch (InterruptedExcep on e) {

e.printStackTrace();

System.out.println("Thread t1 has finished.");

Suspending

In Java, suspending a thread refers to temporarily pausing its execu on so it doesn’t consume
CPU cycles or proceed with its task un l explicitly resumed. While Java originally provided
built-in methods like suspend() and resume(), these are now deprecated due to risks like
deadlocks and resource locking. Let’s explore how suspension works, why it’s discouraged,
and what alterna ves are used today.

Deprecated Methods: suspend() and resume()

 suspend() pauses a thread.

 resume() restarts a suspended thread.


 These methods can lock shared resources indefinitely, leading to deadlocks.

java

Thread t = new Thread(() -> {

System.out.println("Thread running...");

});

t.start();

t.suspend(); // Deprecated

t.resume(); // Deprecated

t.stop();

Obtaining A Thread’s State

In Java, you can obtain a thread’s current state using the getState() method from the Thread
class. This is especially useful for debugging, profiling, or managing thread behavior in
complex mul threaded applica ons.

How to Use getState()

java

Thread t = new Thread(() -> {

System.out.println("Thread running...");

});

System.out.println("Before start: " + t.getState()); // NEW

t.start();

System.out.println("A er start: " + t.getState()); // RUNNABLE or RUNNING

 getState() returns a value from the Thread.State enum.

 The state may change immediately a er calling getState(), so it’s a snapshot, not a
guarantee.

Thread States in Java


Java defines six thread states via the Thread.State enum:

State Descrip on

NEW Thread is created but not started

RUNNABLE Thread is ready to run or running

BLOCKED Wai ng to acquire a lock

WAITING Wai ng indefinitely for another thread (e.g., join(), wait())

TIMED_WAITING Wai ng for a specified me (e.g., sleep(), join( meout))

TERMINATED Thread has finished execu on

Using Mul threading.

1. What Is Mul threading?

Mul threading means running mul ple threads (lightweight processes) within a single
program. Each thread can execute independently but shares the same memory space.

2. Crea ng Threads

You can create threads in three main ways:

a. Extending the Thread class

java

class MyThread extends Thread {

public void run() {

System.out.println("Thread running: " + Thread.currentThread().getName());

b. Implemen ng the Runnable interface

java

class MyRunnable implements Runnable {

public void run() {


System.out.println("Runnable thread: " + Thread.currentThread().getName());

3. Star ng Threads

Use the start() method to begin execu on:

java

Thread t1 = new MyThread();

t1.start();

examples.

4. Thread Lifecycle

Java threads go through these states:

 New → created

 Runnable → ready to run

 Running → execu ng

 Blocked/Wai ng → paused

 Terminated → finished

5. Thread Pools and Executors

For managing many threads efficiently:

java

ExecutorService executor = Executors.newFixedThreadPool(3);

executor.submit(() -> System.out.println("Task running"));

executor.shutdown();

6. Synchroniza on and Safety

Use synchronized blocks or methods to prevent race condi ons when threads share data.

You might also like