java
java
1. Encapsula on
o Bundles data (fields) and methods that operate on that data into a single unit
(class).
2. Inheritance
o Enables a class (child) to inherit proper es and behaviors from another class
(parent).
3. Polymorphism
o Example: A Shape class with a draw() method overridden by Circle, Square, etc.
4. Abstrac on
java
class Student {
this.name = name;
this.age = age;
This class demonstrates encapsula on and abstrac on. You can extend it to include inheritance
and polymorphism.
What Is a Class?
A class is a blueprint or template that defines the structure and behavior of objects.
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() {
What Is an Object?
Example:
myCar.color = "Red";
myCar.speed = 120;
Key Differences
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.
2. Inheritance
Defini on: Allows one class (child) to inherit fields and methods from another class
(parent).
Example: class Dog extends Animal inherits behavior like eat() or sleep().
3. Polymorphism
Types:
Example: A Shape class with a draw() method overridden by Circle, Square, etc.
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.
dataType variableName;
// Constructor
ClassName(parameters) {
returnType methodName(parameters) {
// Method body
Components Explained:
Let’s create a class called Student that stores a student’s name and age and displays their info.
java
// Fields
String name;
int age;
// Constructor
name = studentName;
age = studentAge;
// Method
s1.displayInfo();
Declaring an Object
Declaring an object means crea ng a reference variable that can point to an instance of a class.
java
It simply tells the compiler that obj will refer to an object of type Class Name.
To actually create the object and assign it to the reference variable, use the new keyword:
java
java
This creates a new object in memory and assigns its reference to obj.
java
ClassName obj2 = obj1; // obj2 now refers to the same object as obj1
Both obj1 and obj2 point to the same memory loca on.
Example:
java
class Student {
String name;
}
s1.name = "Gowtham";
Key Concepts
Concept Descrip on
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
A method is a block of code that performs a specific task. It helps organize code, promote reuse,
and improve readability.
Method Syntax
// method body
Let’s define a Box class and add a method to calculate its volume.
class Box {
double width;
double height;
double depth;
double volume() {
This method uses the instance variables to compute and return the volume.
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;
java
b.width = 2;
b.height = 3;
b.depth = 4;
You can define methods that accept parameters and return a value. This makes your class more
flexible.
return w * h * d;
Summary Table
// Box.java
class Box {
// Fields
double width;
double height;
double depth;
// Default Constructor
public Box() {
width = 0;
height = 0;
depth = 0;
// Parameterized Constructor
width = w;
height = h;
depth = d;
}
// Method to calculate volume using instance variables
return w * h * d;
}// Main.java
box1.width = 2.5;
box1.height = 3.0;
box1.depth = 4.0;
// Create a Box using parameterized constructor
System.out.println("Box 1 Details:");
box1.displayInfo();
System.out.println();
System.out.println("Box 2 Details:");
box2.displayInfo();
System.out.println();
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’s automa cally called when an object is instan ated using new
Syntax of a Constructor
java
class ClassName {
ClassName() {
// constructor body
Types of Constructors
Copy Constructor Takes another object of the same class and Box b2 = new
copies its data Box(b1);
java
class Box {
// Default constructor
Box() {
// Parameterized constructor
width = w;
height = h;
depth = d;
double volume() {
class Box {
// 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:
To dis nguish between instance variables and parameters with the same name
java
class Student {
String name;
Student(String name) {
Without this, name = name; would assign the parameter to itself—not the instance variable.
java
class Box {
Box() {
height = h;
depth = d;
This avoids code duplica on and ensures consistent ini aliza on.
java
class Printer {
void print(Student s) {
class Student {
void show() {
class Student {
String name;
Student setName(String name) {
this.name = name;
Limita ons
You cannot use this in sta c methods, because sta c methods belong to the class, not
any object.
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.
How It Works
1. Marking
2. Dele on/Sweeping
3. Compac ng
Example
java
class Student {
String name;
Student(String name) {
this.name = name;
Parallel GC Mul -threaded, good for throughput, may cause longer pauses
You can explore more on GeeksforGeeks' GC guide or Java Code Geeks' tutorial.
Island of Isola on: Group of objects referencing each other but not reachable from
outside
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
Example Usage
java
class Demo {
String name;
Demo(String name) {
this.name = name;
@Override
Risky: Excep ons in finalize() were ignored, and misuse could lead to memory leaks or
crashes.
Be er alterna ves:
Overloading methods
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.
java
class Calculator {
return a + b;
return a + b + c;
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
Ambiguity can arise if type promo on (e.g., int to long) leads to mul ple valid matches.
Benefits
Overloading Constructor
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.
java
class Box {
width = w;
height = h;
depth = d;
Box(double len) {
width = height = depth = len;
// Default constructor
Box() {
double volume() {
java
class Student {
String name;
int age;
Student() {
this.name = name;
this.age = age;
Recursion
What Is Recursion?
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) {
} else {
java
java
When the base case is reached, the stack unwinds and returns values back up.
Recursion vs Itera on
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.
java
class Animal {
void eat() {
void bark() {
Benefits of Inheritance
Type Descrip on
Mul level A subclass inherits from a class that itself inherits another class
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.
A child class inherits fields and methods from a single parent class.
Syntax:
java
class Parent {
void greet() {
void sayHi() {
}
}
Key Concepts
Term Meaning
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.
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");
obj.methodC(); // defined in C
Key Concepts
Term Meaning
Constructor Chain Superclass constructors are called first, then subclass constructors
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.
Subclasses: Each subclass extends the same superclass and inherits its members.
Example:
java
class Animal {
void eat() {
void bark() {
System.out.println("Dog barks.");
void meow() {
System.out.println("Cat meows.");
}
public class Main {
d.bark(); // Dog-specific
c.meow(); // Cat-specific
Key Benefits
hybrid inheritance
Hybrid inheritance blends different inheritance models to create a complex class hierarchy. For
example:
This structure allows for maximum code reuse, modularity, and flexibility.
java
interface Readable {
void read();
interface Writable {
void write();
class Document {
void open() {
System.out.println("Document opened.");
}
}
Here:
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.
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.
Java allows a class to implement mul ple interfaces, which is a form of mul ple inheritance—
without the ambiguity.
java
interface Printable {
System.out.println("Prin ng...");
interface Scannable {
default void scan() {
System.out.println("Scanning...");
print();
scan();
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 {
System.out.println("A");
interface B {
System.out.println("B");
}
class C implements A, B {
A.super.show(); // or B.super.show()
Method overriding
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() {
@Override
void sound() {
System.out.println("Dog barks");
}
java
Must be in a subclass.
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.
The actual method that gets executed depends on the object type, not the reference
type.
java
class Animal {
void sound() {
void sound() {
System.out.println("Dog barks");
Even though a is of type Animal, the method from Dog is executed because the object is a Dog.
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.
Can contain both abstract methods (without a body) and concrete methods (with a
body).
java
System.out.println("Sleeping...");
java
@Override
void makeSound() {
System.out.println("Dog barks");
java
void start() {
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.
java
class Parent {
}
}
#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.
java
class Parent {
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.
Packages help:
java
package mypackage;
7.10 What are Packages in Java explains how to create packages, import them, and their
structure with clear visuals.
java
java
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.
private Yes No No No
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?
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
System.out.println("Car started");
System.out.println("Car stopped");
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 {
java
interface SmartDevice {
System.out.println("Connec ng...");
System.out.println("Rese ng...");
java
interface Vehicle {
System.out.println("Beep beep!");
java
interface Printer {
void print();
java
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.
java
interface U lity {
It’s useful for helper methods, valida on, or calcula ons related to the interface.
java
return x * x;
void operate();
calc.operate();
// Calling sta c method from interface
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:
An excep on is an event that disrupts the normal flow of a program. It typically occurs due to:
Division by zero
Null references
Unchecked excep ons: Occur at run me and don’t require mandatory handling (e.g.,
NullPointerExcep on, Arithme cExcep on)
java
try {
} finally {
java
java
try {
int result = 10 / 0;
} finally {
System.out.println("Execu on complete.");
}
}
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:
These are checked at compile me. If not handled properly, your code won’t compile.
Examples:
Sample:
java
These occur at run me and are not checked during compila on. They usually indicate
programming errors.
Examples:
Sample:
java
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:
Throwable
├── Excep 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:
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
e.printStackTrace();
});
java
}
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 {
try: Wraps risky code (e.g., division, file access, array indexing)
java
try {
int result = 10 / 0;
java
try {
System.out.println(arr[5]); // ArrayIndexOutOfBoundsExcep on
System.out.println("Arithme c error");
} catch (ArrayIndexOutOfBoundsExcep on e) {
Nested Try-Catch
You can nest try-catch blocks to handle excep ons at different levels:
java
try {
try {
int res = 10 / 0;
String s = null;
System.out.println(s.length());
} catch (NullPointerExcep on 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.
java
try {
// risky code
System.out.println("Arithme c error");
} catch (ArrayIndexOutOfBoundsExcep on e) {
} 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
try {
} catch (ArrayIndexOutOfBoundsExcep on e) {
System.out.println("Array Index Out Of Bounds Excep on");
} catch (Excep on e) {
You can combine mul ple excep ons in a single catch block using the | symbol:
java
try {
// risky code
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:
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 {
try {
} catch (OuterExcep on e) {
java
try {
try {
} catch (NumberFormatExcep on e) {
} finally {
} catch (FileNotFoundExcep on e) {
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
// risky code
Key Points
Used for checked excep ons (e.g., IOExcep on, SQLExcep on)
Example
java
try {
riskyMethod();
} catch (InterruptedExcep on 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
Releasing resources
Example
java
try {
int result = 10 / 0;
} finally {
System.out.println("Cleanup done.");
}
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:
IOExcep on
SQLExcep on
ClassNotFoundExcep on
Arithme cExcep on
NullPointerExcep on
ArrayIndexOutOfBoundsExcep on
NumberFormatExcep on
Example: NullPointerExcep on
java
}
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:
java
super(message);
java
try {
validate(15);
} catch (InvalidAgeExcep on e) {
java
super(message);
if (b == 0) {
}
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.
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)
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.
java
try {
try {
1. Try-With-Resources
How it works:
java
System.out.println(br.readLine());
} catch (IOExcep on e) {
e.printStackTrace();
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;
System.out.println(arr[10]);
[JAVA NEW FEATURE] handling mul ple excep ons inside a ... demonstrates how to use
mul -catch effec vely with real examples.
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
try {
// risky code
} catch (Excep on e) {
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 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.
Java Thread Model explains how Java’s run me system uses threads to eliminate polling
loops and improve CPU efficiency, especially in asynchronous environments.
State Descrip on
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.
Understanding of Main thread in Java explains how the main thread is ini alized and its
role in managing other threads.
java
Thread t = Thread.currentThread();
t.setName("SuperMainThread");
System.out.println("Thread name changed to: " + t.getName());
try {
Thread.sleep(2000);
} catch (InterruptedExcep on e) {
Phase Descrip on
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:
This is the most direct method. You create a class that extends Thread and override its run()
method.
java
You can create mul ple threads by defining a class that extends Thread and overriding its
run() method.
java
}
}
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
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
System.out.println("Thread running...");
});
t1.start();
Throws: InterruptedExcep on
Use Case: Ensures sequen al execu on or waits for a thread to complete before
proceeding.
java
System.out.println("Thread running...");
});
t1.start();
try {
} catch (InterruptedExcep on e) {
e.printStackTrace();
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.
java
System.out.println("Thread running...");
});
t.start();
t.suspend(); // Deprecated
t.resume(); // Deprecated
t.stop();
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.
java
System.out.println("Thread running...");
});
t.start();
The state may change immediately a er calling getState(), so it’s a snapshot, not a
guarantee.
State Descrip on
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
java
java
3. Star ng Threads
java
t1.start();
examples.
4. Thread Lifecycle
New → created
Running → execu ng
Blocked/Wai ng → paused
Terminated → finished
java
executor.shutdown();
Use synchronized blocks or methods to prevent race condi ons when threads share data.