JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 1
☕
JAVA
PROGRAMMING
Complete Study Notes
From Basics to Advanced
OOP • Classes • Inheritance • Interfaces • Collections • Exceptions • Threads
Prepared by
Mudit Bagra
Designed & Compiled with ♥ for Java Learners
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 2
TABLE OF CONTENTS
Section Topic
01 Introduction to Java
02 Installation & Setup (JDK, IDE)
03 Basic Structure of a Java Program
04 Data Types & Variables
05 Operators in Java
06 Input & Output (Scanner / [Link])
07 Control Flow — if / else / switch
08 Loops — for, while, do-while, for-each
09 Methods (Functions)
10 Arrays
11 Strings & StringBuilder
12 Object-Oriented Programming — Classes & Objects
13 Constructors
14 Inheritance
15 Polymorphism
16 Abstraction & Interfaces
17 Encapsulation & Access Modifiers
18 Exception Handling
19 Collections Framework
20 Generics
21 File I/O — [Link] & [Link]
22 Multithreading
23 Java 8+ Features — Lambdas & Streams
24 Packages & Important Java APIs
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 3
25 Quick Reference Cheat Sheet
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 4
01 Introduction to Java
What is Java?
Java is a high-level, class-based, object-oriented programming language developed by James Gosling at
Sun Microsystems in 1995. Java follows the principle: "Write Once, Run Anywhere" (WORA) —
compiled code runs on any platform with a JVM.
Key Features
➤ Platform-independent — bytecode runs on any JVM
➤ Strongly typed — every variable must be declared with a type
➤ Object-Oriented — everything revolves around classes and objects
➤ Automatic memory management — Garbage Collector handles deallocation
➤ Robust — strong type checking, exception handling, no pointers
➤ Multithreaded — built-in support for concurrent programming
➤ Secure — runs inside JVM sandbox, no direct memory access
➤ Rich standard library — [Link], [Link], [Link] and more
Java Platform Architecture
Component Role
Full dev package — compiler (javac),
JDK (Java Development Kit) JRE, tools
Runs Java programs — JVM + standard
JRE (Java Runtime Environment) libraries
Interprets bytecode; provides WORA
JVM (Java Virtual Machine) portability
Compiled intermediate code (not
Bytecode (.class file) machine code)
Java compiler — converts .java
javac → .class
java JVM launcher — runs .class bytecode
Java Applications
Domain Examples Frameworks / Tools
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 5
Web (Backend) E-commerce, Banking Spring Boot, Jakarta EE
Android Apps Mobile development Android SDK
Enterprise Apps ERP, CRM systems Hibernate, Spring
Big Data Data processing Apache Hadoop, Spark
Desktop Apps IDE, tools JavaFX, Swing
Cloud & Microservices APIs, serverless Quarkus, Micronaut
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 6
02 Installation & Setup
Installing JDK
➤ Visit: [Link] (Oracle JDK)
➤ Or install OpenJDK: [Link] (free, open-source)
➤ Download JDK 17 or JDK 21 (LTS versions recommended)
➤ Set JAVA_HOME environment variable after installation
# Verify installation
java --version
# Output: java 21.0.x ...
javac --version
# Output: javac 21.0.x
# Compile a file
javac [Link]
# Run the compiled class
java HelloWorld
Popular Java IDEs
IDE Notes
Most popular professional Java IDE
IntelliJ IDEA (Community = free)
Free, powerful, widely used in
Eclipse IDE enterprise
VS Code + Extension Pack Lightweight, great for beginners
Official Apache IDE, good for
NetBeans beginners
Educational IDE, great for learning
BlueJ OOP
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 7
03 Basic Structure of a Java Program
Hello World — Anatomy
// [Link] — filename must match class name
public class HelloWorld { // class definition
public static void main(String[] args) { // entry point
[Link]("Hello, World!"); // print with newline
[Link]("No newline"); // print without newline
[Link]("Pi: %.2f%n", 3.14);// formatted output
}
}
Program Structure Breakdown
Component Purpose
Class declaration — must match
public class HelloWorld filename exactly
public static void main(String[] args) Entry point — JVM calls this first
[Link]() Print to console with newline
[Link]() Print without trailing newline
[Link]() Formatted output (like C's printf)
// comment Single-line comment
/* comment */ Multi-line comment
/** comment */ Javadoc comment for documentation
Statement terminator — required
; after every statement
⚠️IMPORTANT: Java filename must exactly match the public class name (case-sensitive). [Link]
must contain public class HelloWorld.
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 8
04 Data Types & Variables
Primitive Data Types
Type Size Range / Notes
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
long 8 bytes Very large integers — suffix L: 100L
float 4 bytes ~6-7 decimal digits — suffix f: 3.14f
double 8 bytes ~15-16 decimal digits (default decimal)
char 2 bytes Single Unicode character: 'A', '\n'
boolean 1 bit true or false only
Declaring Variables
int age = 20;
double salary = 75000.50;
char grade = 'A';
boolean isStudent = true;
long population = 8000000000L;
float pi = 3.14f;
// var — local type inference (Java 10+)
var name = "Mudit"; // inferred as String
var list = new ArrayList<>(); // inferred as ArrayList
// Constants (final)
final double G = 9.81;
final int MAX_SIZE = 100;
// Type casting
int x = (int) 9.99; // → 9 (truncates)
double d = (double) 5 / 2; // → 2.5
Wrapper Classes
Primitive Wrapper Class
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 9
int Integer
double Double
char Character
boolean Boolean
long Long
float Float
byte Byte
short Short
💡 TIP: Wrapper classes allow primitives to be used in Collections (ArrayList<Integer> not ArrayList<int>).
Autoboxing handles conversion automatically.
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 10
05 Operators in Java
Arithmetic & Assignment Operators
Operator Operation & Example
+ - * / % Arithmetic: 7/2=3 (int div), 7.0/2=3.5
++ -- Increment/Decrement: x++ (post), ++x (pre)
= Assignment: x = 10
+= -= *= /= %= Compound: x += 5 is same as x = x + 5
** No power operator — use [Link](2, 10)
Comparison & Logical Operators
Operator Meaning & Example
Equal / Not equal (for primitives;
== != use .equals() for objects)
> < >= <= Relational: (8 > 3) → true
Logical AND — short-circuits if
&& first is false
Logical OR — short-circuits if first
|| is true
! Logical NOT: !true → false
?: Ternary: int max = (a>b) ? a : b;
Type check: if (obj instanceof
instanceof String)
// == vs .equals()
String s1 = new String("hello");
String s2 = new String("hello");
[Link](s1 == s2); // → false (different objects)
[Link]([Link](s2)); // → true (same content)
// instanceof (Java 16+ pattern matching)
Object obj = "Java";
if (obj instanceof String s) {
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 11
[Link]([Link]()); // → JAVA
}
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 12
06 Input & Output
Reading Input with Scanner
import [Link];
public class InputDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link](); // read full line
[Link]("Enter age: ");
int age = [Link](); // read int
[Link]("Enter marks: ");
double marks = [Link](); // read double
[Link]("Name: %s, Age: %d, Marks: %.2f%n",
name, age, marks);
[Link]();
}
}
Scanner Methods
Method Reads
Full line as String (including
nextLine() spaces)
next() Single word (token) as String
nextInt() Integer value
nextDouble() Double value
nextFloat() Float value
nextLong() Long value
nextBoolean() Boolean (true/false)
hasNext() Returns true if more input exists
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 13
printf Format Specifiers
Specifier Type
%d int / Integer
float / double (%.2f = 2 decimal
%f %.2f places)
%s String
%c char
%b boolean
Platform newline (preferred over \n
%n in printf)
Right-aligned integer in field of
%10d width 10
Left-aligned string in field of
%-10s width 10
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 14
07 Control Flow — if / else / switch
if / else if / else
int score = 85;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B"); // prints
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}
// Ternary
String result = (score >= 50) ? "Pass" : "Fail";
switch Statement & switch Expression
// Traditional switch (Java)
int day = 3;
switch (day) {
case 1: [Link]("Mon"); break;
case 2: [Link]("Tue"); break;
case 3: [Link]("Wed"); break; // prints
default: [Link]("Other");
}
// Switch Expression (Java 14+) — cleaner!
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other";
};
[Link](dayName); // → Wednesday
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 15
08 Loops — for, while, do-while, for-each
for Loop & Enhanced for-each
// Traditional for loop
for (int i = 0; i < 5; i++) {
[Link](i + " "); // → 0 1 2 3 4
}
// Enhanced for-each (for arrays & collections)
int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) {
[Link](n + " "); // → 10 20 30 40 50
}
// Nested loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link]("%4d", i * j);
}
[Link]();
}
while & do-while
// while loop
int n = 1;
while (n <= 5) {
[Link](n++);
}
// do-while — executes at least once
int num;
Scanner sc = new Scanner([Link]);
do {
[Link]("Enter positive: ");
num = [Link]();
} while (num <= 0);
Loop Control
Statement Effect
break Exit the loop immediately
continue Skip current iteration
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 16
break label; Break out of outer/labelled loop
return Exit the entire method
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 17
09 Methods (Functions)
Defining & Calling Methods
public class MathUtil {
// Static method — called without creating object
public static int add(int a, int b) {
return a + b;
}
// Method with no return
public static void printGreeting(String name) {
[Link]("Hello, " + name + "!");
}
// Varargs — variable number of arguments
public static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static void main(String[] args) {
[Link](add(3, 4)); // → 7
printGreeting("Mudit"); // → Hello, Mudit!
[Link](sum(1,2,3,4,5)); // → 15
}
}
Method Overloading
// Same name, different parameters
static int multiply(int a, int b) { return a * b; }
static double multiply(double a, double b) { return a * b; }
static int multiply(int a, int b, int c) { return a * b * c; }
multiply(3, 4); // → 12 (calls int version)
multiply(2.5, 4.0); // → 10.0 (calls double version)
multiply(2, 3, 4); // → 24 (calls 3-arg version)
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 18
10 Arrays
1D Arrays
// Declaration & initialization
int[] marks = new int[5]; // size 5, default 0
int[] scores = {90, 85, 78, 92, 88}; // inline init
String[] names = new String[3];
// Access & modify
scores[0] = 95;
[Link](scores[2]); // → 78
[Link]([Link]);// → 5
// Traverse
for (int i = 0; i < [Link]; i++)
[Link](scores[i] + " ");
// for-each
for (int s : scores)
[Link](s + " ");
// Arrays utility
import [Link];
[Link](scores);
[Link]([Link](scores));
int[] copy = [Link](scores, 3);
2D Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link](matrix[1][2]); // → 6
[Link]([Link]); // → 3 (rows)
[Link](matrix[0].length); // → 3 (cols)
// Traverse 2D
for (int[] row : matrix)
[Link]([Link](row));
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 19
11 Strings & StringBuilder
String Basics
Strings in Java are immutable objects of the String class. Every modification creates a new object.
String name = "Mudit Bagra";
String greeting = new String("Hello");
// Length
[Link]() // → 11
// Concatenation
String full = "Hello " + name; // → Hello Mudit Bagra
String full2 = "Hi".concat(name);
// String methods
[Link]() // → MUDIT BAGRA
[Link]() // → mudit bagra
[Link](0) // → 'M'
[Link]("Bagra") // → 6
[Link](6) // → "Bagra"
[Link](0, 5) // → "Mudit"
[Link]("Bagra","Sharma") // → Mudit Sharma
[Link]() // removes leading/trailing spaces
[Link](" ") // → ["Mudit","Bagra"]
[Link]("Bagra") // → true
[Link]("Mudit") // → true
"42".equals("42") // → true
"abc".compareTo("abd") // → negative int
[Link](42) // → "42"
[Link]("42") // → 42
StringBuilder — Mutable Strings
// Use StringBuilder for heavy string manipulation (much faster)
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link](", ");
[Link]("Mudit!");
[Link](5, " World");
[Link](5, 11);
[Link]();
[Link]([Link]());
// [Link] (like printf, returns String)
String msg = [Link]("Name: %s, Age: %d", "Mudit", 20);
// Text Block (Java 15+)
String json = """
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 20
{
"name": "Mudit",
"age": 20
}
""";
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 21
12 OOP — Classes & Objects
Defining a Class
public class Student {
// Fields (instance variables)
private String name;
private int rollNo;
private double marks;
// Constructor
public Student(String name, int rollNo, double marks) {
[Link] = name;
[Link] = rollNo;
[Link] = marks;
}
// Getter methods
public String getName() { return name; }
public int getRollNo() { return rollNo; }
public double getMarks() { return marks; }
// Setter method
public void setMarks(double marks) { [Link] = marks; }
// Instance method
public String getGrade() {
return marks >= 90 ? "A" : marks >= 80 ? "B" : "C";
}
// toString override
@Override
public String toString() {
return "Student{name=" + name + ", marks=" + marks + "}";
}
}
// Creating objects
Student s1 = new Student("Mudit", 42, 95.5);
Student s2 = new Student("Alice", 10, 88.0);
[Link]([Link]()); // → Mudit
[Link]([Link]()); // → A
[Link](s1); // calls toString()
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 22
13 Constructors
Types of Constructors
public class Car {
String brand;
int year;
double price;
// 1. Default constructor (no args)
public Car() {
[Link] = "Unknown";
[Link] = 2024;
[Link] = 0.0;
}
// 2. Parameterized constructor
public Car(String brand, int year, double price) {
[Link] = brand;
[Link] = year;
[Link] = price;
}
// 3. Copy constructor
public Car(Car other) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}
// Constructor chaining with this()
public Car(String brand) {
this(brand, 2024, 500000.0); // calls 3-arg constructor
}
}
Car c1 = new Car();
Car c2 = new Car("Tesla", 2024, 4500000.0);
Car c3 = new Car(c2); // copy
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 23
14 Inheritance
extends — Single Inheritance
// Parent class
public class Animal {
String name;
public Animal(String name) { [Link] = name; }
public void eat() {
[Link](name + " is eating.");
}
public void sound() {
[Link]("Some sound...");
}
}
// Child class — inherits from Animal
public class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name); // call parent constructor
[Link] = breed;
}
@Override
public void sound() { // method overriding
[Link](name + " says: Woof!");
}
public void fetch() {
[Link](name + " fetches the ball!");
}
}
Dog d = new Dog("Rex", "Labrador");
[Link](); // inherited → Rex is eating.
[Link](); // overridden → Rex says: Woof!
[Link](); // own method
[Link](d instanceof Animal); // → true
💡 NOTE: Java supports single inheritance only (one parent class). Use interfaces to achieve multiple
inheritance-like behavior.
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 24
15 Polymorphism
Runtime Polymorphism (Method Overriding)
// Parent reference can hold child object
Animal a1 = new Dog("Rex", "Lab");
Animal a2 = new Cat("Whiskers");
[Link](); // → Rex says: Woof! (Dog's version)
[Link](); // → Whiskers says: Meow! (Cat's version)
// Process array of Animals polymorphically
Animal[] zoo = { new Dog("Rex","Lab"), new Cat("Tom") };
for (Animal a : zoo) {
[Link](); // correct version called at runtime
}
Compile-time Polymorphism (Overloading)
// Method overloading — same name, different signatures
class Calculator {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a+b+c; }
static String add(String a, String b) { return a + b; }
}
Overriding Rules
Rule Detail
Recommended — compiler checks
@Override annotation correct override
Name + parameters must match parent
Same method signature exactly
Can be covariant (subtype of parent
Return type return type)
Cannot be more restrictive than
Access modifier parent
Cannot override static, final, and private methods
Call parent's version from inside
[Link]() override
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 25
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 26
16 Abstraction & Interfaces
Abstract Classes
abstract class Shape {
String color;
public Shape(String color) { [Link] = color; }
// Abstract method — no body, MUST be overridden
public abstract double area();
// Concrete method — has body, inherited as-is
public void display() {
[Link]("Color: %s, Area: %.2f%n", color, area());
}
}
class Circle extends Shape {
double radius;
public Circle(String color, double radius) {
super(color);
[Link] = radius;
}
@Override
public double area() { return [Link] * radius * radius; }
}
Shape s = new Circle("Red", 5.0);
[Link](); // → Color: Red, Area: 78.54
Interfaces
interface Drawable {
void draw(); // implicitly public abstract
default void show() { // default method (Java 8+)
[Link]("Showing...");
}
static void info() { // static method (Java 8+)
[Link]("Drawable interface");
}
}
interface Resizable {
void resize(double factor);
}
// Class implementing multiple interfaces
class Rectangle extends Shape implements Drawable, Resizable {
double width, height;
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 27
public Rectangle(String c, double w, double h) {
super(c); width=w; height=h;
}
@Override public double area() { return width * height; }
@Override public void draw() { [Link]("Drawing rect"); }
@Override public void resize(double f) { width*=f; height*=f; }
}
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 28
17 Encapsulation & Access Modifiers
Access Modifiers
Modifier Same Class Same Package / Subclass / Other
private ✅ Yes ❌ No / ❌ No / ❌ No
(default) ✅ Yes ✅ Yes / ❌ No / ❌ No
protected ✅ Yes ✅ Yes / ✅ Yes / ❌ No
public ✅ Yes ✅ Yes / ✅ Yes / ✅ Yes
static & final Keywords
class MathConstants {
// static — belongs to class, not instance
public static final double PI = 3.14159265;
public static int instanceCount = 0;
// static method — no 'this', call via class name
public static double circleArea(double r) {
return PI * r * r;
}
}
[Link]; // → 3.14159
[Link](5); // → 78.539
// final class — cannot be extended
final class Immutable { ... }
// final method — cannot be overridden
public final void lock() { ... }
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 29
18 Exception Handling
try / catch / finally / throws
public static int divide(int a, int b) {
try {
int result = a / b;
return result;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
return -1;
} catch (Exception e) { // catch-all
[Link]();
return -1;
} finally {
[Link]("Always runs — cleanup here");
}
}
// try-with-resources (auto-closes resource)
try (Scanner sc = new Scanner(new File("[Link]"))) {
while ([Link]())
[Link]([Link]());
} catch (FileNotFoundException e) {
[Link]();
}
Checked vs Unchecked Exceptions
Type Examples & Notes
IOException, SQLException — must be
Checked Exceptions caught or declared with throws
NullPointerException,
Unchecked (RuntimeException) ArrayIndexOutOfBoundsException —
optional to catch
OutOfMemoryError, StackOverflowError
Error — not meant to be caught
Custom Exceptions
class InsufficientFundsException extends Exception {
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 30
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: need " + amount + " more");
[Link] = amount;
}
public double getAmount() { return amount; }
}
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 31
19 Collections Framework
List — ArrayList & LinkedList
import [Link].*;
// ArrayList — dynamic array, fast random access
ArrayList<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
[Link](0, "Mudit"); // insert at index
[Link](1); // remove by index
[Link]("Bob"); // remove by value
[Link]([Link](0)); // → Mudit
[Link]([Link]()); // → 2
[Link](names);
// LinkedList — fast insert/delete
LinkedList<Integer> ll = new LinkedList<>();
[Link](1); [Link](3); [Link](1, 2);
[Link](); [Link]();
Set & Map
// HashSet — no duplicates, unordered
Set<String> set = new HashSet<>();
[Link]("Java"); [Link]("Python"); [Link]("Java");
[Link]([Link]()); // → 2
// TreeSet — sorted order
Set<Integer> sorted = new TreeSet<>([Link](5,2,8,1));
[Link](sorted); // → [1, 2, 5, 8]
// HashMap — key-value pairs
Map<String, Integer> scores = new HashMap<>();
[Link]("Mudit", 95);
[Link]("Alice", 88);
[Link]("Mudit"); // → 95
[Link]("Bob", 0); // → 0
[Link]("Mudit"); // → true
for ([Link]<String, Integer> e : [Link]())
[Link]([Link]() + " → " + [Link]());
// LinkedHashMap — insertion order preserved
// TreeMap — sorted by key
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 32
20 Generics
Generic Classes & Methods
// Generic class — T is type parameter
public class Box<T> {
private T value;
public Box(T value) { [Link] = value; }
public T getValue() { return value; }
@Override
public String toString() { return "Box[" + value + "]"; }
}
Box<String> strBox = new Box<>("Hello");
Box<Integer> intBox = new Box<>(42);
[Link]([Link]()); // → Hello
[Link]([Link]()); // → 42
// Generic method
public static <T extends Comparable<T>> T max(T a, T b) {
return [Link](b) > 0 ? a : b;
}
max(10, 20); // → 20
max("apple","mango"); // → mango
// Wildcards
void printList(List<?> list) { // any type
for (Object o : list) [Link](o);
}
void sumList(List<? extends Number> l) { // Number or subtype
double sum = 0;
for (Number n : l) sum += [Link]();
}
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 33
21 File I/O — [Link] & [Link]
Reading & Writing Files
import [Link].*;
import [Link].*;
// Write using BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, File!");
[Link]();
[Link]("Second line");
} catch (IOException e) { [Link](); }
// Read using BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null)
[Link](line);
} catch (IOException e) { [Link](); }
// NIO.2 — simpler (Java 7+)
Path path = [Link]("[Link]");
[Link](path, "Content here");
String content = [Link](path);
List<String> lines = [Link](path);
// Check file existence
[Link](path);
[Link](path);
[Link](path);
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 34
22 Multithreading
Creating Threads
// Method 1: Extend Thread
class MyThread extends Thread {
@Override
public void run() {
[Link]("Thread: " + getName() + " running");
}
}
MyThread t1 = new MyThread();
[Link](); // starts new thread (do NOT call run() directly)
// Method 2: Implement Runnable (preferred)
class MyTask implements Runnable {
@Override
public void run() {
[Link]([Link]().getName());
}
}
Thread t2 = new Thread(new MyTask(), "WorkerThread");
[Link]();
// Method 3: Lambda (Java 8+)
Thread t3 = new Thread(() -> [Link]("Lambda thread"));
[Link]();
// Thread methods
[Link](1000); // sleep 1 second
[Link](); // wait for thread to finish
[Link](); // check if running
[Link](Thread.MAX_PRIORITY);
synchronized Keyword
class Counter {
private int count = 0;
// synchronized — only one thread at a time
public synchronized void increment() {
count++;
}
public int getCount() { return count; }
}
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 35
23 Java 8+ Features — Lambdas & Streams
Lambda Expressions
// Functional interface — single abstract method
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
// Lambda syntax: (params) -> expression
MathOperation add = (a, b) -> a + b;
MathOperation mult = (a, b) -> a * b;
[Link]([Link](3, 4)); // → 7
[Link]([Link](3, 4)); // → 12
// Common functional interfaces
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String,Integer> strLen = s -> [Link]();
Consumer<String> printer = s -> [Link](s);
Supplier<String> hello = () -> "Hello World";
[Link](4); // → true
[Link]("Java"); // → 4
Stream API
import [Link].*;
import [Link].*;
List<Integer> nums = [Link](1,2,3,4,5,6,7,8,9,10);
// filter + map + collect
List<Integer> result = [Link]()
.filter(n -> n % 2 == 0) // keep evens
.map(n -> n * n) // square each
.collect([Link]());
// → [4, 16, 36, 64, 100]
// reduce
int sum = [Link]().reduce(0, Integer::sum); // → 55
// count, min, max, average
long count = [Link]().filter(n->n>5).count(); // → 5
Optional<Integer> max = [Link]().max(Integer::compareTo);
// sorted, distinct, limit, skip
[Link]().sorted().distinct().limit(5).forEach([Link]::println);
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 36
// String joining
List<String> names = [Link]("Alice","Bob","Mudit");
String joined = [Link]().collect([Link](", "));
// → "Alice, Bob, Mudit"
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 37
24 Packages & Important Java APIs
Creating & Using Packages
// File: com/myapp/utils/[Link]
package [Link];
public class MathUtil {
public static int square(int n) { return n * n; }
}
// Import in another file
import [Link];
import [Link].*; // import all
[Link](5); // → 25
Key Java APIs
Package Contents Key Classes
[Link] Auto-imported always String, Math, Object, System, Integer
[Link] Utilities & ArrayList, HashMap, Scanner, Arrays, Date
Collections
[Link] Classic File I/O File, BufferedReader, FileWriter,
Serializable
[Link] Modern File I/O Path, Files, Paths
[Link] Big numbers BigInteger, BigDecimal
[Link] Modern date/time LocalDate, LocalDateTime, Duration
[Link] Networking URL, HttpURLConnection, Socket
[Link] Thread utilities ExecutorService, Future,
ConcurrentHashMap
[Link] Stream API Stream, Collectors, Optional
[Link] — Modern Date/Time API
import [Link].*;
LocalDate today = [Link]();
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 38
LocalTime now = [Link]();
LocalDateTime dt = [Link]();
[Link](today); // → 2025-03-21
[Link]([Link]()); // → 2025
LocalDate birthday = [Link](2000, 6, 15);
long days = [Link](birthday, today);
LocalDate future = [Link](30).plusMonths(1);
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 39
25 Quick Reference Cheat Sheet
JAVA CHEAT SHEET
Primitive Types Summary
Type Size Default Value
byte 1 byte 0
short 2 bytes 0
int 4 bytes 0
long 8 bytes 0L
float 4 bytes 0.0f
double 8 bytes 0.0
char 2 bytes '\u0000'
boolean — false
OOP Concepts Summary
Concept Java Implementation
Class class ClassName { ... }
Object ClassName obj = new ClassName();
Inheritance class Child extends Parent { }
Interface class X implements Interface { }
abstract class Shape { abstract
Abstract class double area(); }
private fields + public
Encapsulation getters/setters
Method overriding (@Override) +
Polymorphism overloading
Java Programming Notes • Mudit Bagra • For Academic Excellence
JAVA PROGRAMMING — Complete Study Notes | Mudit Bagra | Page 40
Constructor Same name as class, no return type
static Belongs to class, not instance
Cannot change (variable) / extend
final (class) / override (method)
Refers to parent class constructor /
super method
this Refers to current object
Collections Quick Reference
Collection Best Used For
ArrayList<T> Fast random access, dynamic array
Fast insert/delete, queue/deque
LinkedList<T> operations
Unique elements, fast lookup,
HashSet<T> unordered
TreeSet<T> Unique elements, sorted order
LinkedHashSet<T> Unique elements, insertion order
HashMap<K,V> Key-value pairs, fast lookup
TreeMap<K,V> Key-value pairs, sorted by key
Min-heap / max-heap / priority
PriorityQueue<T> processing
ArrayDeque<T> Double-ended queue, stack operations
☕ Happy Coding in Java! — Mudit Bagra ☕
Java Programming Notes • Mudit Bagra • For Academic Excellence