The whole syllabus, in one place. Every topic is explained in simple with a real-life example, followed by practice questions from easy to hard.
Where Java came from, who built it, and the "buzzwords" that show up in almost every interview.
Java is a programming language created by James Gosling and his team in 1995 at Sun Microsystems. It was originally called "Oak" (named after a tree), and was later renamed "Java" — inspired by Java coffee!
It was originally built to control smart electronic devices (like TVs and remotes), as part of a project called the "Green Project." Later, when the internet took off, Java turned out to be perfect for internet applications, because it can run on any computer — Windows, Mac, or Linux.
Think of Java as a "universal remote." Just like a universal remote works with any TV brand, code written in Java runs on any computer or OS — as long as that computer has a "Java Player" (the JVM) installed.
In 2010, Oracle Corporation acquired Sun Microsystems — so Java is now owned by Oracle.
These are the 12 features that make Java special. They come up a lot in both exams and interviews.
| Buzzword | What It Means |
|---|---|
| Simple | Easy syntax, not as complex as C++, automatic memory management |
| Object-Oriented | Everything is thought of as an object |
| Platform Independent | Write it once, run it anywhere — "Write Once, Run Anywhere" (WORA) |
| Secure | No pointers, runs inside a safe environment within the JVM |
| Robust | Strong — memory is managed automatically, errors get handled gracefully |
| Multithreaded | Can do multiple tasks at the same time |
| Architecture Neutral | Bytecode isn't tied to any one CPU type |
| Portable | The same bytecode can be carried to any device |
| High Performance | Runs fast thanks to the JIT (Just-In-Time) compiler |
| Distributed | Can work over a network (internet apps) |
| Dynamic | Can load new classes at runtime |
| Interpreted | The JVM interprets bytecode line by line |
The most important buzzword is "Write Once, Run Anywhere" — meaning: you write your Java code ONE time, and it runs everywhere — Windows, Mac, Linux — without any changes. This is Java's biggest strength.
Java is "Object-Oriented" — but what does that actually mean, and how is it different from the older style (Procedural)?
Procedural Programming (like the C language) writes a program as a list of steps/functions — do this first, then do that. Data and functions stay separate, and any function can access any data (like an open house that anyone can walk into).
Object-Oriented Programming (OOP) (like Java) bundles data together with the functions that work on it, inside an "object" — like a sealed box that you can only enter through authorized doors.
Procedural = A roadside food stall where everything happens in one open kitchen, and anyone can touch anything. OOP = A restaurant where every section (kitchen, billing, storage) has its own job and its own access — organized and secure.
| Feature | Procedural (C) | OOP (Java) |
|---|---|---|
| Program built from | Functions | Objects |
| Data & Functions | Separate | Bundled together (Encapsulation) |
| Approach | Top-down | Bottom-up |
| Security | Low (global data, anyone can access it) | High (private data, controlled access) |
| Code Reuse | Limited | High (via Inheritance) |
| Real World Modeling | Difficult | Natural — like Student, Car, BankAccount |
These three sets of letters (JDK, JRE, JVM) confuse people more than anything else — after this topic, you'll never mix them up again.
Imagine you need to both bake a cake and eat it:
JVM = your mouth + stomach, which eats and digests the cake (the actual execution). JRE = plate + cutlery + your mouth-stomach — the complete setup needed to eat the cake. JDK = the whole kitchen + ingredients + plate + cutlery + mouth-stomach — the complete setup for both BAKING and eating the cake.
| Term | Full Form | What It Does |
|---|---|---|
| JVM | Java Virtual Machine | Actually runs the bytecode (.class file). Every OS has its own JVM, but the bytecode is the same for all of them — this is what makes WORA (Write Once Run Anywhere) possible. |
| JRE | Java Runtime Environment | JVM + core libraries. Needed only to run a Java program (not for developers — this is enough for an end user). |
| JDK | Java Development Kit | JRE + compiler (javac) + debugging tools. Needed to write and compile Java programs — this is what a developer installs. |
JDK ⊃ JRE ⊃ JVM — meaning JDK is the biggest set, containing JRE, and JRE contains JVM.
The "containers" used to store data — and how we name them.
A data type tells us what kind of data we're storing — a number, a decimal, a letter, or true/false. A variable is a named box that holds that data.
Imagine your kitchen has containers of different sizes — a small one for spices (int), a big one for flour (double), and one just for yes/no notes (boolean). Each container has its own label written on it (the variable name).
| Primitive (8 types — stores the actual value) | Size |
|---|---|
byte | 1 byte |
short | 2 bytes |
int | 4 bytes — used the most |
long | 8 bytes |
float | 4 bytes — decimal |
double | 8 bytes — decimal (more precise) |
char | 2 bytes — a single character |
boolean | true / false |
Non-Primitive (Reference types) — like String, Array, and Class objects — these don't store the actual value, but rather its memory address.
int age = 20;
double marks = 89.5;
char grade = 'A';
boolean isPassed = true;
String name = "Keshav";
int is the data type (whole number), age is the variable's name, 20 is its value'A'true or false"..." — this is a reference type (not Primitive!)static keyword, shared across all objects (covered in detail in Unit 2)Symbols that operate on two values — adding, subtracting, comparing, and much more.
Operators are symbols that perform an "operation" on values — like the buttons on a calculator (+, -, ×, ÷).
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | a + b (adding), a % b (remainder — what's left over) |
| Relational | == != > < >= <= | a > b → gives true/false (comparison) |
| Logical | && || ! | a > 5 && b < 10 → both must be true (AND) |
| Assignment | = += -= *= /= | a += 5 means a = a + 5 |
| Unary | ++ -- ! | a++ → increase the value of a by 1 |
| Ternary | ? : | a > b ? a : b → if true then a, otherwise b |
int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1 (divide 10 by 3, remainder is 1)
System.out.println(a > b); // true
int max = (a > b) ? a : b; // ternary -> max = 10
Let the program make decisions (if-else) and repeat tasks (loops).
Selection (if-else, switch) = letting the program make a decision. Loop (for, while) = repeating a task again and again, without writing it out every time.
if-else = "If it's raining, take an umbrella, otherwise don't." Loop = "Keep eating until the plate is empty" — a program does exactly the same kind of thing.
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
switch (day) {
case 1: System.out.println("Monday"); break;
default: System.out.println("Invalid");
}
// for loop -> use when you know how many times to repeat
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop -> runs while the condition is true
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
// do-while -> runs once first, then checks the condition
int j = 0;
do {
System.out.println(j);
j++;
} while (j < 5);
i at 0i by 1From writing "Hello World" to seeing it on screen — the full journey inside Java.
When you write Java code, the computer can't understand it directly. It first needs to be compiled (translated) into bytecode, and then the JVM runs it.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
HelloWorld. This name must match the FILE name (HelloWorld.java)javac HelloWorld.java # turns .java into .class (bytecode)
java HelloWorld # the JVM runs the bytecode
Java is both compiled and interpreted — the source code is first compiled into bytecode, and then the JVM interprets/runs that bytecode. This is exactly what makes "Write Once, Run Anywhere" possible.
The very first and most important building block of OOP. Everything starts right here.
A class is a blueprint / design / plan that describes what an object will look like and what it will be able to do. A class itself isn't a real thing — it's just a plan.
Class = the blueprint of a house that an architect draws up. A blueprint alone doesn't give you a house to live in — it just shows the design. When an actual house gets BUILT from that blueprint, that's called an "Object."
class ClassName {
// Attributes (data) — these store state
dataType attribute1;
dataType attribute2;
// Methods (functions) — these define behavior
returnType methodName(parameters) {
// method body
}
}
class Student {
// Attributes
int id;
String name;
double marks;
// Methods
void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
}
A class is just a template. Memory is NOT allocated until an object is created. Memory is only allocated when you write: Student s1 = new Student();
How a class's blueprint becomes real in the world — meet the Object.
An object is a real-world entity that's an instance (actual copy) of a class. It has both state (data) and behavior (methods).
Class = the design/model of a phone (like "iPhone 15"). Objects = the actual phones — yours, your friend's, and the ones in the shop — each with its own color, storage, and battery percentage (its own data), but all following the same design.
ClassName objectName = new ClassName();
class Student {
int id;
String name;
void display() {
System.out.println(id + " - " + name);
}
}
public class Main {
public static void main(String[] args) {
// Creating two objects
Student s1 = new Student();
Student s2 = new Student();
// Setting each object's own values
s1.id = 101; s1.name = "Aman";
s2.id = 102; s2.name = "Riya";
s1.display(); // Output: 101 - Aman
s2.display(); // Output: 102 - Riya
}
}
new keyword do?What an object can do — that's what a Method defines.
A method is a block of code that performs a specific task. It's defined inside a class and represents an object's "behavior."
Think of a TV remote. Every button (method) does one specific job — the Volume Up button only raises the volume, the Channel button only changes the channel. Every button has its own specific function — methods work the same way.
void)returnType methodName(parameters) {
// method body
return value; // optional — only when returnType isn't void
}
class Calculator {
int add(int a, int b) {
int sum = a + b;
return sum;
}
void showMessage() {
System.out.println("Hello, Java!");
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
int result = c.add(10, 20); // gets the return value back
System.out.println("Sum = " + result);
c.showMessage(); // void method, returns nothing
}
}
int is the return type (this method will return a number). a, b are parameters — the data the method needs to do its jobvoid means this method won't return ANYTHING, it'll just do its jobStoring not just one, but many objects at once.
Just like we build an array of numbers with int[], we can store multiple objects of a class in an array too.
A classroom has 30 students — each student is a "Student object." To handle the whole class, you can create a Student[] array that stores all 30 students together.
class Student {
int id; String name;
Student(int id, String name) { this.id = id; this.name = name; }
void display() { System.out.println(id + " - " + name); }
}
public class Main {
public static void main(String[] args) {
// Array of 3 Student objects
Student[] students = new Student[3];
students[0] = new Student(1, "Aman");
students[1] = new Student(2, "Riya");
students[2] = new Student(3, "Kabir");
for (Student s : students) {
s.display();
}
}
}
nullIf you use an index without initializing it with new Student() first, you'll get a NullPointerException — this is Java's most common error, so watch out for it!
When an object is created, who sets its initial values? Meet the Constructor.
A constructor is a special method that has the same name as the class, and gets called automatically the moment an object is created — to set the object's initial values.
When you create an account on any website (Instagram, or anything else), you're immediately asked for your name, email, and password, and all of that gets set the moment the account is created. This "setup process" is exactly like a Constructor.
voidclass Student {
int id;
String name;
// Constructor
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " - " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Aman");
Student s2 = new Student(102, "Riya");
s1.display(); // 101 - Aman
s2.display(); // 102 - Riya
}
}
this.id = the object's own id (instance variable), id (right side) = what came in as the parameter. this tells them apartclass Student {
int id; String name;
Student(int id, String name) { this.id = id; this.name = name; }
Student(Student s) { // copy constructor
this.id = s.id;
this.name = s.name;
}
}
Who connects a method call to its body, and when?
Binding means: "when you call a method, how does the JVM know WHICH method body to run?" There are 2 types, based on when this decision gets made.
| Type | When It's Decided | Example |
|---|---|---|
| Static Binding (Early) | Compile Time | static, private, final methods, Overloading |
| Dynamic Binding (Late) | Run Time | Method Overriding (parent reference → child object) |
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.println("Dog barks"); } }
Animal a = new Dog();
a.sound(); // "Dog barks" -> decided at RUNTIME = Dynamic Binding
Overloading = which method will run is already known at compile time (Static Binding). Overriding = the JVM looks at the actual object at runtime (not the reference type!) and decides — that's why it's Dynamic Binding.
Members that belong to the whole class, not to any one object — SHARED across all of them.
The static keyword means: this member belongs to the class, not to an object. All objects share the exact same copy.
A college's name ("GEC Jehanabad") is the SAME for every student — that's like "static" (a property of the whole college). But every student's roll number is different — that's like "instance" (non-static).
class Counter {
static int count = 0; // SHARED across all objects
Counter() { count++; }
}
public class Main {
public static void main(String[] args) {
new Counter(); new Counter(); new Counter();
System.out.println(Counter.count); // 3
}
}
count variable that every Counter object shares — it increases every time a new object is createdWho can access what — that's what Access Modifiers control.
Access Modifiers are like "permission levels" — they decide who can see or use which data/method.
private = your personal diary (only you can read it). public = your public Instagram post (everyone can see it). protected = a family group chat that only family members can see.
| Modifier | Same Class | Same Package | Subclass (diff package) | Everywhere |
|---|---|---|---|---|
private | ✅ | ❌ | ❌ | ❌ |
| default (write nothing) | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ | ✅ |
public class Student {
private int id; // only inside the Student class
String name; // default: same package only
protected double marks; // same package + subclasses
public String college; // accessible from anywhere
}
Java's way of saying "myself."
The this keyword always refers to the current object — meaning "the object currently being worked on."
this(...))class Student {
int id; String name;
Student(int id, String name) {
this.id = id; // this.id = the object's variable, id = the parameter
this.name = name;
}
Student() {
this(0, "Unknown"); // constructor chaining
}
}
this.id = the object's own property. Right side id = what came in as the parameter. Sharing the same name causes confusion, so we use this to make it clearHow Java cleans up after itself — without you having to say a word.
In C/C++, you have to free memory manually. Java doesn't work that way — when an object isn't being used at all (no variable points to it anymore), Java automatically cleans up its memory. This process is called Garbage Collection (GC).
Imagine a robot cleaner that runs on its own and picks up anything lying around unused in the house and throws it away — without asking you. That's exactly what the Garbage Collector does.
Student s1 = new Student();
s1 = null; // nothing refers to the old Student object anymore
// -> it has become "eligible" for Garbage Collection
System.gc(), but there's no guarantee it will run right awayfinalize() — GC calls this before destroying an object (for cleanup) — but it's deprecated since Java 9+ and shouldn't be used anymoreThis is a big advantage Java has over C/C++ — the risk of memory leaks drops a lot, because there's no chance of forgetting to free something manually.
A class inside another class — when and why do we use this?
In Java, you're allowed to define a class inside another class. This is used when a class is only ever going to be used in one place — it improves organization and encapsulation.
class Outer {
int data = 10;
class Inner { // non-static inner class
void show() {
System.out.println("Outer data: " + data);
}
}
static class StaticNested { // static nested class
void display() { System.out.println("I am static nested"); }
}
}
public class Main {
public static void main(String[] args) {
Outer o = new Outer();
Outer.Inner in = o.new Inner(); // outer object IS NEEDED
in.show();
Outer.StaticNested sn = new Outer.StaticNested(); // outer object is NOT needed
sn.display();
}
}
The most-used class of all — the inside story of String.
String is a class (not a primitive type!) that stores a sequence of characters. The most important thing to know: Java Strings are immutable — once created, they never change. Any "change" actually creates a NEW String object.
Think of a printed poster — you can't edit it, it's fixed once printed. If you want a change, you'll need to print a new poster. The same thing happens with String — "changing" it creates a NEW object.
String s1 = "hello"; // literal -> stored in the String Pool
String s2 = new String("hello"); // new -> a separate object on the heap
System.out.println(s1 == s2); // false (different memory)
System.out.println(s1.equals(s2)); // true (the content is the same)
| Method | What It Does |
|---|---|
length() | length (how many characters) |
charAt(i) | the character at index i |
substring(a,b) | extracts a portion |
toUpperCase()/toLowerCase() | changes the case |
trim() | removes leading/trailing spaces |
split(regex) | splits into an array |
Writing s1.concat("world") does NOT change s1 itself — it creates a new String. If you don't assign it back (s1 = s1.concat("world")), the original s1 stays exactly the same.
When you need to make a lot of changes/concatenations (like inside a loop), use StringBuilder — it modifies the SAME object instead of creating a new one every time:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java"); // modifies the same object
System.out.println(sb); // Hello Java
How one class "inherits" features from another class.
Inheritance is a mechanism where a NEW class (child/subclass) automatically gets the properties and behaviors (fields and methods) of an EXISTING class (parent/superclass).
Just like you "inherit" traits such as eye color and height from your parents without creating them yourself — the Dog class similarly "inherits" the eat() method and the color property from the Animal class, without writing them again.
// Parent Class (Superclass)
class Animal {
String color = "Brown";
void eat() { System.out.println("Animal is eating"); }
}
// Child Class (Subclass)
class Dog extends Animal {
void bark() { System.out.println("Dog is barking"); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited method
d.bark(); // its own method
System.out.println(d.color); // inherited field
}
}
extends keyword shows that Dog is inheriting from AnimalUse the extends keyword. Private members do NOT get inherited. Constructors are never inherited. Inheritance represents an IS-A relationship ("Dog IS-A Animal").
The different "shapes" inheritance can take — single, multilevel, hierarchical.
| Type | Structure | Explanation |
|---|---|---|
| Single | A → B | One class inherits from one parent (Dog extends Animal) |
| Multilevel | A → B → C | A chain — C inherits from B, B inherits from A |
| Hierarchical | A → B, A → C, A → D | Multiple classes inherit from the SAME parent |
In Java, a class CANNOT extend two classes at once (class C extends A, B ❌ compile error). This avoids the "Diamond Problem" — if both A and B had the same method, there'd be confusion about which one to use.
Java solves this problem with Interfaces — a class can implement MULTIPLE interfaces (covered in detail in the Interface topic later in this unit).
How a child class "calls back" to its parent class.
The super keyword lets a child class refer to its parent class — whether that's a variable, a method, or a constructor.
super(...) — this must always be the FIRST line in the child's constructorclass Animal {
String color = "Brown";
Animal(String color) { this.color = color; }
void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
Dog(String color) {
super(color); // calling Animal's constructor
}
void sound() {
super.sound(); // calling Animal's sound()
System.out.println("Dog barks");
}
}
| Parent Member | Does the Child Get It? |
|---|---|
public / protected | ✅ Yes |
| default (package) | ✅ same package only |
private | ❌ No (it exists in memory, but there's no direct access) |
| Constructors | ❌ Never |
static members | ✅ Accessed via the class name |
The parent of every Java class, and the methods every object gets for free.
Sometimes we DON'T want a class or method to be extended/overridden any further.
The final keyword means "this is the last stop, nothing further". It's used in 3 places:
final class → nobody can extend itfinal method → no child class can override itfinal variable → this becomes a CONSTANT — once its value is set, it can never changefinal class Vehicle { // can't extend this
// ...
}
// class Car extends Vehicle { } ❌ Compile Error!
class Bike {
final void start() { // can't override this
System.out.println("Bike started");
}
}
final = "this is the last stop, no going further" — whether it's a class, a method, or a variable, it always means "no more change/extension."
"Poly" = many, "morph" = forms. One name, many forms.
Polymorphism means "many forms" — the same interface (like a method name) can be used in different ways. In Java, this happens in 2 ways: Overloading (compile-time) and Overriding (run-time, next topic).
Imagine you say "print" — if it's a photo, the printer prints a photo; if it's a document, it prints a document. The SAME "print" command, but the result depends on the data. That's Overloading!
class Calculator {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
double add(double a, double b) { return a + b; }
}
public class Main {
public static void main(String[] args) {
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20)); // 30
System.out.println(obj.add(10, 20, 30)); // 60
System.out.println(obj.add(10.5, 20.5)); // 31.0
}
}
When a child class REDEFINES a parent's method in its own way.
Overriding happens when a child class redefines its parent class's method with the SAME name and SAME parameters — but gives it its own behavior. It's decided at runtime which version runs, based on the actual object.
class Animal {
void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Reference type is Animal, object is Dog
a.sound(); // Output: "Dog barks"
}
}
| Feature | Overloading | Overriding |
|---|---|---|
| When It's Decided | Compile-time | Run-time |
| Where It Happens | Same class | Different classes (Inheritance) |
| Parameters | Must be different | Must be the same |
| Binding | Static | Dynamic |
private, static, and final methods CANNOT be overriddenAnimal a = new Dog();, which method runs when you call a.sound()?Show WHAT happens, hide HOW it happens.
Abstraction means hiding the implementation details and showing only the essential features.
When you drive a car, you just need to know the steering, accelerator, and brake (WHAT the car does). You don't need to know exactly what's happening inside the engine (HOW). That's Abstraction!
A class whose object CANNOT be created. It can contain 2 kinds of methods:
| What's Allowed Inside an Abstract Class? | Allowed? |
|---|---|
| Abstract Methods | ✅ |
| Concrete Methods | ✅ |
| Constructors | ✅ |
| Instance Variables | ✅ |
| Static Methods | ✅ |
| Object Creation | ❌ |
abstract class Shape {
abstract void draw(); // abstract method (no body)
void color() { // concrete method (has a body)
System.out.println("Color is set");
}
}
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); } // had to implement it
}
draw() — otherwise Circle would also have to be made abstractnew Shape() ❌ will error outA "contract" that tells a class what it must do.
An interface is a blueprint of a class — a "contract" that says which methods a class must implement, but doesn't say HOW to do it. It only contains abstract methods (public + abstract by default) and constants.
Think of a job contract — "the employee must show up and hit their targets" — it sets EXPECTATIONS, but exactly how they get there is up to the employee. An interface is exactly that kind of contract.
interface Animal {
void sound(); // default: public and abstract
}
class Dog implements Animal {
public void sound() { System.out.println("Dog barks"); }
}
class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Output: Dog barks
}
}
interface keyword is used instead of classimplements it — and it's COMPULSORY to define ALL of its abstract methods| Type | Has a Body? | Since |
|---|---|---|
| Abstract Method | No | Always |
| Default Method | Yes | Java 8 |
| Static Method | Yes | Java 8 |
| Private Method | Yes (only as a helper inside the interface) | Java 9 |
interface Vehicle {
void start(); // abstract
default void stop() { // default method — has a body
System.out.println("Vehicle Stopped");
}
}
class Car implements Vehicle {
public void start() { System.out.println("Car Started"); }
// no need to override stop() -> the default will be used
}
A class can implement MULTIPLE interfaces — this is how Java solves the multiple inheritance problem:
interface Runnable2 { void run(); }
interface Serializable2 { void save(); }
class MyTask implements Runnable2, Serializable2 {
public void run() { System.out.println("Running"); }
public void save() { System.out.println("Saving"); }
}
Both give you "abstraction" — but when should you use which one?
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract | interface |
| Methods | Abstract + Concrete | Abstract only (default/static too, in Java 8+) |
| Instance Variables | ✅ | ❌ (constants only) |
| Constructor | ✅ | ❌ |
| Multiple Inheritance | ❌ (can only extend one class) | ✅ (can implement many interfaces) |
| Object Creation | ❌ | ❌ |
| State (Data) | Can maintain it | No |
| Use Case | Need common implementation + state | Just need to define a contract/behavior |
An interface with only ONE abstract method is called a "Functional Interface." We use a Lambda Expression to implement it in a compact way.
@FunctionalInterface
interface MyFunctional {
void show(String msg);
}
public class Test {
public static void main(String[] args) {
MyFunctional mf = (msg) -> System.out.println(msg); // Lambda!
mf.show("Hello Java 8");
}
}
(msg) -> System.out.println(msg) — this is a compact way of writing a method, without creating a whole class. Read -> as "goes to": "msg goes to System.out.println(msg)."
How do we define the relationship between two classes?
IS-A (Inheritance) = "this IS A type of that thing" → Dog IS-A Animal. HAS-A (Composition) = "this HAS another thing inside it" → Car HAS-A Engine.
| Aspect | IS-A (Inheritance) | HAS-A (Composition) |
|---|---|---|
| Keyword | extends | Holding an object as a field |
| Coupling | Tight (more tightly linked) | Loose (less tightly linked) |
| Flexibility | Less | More |
// IS-A
class Animal { }
class Dog extends Animal { } // Dog IS-A Animal
// HAS-A
class Engine { }
class Car {
Engine engine = new Engine(); // Car HAS-A Engine
}
Whenever possible, Composition (HAS-A) is considered better than Inheritance (IS-A) — it keeps code loosely coupled and flexible. Only use IS-A when there's a TRUE parent-child relationship.
Keeping data in a secure "box" — the fourth pillar of OOP.
Encapsulation means wrapping data (variables) and code (methods) into ONE unit, and protecting the data from direct access.
Think of a medicine capsule — you don't eat the medicine inside it directly, you take the whole capsule (in a controlled way). Similarly, we don't access a class's data directly, we go through "getter/setter" methods.
class Student {
private int id; // private -> no direct access from outside
private String name;
public int getId() { return id; } // GETTER
public void setId(int id) { this.id = id; } // SETTER
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
obj.id = 5 — it'll cause a compile errorMake variables private → provide public getters/setters → access/modify data only through those methods.
Organizing classes into folders — essential for big projects.
A package is a folder/namespace that groups related classes together — it avoids naming conflicts and improves organization.
Just like you create folders like "College," "Projects," and "Photos" on your laptop to organize files — packages organize Java classes the same way.
package mypack; // must be the very first line
public class Calculator {
public int add(int a, int b) { return a + b; }
}
import mypack.Calculator; // import a specific class
// import mypack.*; // or import the whole package
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(5, 3));
}
}
CLASSPATH is an environment variable that tells the JVM/compiler where to look for .class files (user-defined classes/packages).
javac -d . Calculator.java # -d . creates the mypack/ folder
javac Main.java
java Main
In real projects, package names follow the reverse-domain style, like com.company.project — this avoids global naming conflicts.
When something goes wrong in a program — what do we call it, and what types are there?
An exception is an unwanted/unexpected event that stops the program's normal flow (like dividing by 0, or accessing an invalid array index).
Imagine you're driving and suddenly get a flat tire — that's an "exception." You can stop, put on the spare tire, and continue (handle it) — there's no need to cancel the whole trip.
| Aspect | Error | Exception |
|---|---|---|
| Meaning | A serious problem, generally can't be handled | A problem that CAN be caught and handled |
| Cause | System-level (JVM/hardware) | Program-level (logic/input issue) |
| Example | OutOfMemoryError, StackOverflowError | ArithmeticException, NullPointerException |
| Recovery | Generally not possible | Can be recovered with try-catch |
| Aspect | Checked Exception | Unchecked Exception |
|---|---|---|
| When It's Caught | Compile time | Runtime |
| Is Handling Required? | Yes (try-catch or throws) | Not required (but good practice) |
| Example | IOException, SQLException | ArithmeticException, NullPointerException |
Java's way of safely handling risky code.
try = "attempt this risky operation." catch = "if something goes wrong, catch it here." finally = "no matter what happens, this part ALWAYS runs" (for cleanup).
public class Main {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // exception gets thrown here
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This always runs (cleanup)");
}
System.out.println("Program continues normally");
}
}
ArithmeticException| Keyword | Meaning |
|---|---|
try | The block of risky code |
catch | Handles the exception |
finally | ALWAYS runs — for cleanup |
throw | Manually raises an exception |
throws | Declares in the method signature that an exception might occur |
Two very similar-looking keywords, but completely different jobs.
throw = "I am throwing an exception right now" (an action, used at one specific point). throws = "this method MIGHT throw an exception, watch out" (a warning, written in the method signature).
void checkAge(int age) throws Exception { // throws -> declaring the possibility
if (age < 18) {
throw new Exception("Not eligible to vote"); // throw -> manually raising it
}
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
try {
new Main().checkAge(15);
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
try {
// risky code
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
You can handle multiple exception types in a single catch block, separated by | (pipe).
When more than one kind of exception can occur, or when one try sits inside another.
try {
int[] arr = new int[5];
arr[10] = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error: " + e.getMessage());
} catch (Exception e) { // most general, always LAST
System.out.println("Some other error: " + e.getMessage());
}
Catch specific exceptions FIRST, and the general one (Exception) always LAST — otherwise you'll get a compile error ("unreachable catch block").
try {
System.out.println("Outer try");
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch: " + e.getMessage());
}
int[] arr = new int[3];
arr[5] = 10; // gets caught by the outer catch
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch: " + e.getMessage());
}
void process() throws Exception {
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Logging error...");
throw e; // passing the same exception along
}
}
Sometimes you want to log or act on something locally, but leave the final handling to the calling method — that's why we re-throw.
Building your own exception class — for when the built-in exceptions aren't enough.
Sometimes you need your own specific error message (like "Insufficient Balance"). For this, you can extend the Exception class and create your own exception.
// Custom checked exception
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String message) {
super(message); // pass the message to the Exception class
}
}
class BankAccount {
double balance = 1000;
void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance!");
}
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
try {
acc.withdraw(5000);
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
getMessage() worksExtend Exception = Checked exception (must be handled). Extend RuntimeException = Unchecked exception (handling is optional).
Before starting multithreading, understand the difference between these two.
Process = an entire restaurant (its own kitchen, staff, resources — independent). Thread = the workers inside the restaurant (waiter, chef) who SHARE the SAME kitchen/resources, each doing different work at the same time.
| Aspect | Process | Thread |
|---|---|---|
| Meaning | An independently running program, with its own memory | A lightweight part of a process, sharing its memory |
| Memory | Separate | Shared with sibling threads |
| Communication | Slow (needs IPC) | Fast (shared memory) |
| Creation Cost | Heavy | Light |
| Example | Chrome and VS Code = 2 processes | Chrome downloading a file while also rendering the page = 2 threads |
It achieves parallelism → better use of the CPU, and independent tasks execute faster (like a game rendering graphics while also processing user input, at the same time).
Two ways to start multithreading in Java.
class MyThread extends Thread {
public void run() { // write the task inside run()
for (int i = 1; i <= 3; i++) {
System.out.println("MyThread: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // start() -> creates a new thread, calls run() inside it
}
}
class MyTask implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("MyTask: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyTask());
t1.start();
}
}
Implementing Runnable is better, because in Java a class can only extend ONE class. If you extend Thread, you can't extend any other class. Runnable doesn't have this restriction.
Always call start(), NEVER call run() directly — calling run() directly does NOT create a new thread, it just runs like a normal method call.
A thread's "life" — from birth to death.
| State | Meaning |
|---|---|
| New | The thread object has been created, start() hasn't been called yet |
| Runnable | Ready to run, waiting for the CPU |
| Running | Currently actually executing on the CPU |
| Blocked/Waiting | Waiting for a resource/lock, or paused because of wait()/sleep() |
| Terminated | The run() method has finished |
Giving threads a hint about "who runs first," and stopping them.
Every thread has a priority (1 to 10) that gives the scheduler a "hint" — it's not a GUARANTEE.
| Constant | Value |
|---|---|
Thread.MIN_PRIORITY | 1 |
Thread.NORM_PRIORITY | 5 (default) |
Thread.MAX_PRIORITY | 10 |
Thread t1 = new Thread(new MyTask());
t1.setPriority(Thread.MAX_PRIORITY);
System.out.println(t1.getPriority());
class MyTask extends Thread {
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Working... " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyTask t = new MyTask();
t.start();
Thread.sleep(2500);
t.interrupt(); // interrupting the sleeping thread
}
}
InterruptedException gets thrown immediatelyWhen two threads touch the SAME data, how do we avoid the resulting confusion (race condition)?
When multiple threads access/modify shared data AT THE SAME TIME, the data can become inconsistent (wrong) — this is called a "Race Condition."
Imagine 2 people trying to withdraw money from the same bank account AT THE SAME TIME, and both think the balance is currently ₹1000. If both withdraw simultaneously without checking, the balance ends up wrong. synchronized puts everyone in a "line/queue" — only ONE person can transact at a time.
class Counter {
int count = 0;
synchronized void increment() { // only ONE thread at a time
count++;
}
}
class MyThread extends Thread {
Counter counter;
MyThread(Counter c) { this.counter = c; }
public void run() {
for (int i = 0; i < 1000; i++) counter.increment();
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
MyThread t1 = new MyThread(counter);
MyThread t2 = new MyThread(counter);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("Final count: " + counter.count); // reliably 2000
}
}
Without synchronized, both threads can modify the same variable simultaneously, and the final result can come out wrong (some random number instead of 2000, like 1850). synchronized reliably keeps it at 2000.
How threads "talk" to each other — wait and notify.
Java provides wait(), notify(), and notifyAll() methods (defined in the Object class) so threads can coordinate with each other — like in the Producer-Consumer problem.
class SharedResource {
synchronized void produce() throws InterruptedException {
System.out.println("Producing...");
wait(); // releases the lock and waits
System.out.println("Resumed after notify");
}
synchronized void consume() {
System.out.println("Consuming and notifying...");
notify(); // wakes up one waiting thread
}
}
| Method | What It Does |
|---|---|
wait() | The current thread releases its lock and waits |
notify() | Wakes up ONE waiting thread |
notifyAll() | Wakes up ALL waiting threads |
join() | Makes the calling thread wait until the target thread finishes |
sleep(ms) | Pauses the current thread for the given number of milliseconds |
Create a thread via the Thread class or the Runnable interface → use start(), not run() → avoid race conditions with synchronized → threads communicate using wait()/notify().
Writing data to a file and reading it back, from a Java program.
"Stream" means a flowing line of data (like a stream of water) — from a file into a program, or from a program into a file.
| Aspect | Byte Stream | Character Stream |
|---|---|---|
| Handles | Raw binary data (images, video, any file) | Text data |
| Base classes | InputStream/OutputStream | Reader/Writer |
| Unit | 1 byte | 1 character (Unicode) |
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
// Writing
FileWriter fw = new FileWriter("data.txt");
fw.write("Hello Java File Handling!");
fw.close();
// Reading (line by line, using BufferedReader — it's fast)
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
Getting "info" about a file, and reading/writing at any position within it.
The File class does NOT read/write content — it's only for a file/folder's metadata and management (exists, delete, rename, list, create folder).
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = new File("data.txt");
System.out.println("Exists: " + f.exists());
System.out.println("Size (bytes): " + f.length());
f.delete();
new File("newFolder").mkdir();
}
}
RandomAccessFile lets you read/write at ANY position in a file — not just sequentially from start to end.
RandomAccessFile raf = new RandomAccessFile("data.txt", "rw");
raf.seek(5); // move the pointer to position 5
raf.writeBytes("XYZ"); // overwrite from there
raf.seek(0);
System.out.println(raf.readLine());
raf.close();
Beyond arrays — Java's "smart" data structures.
A Collection is a group of objects — like a smart, resizable array. The Collections Framework gives you ready-made data structures (List, Set, Queue, Map) that are MORE powerful than plain arrays (auto-resize, sorting, and searching built in).
Map (HashMap, TreeMap) — key-value pairs. It's technically NOT part of the Collection interface — it has a separate hierarchy — but it is part of the framework.
The most-used collection classes — when to use which one.
A resizable array — allows duplicates and maintains insertion order.
import java.util.*;
ArrayList list = new ArrayList<>();
list.add("Aman"); list.add("Riya"); list.add("Aman"); // duplicate allowed
System.out.println(list); // [Aman, Riya, Aman]
System.out.println(list.get(0)); // Aman
HashSet set = new HashSet<>();
set.add("A"); set.add("B"); set.add("A"); // the duplicate gets IGNORED
System.out.println(set); // order isn't guaranteed, e.g. [A, B]
TreeSet ts = new TreeSet<>();
ts.add(30); ts.add(10); ts.add(20);
System.out.println(ts); // [10, 20, 30] -> automatically SORTED
HashMap map = new HashMap<>();
map.put(1, "Aman");
map.put(2, "Riya");
System.out.println(map.get(1)); // Aman
| Class | Duplicates? | Order | Sorted? | Best For |
|---|---|---|---|---|
| ArrayList | Yes | Insertion order | No | Fast index access |
| LinkedList | Yes | Insertion order | No | Frequent insert/delete |
| HashSet | No | No guarantee | No | Fast unique storage |
| TreeSet | No | Sorted | Yes | Unique + sorted data |
| PriorityQueue | Yes | Priority-based | Yes | Task scheduling |
List = order matters, duplicates are fine (like a task list). Set = duplicates are NOT wanted (unique roll numbers). Map = key-value pairs (roll number → name, like a dictionary).
Talking to a MySQL/Oracle database from a Java program.
JDBC (Java Database Connectivity) is an API that lets Java programs connect to, query, and update a database, using SQL.
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Step 1
Connection con = DriverManager.getConnection( // Step 2
"jdbc:mysql://localhost:3306/college_db", "root", "password");
Statement stmt = con.createStatement(); // Step 3
ResultSet rs = stmt.executeQuery("SELECT * FROM students"); // Step 4
while (rs.next()) { // Step 5
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
con.close(); // Step 6
} catch (Exception e) {
e.printStackTrace();
}
}
}
String sql = "INSERT INTO students (id, name, marks) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 6);
ps.setString(2, "Neha");
ps.setDouble(3, 91.5);
ps.executeUpdate();
With Statement you build the query string manually — this carries a SQL Injection risk. With PreparedStatement, ? placeholders let you set values safely. In real projects, ALWAYS use PreparedStatement.
| Method | Used For | Return |
|---|---|---|
executeQuery() | SELECT | ResultSet |
executeUpdate() | INSERT, UPDATE, DELETE | int (how many rows were affected) |