important topics in java
UNIT-1
📘 1️⃣📘 Java Overview
🔹 Introduction to Java
Java is a high-level, object-oriented, platform-independent programming language developed by James
Gosling at Sun Microsystems in 1995.
It follows the concept —
👉 “Write Once, Run Anywhere” (WORA) — meaning Java programs can run on any device that has a
Java Virtual Machine (JVM).
🔹 Features of Java
No. Feature Description
1️👉 Simple Easy to learn and use (syntax similar to C/C++)
2️👉 Object-Oriented Everything in Java is an object
3️👉 Platform Independent Code runs on any OS (Windows, Linux, Mac)
4️👉 Secure No pointers, has built-in security features
5️👉 Robust Strong memory management and exception handling
6️👉 Portable Bytecode can run anywhere
7️👉 Multithreaded Supports running multiple tasks simultaneously
8️👉 Dynamic Supports runtime method linking and class loading
9️👉 High Performance Uses Just-In-Time (JIT) compiler
👉 Distributed Supports internet-based distributed applications
🔹 Java Architecture
Java Program Execution Steps:
1️⃣👉 Write code → .java file
2️⃣👉 Compile using javac → produces .class file (Bytecode)
3️⃣👉 Run using java → JVM interprets the bytecode
Diagram:
Source Code (.java)
↓
Compiler (javac)
↓
Bytecode (.class)
↓
JVM
↓
Machine Code (Execution)
🔹 Java Components
Component Description
JDK (Java Development Kit) Contains compiler, JRE, tools for developers
JRE (Java Runtime Environment) Used to run Java programs
JVM (Java Virtual Machine) Executes Java bytecode
🔹 Java Program Example
public class HelloWorld {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Output:
Welcome to Java!
📘 2️⃣📘 Object-Oriented Programming (OOP) Concepts in Java
🔹 Introduction
OOP (Object-Oriented Programming) is a programming paradigm that organizes data and behavior around
objects rather than functions or logic.
🔹 Main Principles of OOP
Concept Description Example
1️🔹 Class A blueprint or template for creating objects class Student { }
Concept Description Example
2️🔹 Object Instance of a class Student s1 = new Student();
3️🔹 Encapsulation Wrapping of data and methods in a single unit Private variables with getters/setters
4️🔹 Inheritance Acquiring properties of one class into another class Dog extends Animal { }
5️🔹 Polymorphism Performing one action in many ways Method overloading & overriding
6️🔹 Abstraction Hiding internal details and showing only functionality Using abstract classes or interfaces
🔹 1️⃣🔹 Class and Object Example
class Student {
String name;
int age;
void showDetails() {
[Link](name + " is " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Rahul";
[Link] = 20;
[Link]();
}
}
Output:
Rahul is 20 years old.
🔹 2️⃣🔹 Encapsulation Example
class BankAccount {
private double balance;
public void setBalance(double bal) {
if(bal > 0)
balance = bal;
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
[Link](5000);
[Link]("Balance: " + [Link]());
}
}
🔹 3️⃣🔹 Inheritance Example
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output:
Eating...
Barking...
🔹 4️⃣🔹 Polymorphism Example
class Shape {
void draw() {
[Link]("Drawing Shape...");
}
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle...");
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(); // Runtime polymorphism
[Link]();
}
}
Output:
Drawing Circle...
🔹 5️⃣🔹 Abstraction Example
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
[Link]("Car starts with key.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
[Link]();
}
}
Output:
Car starts with key.
🔹 Summary Table of OOP Concepts
Concept Keyword Description
Class class Blueprint of object
Object new Instance of class
Encapsulation private, public Data hiding
Inheritance extends Code reusability
Polymorphism overload, override Many forms
Abstraction abstract, interface Hiding details
✅ Real-time Example of OOP:
In a Banking System:
o Class: Account, Customer
o Object: One customer's account
o Inheritance: SavingAccount inherits from Account
o Polymorphism: Different types of accounts calculate interest differently
o Encapsulation: Account balance kept private
o Abstraction: User only sees “Deposit/Withdraw” buttons, not internal logic
📘 1️⃣📘 Control Statements in Java
🔹 Introduction
Control statements are used to control the flow of execution of a program.
They decide which statement to execute next, based on a condition or loop.
🔹 Types of Control Statements
Type Description
Decision-Making Statements Used to make choices (if, if-else, switch)
Looping Statements Used to repeat tasks (for, while, do-while)
Jump Statements Used to transfer control (break, continue, return)
📘 1. Decision-Making Statements
👉 if Statement
Used to execute a block of code only if the condition is true.
int age = 20;
if(age >= 18){
[Link]("Eligible to vote");
}
👉 if-else Statement
Executes one block when condition is true, another when false.
int age = 16;
if(age >= 18){
[Link]("Eligible to vote");
} else {
[Link]("Not eligible to vote");
}
👉 else if Ladder
Used to test multiple conditions.
int marks = 85;
if(marks >= 90)
[Link]("Grade A");
else if(marks >= 75)
[Link]("Grade B");
else if(marks >= 50)
[Link]("Grade C");
else
[Link]("Fail");
👉 switch Statement
Used when we have many conditions to check.
int day = 3;
switch(day){
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid Day");
}
📘 2. Looping Statements
👉 for Loop
Used when number of iterations is known.
for(int i = 1; i <= 5; i++){
[Link](i);
}
👉 while Loop
Used when number of iterations is not known.
int i = 1;
while(i <= 5){
[Link](i);
i++;
}
👉 do-while Loop
Executes the body at least once, even if condition is false.
int i = 1;
do{
[Link](i);
i++;
}while(i <= 5);
📘 3. Jump Statements
Statement Use
break Exits from loop/switch
continue Skips current iteration
return Exits from method
for(int i=1; i<=5; i++){
if(i==3) continue;
[Link](i);
}
📘 2️⃣📘 Data Types in Java
🔹 Introduction
Data types specify the type and size of data a variable can store.
They help the compiler allocate memory.
🔹 Types of Data Types
Type Category Examples
Primitive Basic data types int, float, char, boolean
Non-Primitive Derived types String, Arrays, Classes
🔹 Primitive Data Types
Data Type Size Example Range
byte 1 byte byte b=10; -128 to 127
short 2 bytes short s=1000; -32,768 to 32,767
int 4 bytes int a=50000; -2⁹³¹ to 2³¹-1
long 8 bytes long l=100000L; Large integers
float 4 bytes float f=12.3f; Decimal (up to 7 digits)
double 8 bytes double d=19.3456; Decimal (up to 15 digits)
char 2 bytes char c='A'; Unicode characters
boolean 1 bit boolean b=true; true or false
🔹 Non-Primitive Data Types
Type Description
String Sequence of characters ("Hello")
Array Collection of elements of same type
Type Description
Class / Object Used in OOP programming
Interface Used to achieve abstraction
📘 3️⃣📘 Operators in Java
🔹 Introduction
Operators are symbols that perform operations on variables and values.
Example: +, -, *, /, ==, >, etc.
🔹 Types of Operators
Type Example Description
Arithmetic Operators +, -, *, /, % Perform mathematical operations
Relational Operators ==, !=, >, <, >=, <= Compare two values
Logical Operators &&, ||, ! Combine multiple conditions
Assignment Operators =, +=, -=, *=, /= Assign values to variables
Increment / Decrement ++, -- Increase or decrease value by 1
Conditional / Ternary condition ? value1 : value2 Short form of if-else
Bitwise Operators &, |, ^, ~, <<, >> Perform bit-level operations
🔹 1️⃣🔹 Arithmetic Operators Example
int a = 10, b = 5;
[Link](a + b); // 15
[Link](a - b); // 5
[Link](a * b); // 50
[Link](a / b); // 2
[Link](a % b); // 0
🔹 2️⃣🔹 Relational Operators Example
int a = 10, b = 20;
[Link](a == b); // false
[Link](a < b); // true
[Link](a > b); // false
🔹 3️⃣🔹 Logical Operators Example
int x = 5, y = 10;
[Link](x < y && y > 0); // true
[Link](x > y || y > 0); // true
[Link](!(x < y)); // false
🔹 4️⃣🔹 Assignment Operators Example
int a = 5;
a += 3; // a = a + 3
[Link](a); // 8
🔹 5️⃣🔹 Increment / Decrement Example
int i = 10;
[Link](i++); // 10 (post-increment)
[Link](++i); // 12 (pre-increment)
🔹 6️⃣🔹 Conditional (Ternary) Operator Example
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
[Link](result);
🔹 Summary Table
Category Keywords / Symbols Example
Decision if, if-else, switch Choose one path
Looping for, while, do-while Repeat actions
Jump break, continue Skip or exit loop
Data Types int, float, char Define variable type
Operators +, -, ==, &&, ? : Perform actions
UNIT-2
📘 CLASS in Java
📘 Definition:
A class in Java is a blueprint or template that defines the structure and behavior (data and methods) of
objects.
It represents a group of objects that share common properties and behaviors.
📘 Syntax:
class ClassName {
// Data members (variables)
// Member functions (methods)
}
📘 Explanation:
A class contains variables (to store data) and methods (to perform operations).
It does not occupy memory until an object is created.
It acts as a logical structure for organizing code in an object-oriented manner.
📘 Example:
class Student {
int id; // data member
String name; // data member
void display() { // method
[Link](id + " " + name);
}
}
Here:
Student is the class name.
id and name are variables (data members).
display() is a method that shows the data.
📘 Rules for Creating a Class:
1. Class name should start with a capital letter (e.g., Student, Car).
2. One file can contain multiple classes, but only one public class.
3. The file name should match the public class name.
4. A class can include constructors, methods, fields, and inner classes.
📘 Real-Time Example:
Think of a class as a plan or design.
👉 Example:
Class: Mobile
Objects: Samsung, iPhone, OnePlus
Each object has properties like color, price, and features — all defined by the Mobile class.
📘 Key Points:
A class is the core of Object-Oriented Programming.
It provides data encapsulation (grouping variables & methods together).
It helps to create modular, reusable, and maintainable code.
📘 OBJECT in Java
📘 Definition:
An object is a real-world entity or instance of a class.
It represents a thing that has state (data) and behavior (methods).
When a class is defined, no memory is allocated.
But when an object is created, memory is allocated to store its data.
📘 Syntax:
ClassName objectName = new ClassName();
Explanation:
ClassName → name of the class
objectName → reference variable
new → keyword used to allocate memory
ClassName() → calls the class constructor
📘 Example:
class Student {
int id;
String name;
void display() {
[Link](id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects
Student s1 = new Student();
Student s2 = new Student();
// Assigning values
[Link] = 101;
[Link] = "Ravi";
[Link] = 102;
[Link] = "Priya";
// Calling method using objects
[Link]();
[Link]();
}
}
📘 Output:
101 Ravi
102 Priya
📘 Explanation:
Student → class
s1, s2 → objects created from the class
Each object has its own copy of variables (id, name).
Methods (like display()) are called using objects.
📘 Key Points:
1. An object is created using the new keyword.
2. Each object can store different data.
3. One class can create many objects.
4. Through objects, you can access class members (variables & methods).
5. Without an object, methods and variables of a class cannot be accessed (unless they are static).
📘 Real-Time Example:
Think of a class as a blueprint and objects as actual buildings built from that blueprint.
👉 Example:
Class: Car
Objects: Swift, BMW, Tesla
Each car (object) has its own color, model, and price.
📘 INHERITANCE in Java
📘 Definition:
Inheritance is one of the main features of Object-Oriented Programming.
It allows one class to acquire (inherit) the properties and methods of another class.
It helps in code reusability and method overriding.
📘 Syntax:
class Parent {
// parent class code
}
class Child extends Parent {
// child class code
}
Explanation:
extends keyword is used to inherit a class.
The child class can use all the non-private members (variables and methods) of the parent class.
The child class can also add its own methods.
📘 Example Program:
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited from Animal class
[Link](); // own method
}
}
📘 Output:
Eating...
Barking...
📘 Explanation:
Animal → Parent class (Base class)
Dog → Child class (Derived class)
Dog class inherits eat() method from Animal.
Hence, Dog can use both eat() and bark() methods.
🔹 Advantages of Inheritance
1. Code Reusability: You can use the existing class code without rewriting.
2. Readability: The code becomes more organized.
3. Extensibility: New features can be easily added.
4. Maintenance: Easier to modify and maintain.
🔹 Types of Inheritance in Java
Type Description
1. Single Inheritance One class inherits from another.
2. Multilevel Inheritance A class inherits from another class, which itself inherits from another class.
3. Hierarchical
Multiple classes inherit from a single parent class.
Inheritance
Combination of more than one type (not directly supported in Java, but achieved through
4. Hybrid Inheritance
interfaces).
📘 Example: Multilevel Inheritance
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Puppy extends Dog {
void weep() {
[Link]("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
}
}
📘 Output:
Eating...
Barking...
Weeping...
🔹 Key Points to Remember:
The extends keyword is used for inheritance.
Java does not support multiple inheritance with classes (to avoid ambiguity).
Constructors of the parent class are called automatically when the child object is created.
Method overriding can be used to redefine parent methods in the child class.
📘 POLYMORPHISM in Java
📘 Definition:
The word Polymorphism means “many forms.”
In Java, polymorphism allows one task to be performed in different ways.
In simple words —
👉 The same method name can perform different actions depending on the object that calls it.
📘 Types of Polymorphism
Java supports two types of polymorphism:
Type Description Example
1. Compile-time Polymorphism Also known as Method Overloading Same method name with different parameters
2. Runtime Polymorphism Also known as Method Overriding Same method name in parent and child class
🔹 1. Compile-time Polymorphism (Method Overloading)
📘 Definition:
When multiple methods have the same name but different parameter lists (different number or type of
arguments), it is called method overloading.
This happens during compile-time.
📘 Example:
class MathOperation {
// method 1
int add(int a, int b) {
return a + b;
}
// method 2 (overloaded)
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
MathOperation m = new MathOperation();
[Link]("Sum1: " + [Link](10, 20));
[Link]("Sum2: " + [Link](10, 20, 30));
}
}
📘 Output:
Sum1: 30
Sum2: 60
👉 Explanation:
Both methods have the same name add() but different parameters — the compiler decides which one to
call.
🔹 2. Runtime Polymorphism (Method Overriding)
📘 Definition:
When a subclass provides a specific implementation of a method that is already defined in its superclass,
it is called method overriding.
This happens during runtime.
📘 Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
[Link](); // calls Dog's version of sound()
}
}
📘 Output:
Dog barks
👉 Explanation:
The reference variable a is of type Animal, but it points to a Dog object.
At runtime, the JVM calls the Dog class method — this is runtime polymorphism.
🔹 Advantages of Polymorphism
1. Code Reusability — same method name used for multiple tasks.
2. Flexibility — one interface can be used for different object types.
3. Extensibility — easy to add new classes with their own method implementations.
4. Maintainability — cleaner and more readable code.
🔹 Real-Time Example:
Think of a TV remote —
The same button (method) works for different TVs (objects).
The action changes based on the TV brand (object type).
That’s Polymorphism in real life!
🔹 Key Points to Remember
Compile-time polymorphism → Method Overloading
Runtime polymorphism → Method Overriding
Overloading is resolved by the compiler
Overriding is resolved by the JVM (at runtime)
Polymorphism improves code flexibility and reusability
UNIT-3
📘 INTERFACE in Java
📘 Definition:
An interface in Java is a blueprint of a class.
It is used to achieve abstraction and multiple inheritance in Java.
An interface contains abstract methods (methods without body) and constants (final variables).
📘 Syntax:
interface InterfaceName {
// abstract methods
void method1();
void method2();
}
To use an interface, a class must implement it using the implements keyword.
class ClassName implements InterfaceName {
// provide implementation for interface methods
public void method1() { ... }
public void method2() { ... }
}
🔹 Example Program:
interface Animal {
void sound(); // abstract method
void eat(); // abstract method
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
public void eat() {
[Link]("Dog eats meat");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
📘 Output:
Dog barks
Dog eats meat
📘 Explanation:
Animal → Interface
Dog → Class implementing the interface
Class Dog must implement all methods defined in the interface.
Interface methods are public and abstract by default.
🔹 Why Use Interfaces?
1. To achieve 100% abstraction.
2. To support multiple inheritance (since Java doesn’t allow multiple class inheritance).
3. To define a common behavior that many classes can share.
🔹 Real-Time Example:
Think of an interface as a contract —
If a company (interface) says “every employee must work() and attendMeeting()”,
then every class (employee) implementing it must follow that rule.
🔹 Multiple Inheritance Using Interfaces
Java allows a class to implement multiple interfaces.
interface A {
void show();
}
interface B {
void display();
}
class C implements A, B {
public void show() {
[Link]("Show from A");
}
public void display() {
[Link]("Display from B");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}
📘 Output:
Show from A
Display from B
👉 Explanation:
Here class C implements both interfaces A and B, achieving multiple inheritance safely.
🔹 Key Points to Remember:
Interfaces cannot have method bodies (before Java 8).
All interface variables are public, static, and final by default.
A class must implement all abstract methods of an interface.
One interface can extend another interface.
Since Java 8, interfaces can have:
o default methods (with body)
o static methods
📘 Example of Default Method (Java 8):
interface Vehicle {
void start();
default void fuelType() {
[Link]("Petrol or Diesel");
}
}
class Car implements Vehicle {
public void start() {
[Link]("Car starts with key");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link]();
}
}
📘 Output:
Car starts with key
Petrol or Diesel
📘 Summary Table:
Feature Interface Class
Keyword interface class
Methods Abstract (no body) Can be normal or abstract
Variables Public, static, final Normal variables
Multiple Inheritance Supported Not supported
Object Creation Not possible Possible
📘 Packages in Java
📘 Definition:
A package in Java is a collection of related classes, interfaces, and sub-packages that are grouped
together to organize code logically.
It helps avoid naming conflicts and makes code easier to manage and reuse.
📘 Types of Packages:
1. Built-in Packages (Predefined)
→ Provided by Java itself.
Examples:
o [Link] → Basic classes (String, Math, Object)
o [Link] → Utility classes (ArrayList, HashMap, Date)
o [Link] → Input and Output classes
o [Link] → Networking classes
o [Link] → Database classes
2. User-defined Packages
→ Created by the programmer to organize custom classes.
📘 Syntax for creating a package:
package packagename;
public class ClassName {
// class code
}
📘 Example:
Step 1: Create a package
package mypackage;
public class Student {
public void display() {
[Link]("Hello from Student class in mypackage");
}
}
Step 2: Use the package in another program
import [Link];
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
📘 Real-time Example:
Imagine you are developing a banking application.
You can organize your classes using packages like this:
[Link]
[Link]
[Link]
[Link]
Each package will have classes related to that specific functionality — this keeps your project clean and
modular.
📘 Advantages of Packages:
✅ Code reusability
✅ Easy maintenance
✅ Avoids name conflicts
✅ Access control (public, protected, private)
✅ Organized project structure
📘 Accessing Packages:
Keyword Meaning
import packagename.*; Imports all classes in a package
import [Link]; Imports only that specific class
fully qualified name Example: [Link] s = new [Link]();
📘 Summary:
Package = Folder that contains related classes.
Helps in better project organization.
You can use both built-in and user-defined packages.
Used in all real-time applications.
⚡ Exception Handling in Java
🔹 What is an Exception?
An exception is an error that happens while a program is running (runtime error).
It stops the normal flow of the program.
👉 Example:
Dividing a number by zero
Accessing an array element that doesn’t exist
File not found
🔹 Why Exception Handling?
To handle errors properly without crashing the program.
Instead of stopping the program suddenly, Java allows you to catch and handle the error smoothly.
🔹 Types of Exceptions
1. Checked Exceptions → Detected by compiler at compile time
(e.g., FileNotFoundException, IOException)
2. Unchecked Exceptions → Detected during runtime
(e.g., ArithmeticException, NullPointerException)
3. Errors → Serious issues that cannot be handled (e.g., OutOfMemoryError)
🔹 Exception Handling Keywords
Keyword Description
try Contains the code that might throw an exception
catch Used to handle (catch) the exception
finally Always executes whether exception occurs or not
throw Used to throw an exception manually
throws Used to declare an exception in method signature
🔹 Basic Example:
public class Example1 {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // This will cause an exception
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed!");
}
[Link]("Program continues...");
}
}
✅Output:
Error: Division by zero is not allowed!
Program continues...
🔹 Explanation (Line by Line):
1. try block → code that may throw an exception.
2. When a / b is performed, b is zero → causes ArithmeticException.
3. catch block → catches and handles the exception.
4. Program doesn’t stop — continues executing after catch block.
🔹 Real-Time Example:
Imagine you are using an ATM machine.
If you enter the wrong PIN, the ATM doesn’t crash —
it shows an error message and asks you to try again.
That’s Exception Handling in action!
🔹 Example 2: Multiple Catch Blocks
public class Example2 {
public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
[Link](arr[5]); // array index error
}
catch (ArithmeticException e) {
[Link]("Arithmetic Error!");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index is out of range!");
}
finally {
[Link]("Program finished.");
}
}
}
✅Output:
Array index is out of range!
Program finished.
🔹 finally Block Example
try {
int num = 5 / 0;
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
finally {
[Link]("This block always executes");
}
✅Output:
Cannot divide by zero
This block always executes
🔹 Summary
Keyword Purpose
try Block of code that might throw an exception
catch Handles the exception
finally Executes always (used to close files, release resources)
throw Throws an exception manually
throws Declares exceptions in method signature
🔹 Advantages of Exception Handling
Prevents program from crashing
Helps in debugging
Improves reliability and readability of code
UNIT-4
📘 MULTITHREADING IN JAVA
🔹 What is Multithreading?
Multithreading is a feature in Java that allows a program to perform multiple tasks at the same time.
Each task is called a thread.
A thread is a lightweight process that runs independently.
📘 Example (Real-life)
Imagine you are:
Listening to music 👉
Downloading a file 👉
Typing a document 👉
—all at the same time!
Each activity is a separate thread running simultaneously in your computer.
That’s multithreading.
🔹 Why Use Multithreading?
✅ To perform multiple tasks simultaneously
✅ To save time and increase performance
✅ To use CPU efficiently
✅ To make applications faster and smoother
🔹 Thread in Java
A Thread is a small unit of a process that executes independently.
All threads share the same memory of the process but have their own execution path.
🔹 How to Create Threads in Java
There are two ways to create threads in Java:
1️⃣📘 By extending the Thread class
class MyThread extends Thread {
public void run() { // run() method - thread task
for(int i = 1; i <= 5; i++) {
[Link]("Thread running: " + i);
}
}
}
public class Example1 {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // create thread object
[Link](); // start the thread
}
}
✅Output:
Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5
Explanation:
run() → method contains the code that thread executes.
start() → begins thread execution and calls run() method internally.
JVM allocates CPU time to each thread automatically.
2️⃣📘 By implementing the Runnable interface
class MyTask implements Runnable {
public void run() {
for(int i = 1; i <= 3; i++) {
[Link]("Runnable Thread: " + i);
}
}
}
public class Example2 {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread t1 = new Thread(task);
[Link]();
}
}
🔹 Difference Between Thread Class and Runnable Interface
Feature Thread Class Runnable Interface
Inheritance Extends Thread class Implements Runnable interface
Flexibility Can’t extend any other class Can extend other classes too
Usage For simple threads For complex thread-based tasks
🔹 Important Thread Methods
Method Description
start() Starts thread execution
run() Defines code of thread
sleep(ms) Pauses thread for given milliseconds
Method Description
join() Waits for a thread to finish before continuing
isAlive() Checks if thread is still running
getName() Returns thread name
setPriority() Sets priority (1–10) of thread
🔹 Example: Multiple Threads
class First extends Thread {
public void run() {
for(int i=1; i<=3; i++) {
[Link]("First Thread: " + i);
}
}
}
class Second extends Thread {
public void run() {
for(int i=1; i<=3; i++) {
[Link]("Second Thread: " + i);
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
First t1 = new First();
Second t2 = new Second();
[Link](); // start both threads
[Link]();
}
}
✅Output (Order may vary):
First Thread: 1
Second Thread: 1
First Thread: 2
Second Thread: 2
First Thread: 3
Second Thread: 3
👉 Threads may execute in any order — depends on CPU scheduling.
🔹 Real-Time Example
👉 Example: Downloading and Watching a Video
While watching a YouTube video:
One thread plays the video
Another thread downloads data in the background
Both run simultaneously — that’s multithreading.
🔹 Thread Life Cycle
State Description
New Thread object created but not started
Runnable Thread ready to run
Running Thread is executing its task
Blocked/Waiting Thread waiting for resources or another thread
Terminated Thread has finished execution
🔹 Advantages of Multithreading
✅ Increases application speed
✅ Saves CPU time
✅ Runs multiple tasks together
✅ Useful for games, animations, and background processing
🔹 Summary
Concept Description
Thread Smallest unit of execution
Multithreading Running multiple threads at once
run() Code of thread
start() Starts the thread
sleep(), join() Control thread execution
Synchronization Used to prevent thread conflicts
📘 Stream-Based Input/Output ([Link]) in Java
🔹 Introduction
In Java, Input/Output (I/O) means reading data from a source and writing data to a destination.
For example:
Reading data from the keyboard 👉👉
Reading a file 👉
Writing output to the console or saving to a file 👉
Java provides the [Link] package to perform all I/O operations.
🔹 What is a Stream?
A stream is a sequence of data that flows from one place to another.
👉 Think of a stream as a pipeline:
Input Stream → used to read data (from keyboard, file, etc.)
Output Stream → used to write data (to screen, file, etc.)
🔹 Types of Streams
Java has two main types of streams:
Type Description Examples
Byte Streams Used to handle binary data (images, audio, video, etc.) FileInputStream, FileOutputStream
Character Streams Used to handle text data (characters) FileReader, FileWriter
🔹 1️⃣🔹 Byte Streams
Byte streams are used to read and write byte (8-bit) data.
Example: Reading from a file using FileInputStream
import [Link].*;
public class ReadFile {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
} catch (IOException e) {
[Link]("Error reading file: " + e);
}
}
}
✅Explanation
FileInputStream reads one byte at a time from the file.
(char)i converts the byte into a character for display.
-1 means end of file.
[Link]() closes the file.
Example: Writing to a file using FileOutputStream
import [Link].*;
public class WriteFile {
public static void main(String[] args) {
try {
FileOutputStream fout = new FileOutputStream("[Link]");
String text = "Welcome to Java I/O Programming!";
byte b[] = [Link](); // Convert to bytes
[Link](b);
[Link]();
[Link]("File written successfully.");
} catch (IOException e) {
[Link]("Error writing file: " + e);
}
}
}
✅Explanation
FileOutputStream writes bytes into the file.
getBytes() converts text into bytes.
File is created if it doesn’t exist.
🔹 2️⃣🔹 Character Streams
Character streams are used to read/write text data (16-bit Unicode).
Example: Reading a file using FileReader
import [Link].*;
public class ReadCharacters {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char)ch);
}
[Link]();
} catch (IOException e) {
[Link]("Error reading file: " + e);
}
}
}
Example: Writing to a file using FileWriter
import [Link].*;
public class WriteCharacters {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Java I/O is simple and powerful!");
[Link]();
[Link]("Data written successfully!");
} catch (IOException e) {
[Link]("Error writing file: " + e);
}
}
}
🔹 Buffered Streams
Buffered Streams improve performance by storing data in a temporary buffer.
Class Description
BufferedReader Reads text from a character-input stream
BufferedWriter Writes text to a character-output stream
BufferedInputStream / BufferedOutputStream Used for byte streams
Example using BufferedReader
import [Link].*;
public class BufferedExample {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
}
}
🔹 Real-Time Example
👉 Example: A media player
Input Stream: Reads song file (.mp3)
Output Stream: Sends data to speakers
👉 Example: Copying files
One stream reads data from the source file
Another stream writes data into the destination file
🔹 Common I/O Classes ([Link] package)
Class Purpose
File Represents a file or directory
FileReader Reads character data
FileWriter Writes character data
FileInputStream Reads byte data
FileOutputStream Writes byte data
BufferedReader Reads text efficiently
BufferedWriter Writes text efficiently
PrintWriter Prints formatted text
🔹 Summary
Concept Description
Stream Sequence of data flow
Input Stream Used to read data
Output Stream Used to write data
Byte Stream Handles binary data
Character Stream Handles text data
Buffered Stream Improves performance
[Link] package Contains all I/O classes
🔹 Advantages of Stream-Based I/O
✅ Platform independent
✅ Fast and efficient
✅ Easy to handle files and user input
✅ Helps in reading/writing large data