A CO MPLETE FIELD GUIDE
Java
from syntax to systems
Variables, control flow, methods, object-oriented
programming, exceptions, collections — everything a
developer needs, built up from scratch.
7 30+ Real
CORE SECTIONS CONCEPTS COVERED WORKING EXAMPLES
JAVA & OOP C ON TE N TS
O VERVIEW
What's inside
# Section Covers
01 Foundations How Java runs · Variables · Operators · Strings
02 Control Flow Conditions · Loops · Arrays
03 Methods Defining · Parameters · Return values · Overloading
04 Object- Classes · Constructors · Encapsulation · Inheritance ·
Oriented Polymorphism · Abstraction
Programming
05 Interfaces Contracts · Real-world payment example · Abstract vs Interface
06 Beyond the Exception handling · ArrayList · HashMap · String methods
Basics
07 Reference Quick-reference cheat sheet
HO W TO RE AD THIS GUIDE
Each section builds on the last. If you already know Java syntax, jump straight to Section
04 (OOP). The reference page at the end is designed to be kept and revisited.
02
01
SECTION ONE
Foundations
Java syntax from scratch — how the language runs, what
you can store, and how you talk to it.
JAVA & OOP FOU N D ATI ON S · 01
SE CTIO N 0 1
How Java Runs
Java's famous promise: write once, run anywhere. Your source file compiles to
bytecode once, then any JVM — on any OS — can execute it.
javac java
[Link] [Link] JVM
source code bytecode any platform
runs it
Figure 1 — Source is compiled to bytecode once. Any JVM on any OS can run it.
Term What it is
JDK Java Development Kit — install this. Contains the compiler (javac) + everything
below.
JRE Java Runtime Environment — what's needed to run Java programs.
JVM Java Virtual Machine — the engine that executes bytecode. Runs on Windows,
Mac, Linux.
YOUR FIRST PROGRAM
public class Hello {
public static void main(String[] args) {
[Link]("Hello, Java!"); // entry point
}
}
03
JAVA & OOP FOU N D ATI ON S · 02
SE CTIO N 0 1
Variables & Types
Java is statically typed — every variable must declare its type before use. The
compiler then catches type mismatches before your program runs.
VARIABLES & PRIMITIVE TYPES
// primitives — stored directly in memory
int age = 23;
double salary = 45000.50;
boolean hired = true;
char grade = 'A';
// String is an object (capital S), not a primitive
String name = "Asha";
// final = constant, cannot be reassigned
final double TAX_RATE = 0.18;
Type Stores Default Example
int Whole numbers 0 42
double Decimals 0.0 3.14
boolean true / false false true
char One character '\u0000' 'X'
String Text (object) null "hello"
STRING CO MPARISO N TRAP
Never use == to compare Strings — it checks memory address, not content. Always use
.equals() : write [Link]("Asha"), never name == "Asha".
04
JAVA & OOP FOU N D ATI ON S · 03
SE CTIO N 0 1
Operators
Operators are the symbols that act on values. Java evaluates them in the standard
mathematical precedence — but when in doubt, use parentheses.
Category Operators Example
Arithmetic + - * / % 10 % 3 → 1 (remainder)
Assignment = += -= *= /= x += 5 same as x = x + 5
Comparison == != > < >= <= returns true or false
Logical && || ! age >= 18 && hasId
Increment ++ -- i++ adds 1 to i
Ternary ? : x > 0 ? "pos" : "neg"
OPERATORS IN ACTION
int price = 100;
int discount = 20;
double final_price = price - (price * discount / 100.0);
// ternary — one-line if/else
String label = (final_price > 50) ? "Premium" : "Budget";
05
JAVA & OOP FOU N D ATI ON S · 04
SE CTIO N 0 1
Strings
Strings in Java are objects — immutable sequences of characters. Every method call
returns a new String; the original never changes.
ESSENTIAL STRING OPERATIONS
String name = "Java Developer";
// length
int len = [Link](); // 14
// case
[Link](); // "JAVA DEVELOPER"
[Link](); // "java developer"
// search
[Link]("Java"); // true
[Link]("Java"); // true
[Link]("Dev"); // 5
// transform
[Link]("Java","Python"); // "Python Developer"
[Link](); // removes leading/trailing spaces
[Link](0, 4); // "Java"
STRING CO NCATE NATIO N
Use + to join strings: String msg = "Hello " + name; . For many joins in a loop, use
StringBuilder instead — far more efficient than creating many String objects.
06
02
SE CTIO N TWO
Control Flow
Decisions, repetition, and collections — the logic that makes
programs do real work.
JAVA & OOP C ON TROL FLOW · 01
SE CTIO N 0 2
Conditions
Conditions let your program make decisions. Use if/else when evaluating ranges or
complex logic, and switch when matching one variable against fixed values.
IF · ELSE IF · ELSE
int marks = 76;
String grade;
if (marks >= 90) { grade = "A"; }
else if (marks >= 75) { grade = "B"; }
else if (marks >= 60) { grade = "C"; }
else { grade = "F"; }
SWITCH — CLEANER FOR FIXED CHOICES
switch (grade) {
case "A": [Link]("Distinction"); break;
case "B": [Link]("First class"); break;
default: [Link]("Pass"); break;
}
ALWAY S INCLUDE BRE AK IN SWITCH
Missing a break causes fall-through — execution continues into the next case even if it
does not match. A common source of bugs.
07
JAVA & OOP C ON TROL FLOW · 02
SE CTIO N 0 2
Loops
Loops execute a block repeatedly. Choose the right loop for the situation — using the
wrong one is one of the most common readability mistakes.
FOR LOOP — WHEN YOU KNOW THE COUNT
for (int i = 1; i <= 5; i++) {
[Link]("Attempt " + i);
}
WHILE LOOP — WHEN YOU DO NOT KNOW THE COUNT
int otp = 0;
while (otp != 1234) {
otp = [Link](); // keep asking until correct
}
FOR-EACH — CLEANEST WAY TO ITERATE A LIST
String[] skills = {"Java", "Git", "SQL"};
for (String skill : skills) {
[Link](skill);
}
BRE AK AND CO NTINUE
break exits the loop immediately. continue skips the current iteration and moves to the
next.
08
JAVA & OOP C ON TROL FLOW · 03
SE CTIO N 0 2
Arrays
An array is a fixed-size, ordered list of values of the same type. Once created, its size
cannot change — that's the trade-off for raw speed.
scores
88 74 91 65 82
[0] [1] [2] [3] [4]
Figure 2 — An array of 5 integers. Indices start at 0.
DECLARING AND USING ARRAYS
// declare + initialise in one line
int[] scores = {88, 74, 91, 65, 82};
// access by index (starts at 0)
[Link](scores[0]); // 88
[Link](scores[4]); // 82
// length property
[Link]([Link]); // 5
INDE X O UT O F BO UNDS
Accessing a missing index (e.g. scores[10] on a 5-element array) crashes with
ArrayIndexOutOfBoundsException at runtime. Always check .length first.
09
03
SECTION THREE
Methods
Reusable, named blocks of logic — the building block of
well-structured programs.
JAVA & OOP ME TH OD S · 01
SE CTIO N 0 3
Methods
A method packages logic so you can name it, call it, and reuse it. Every Java program
needs at least one — the main method — and well-designed programs are built from
many small focused ones.
ANATOMY OF A METHOD
// access return type name parameters
public static double applyDiscount(double price, int pct) {
return price - (price * pct / 100.0);
}
// void = no return value; just does work
public static void printReceipt(String item, double price) {
[Link](item + ": ₹" + price);
}
CALLING METHODS
double finalPrice = applyDiscount(1000.0, 20); // 800.0
printReceipt("Laptop", finalPrice); // Laptop: ₹800.0
METHOD OVERLOADING — SAME NAME, DIFFERENT PARAMETERS
// Java picks the right version by argument types
static double tax(double amt) { return amt * 0.18; }
static double tax(double amt, double rate) { return amt * rate; }
static int tax(int rupees) { return (int)(rupees * 0.18); }
SINGLE RE SPO NSIBILITY
A good method does exactly one thing and does it well. If you find yourself writing a
method called doEverything() , split it up.
10
SECTIO N FO UR
04
Object-Oriented
Programming
The four pillars that separate structured code from scalable
systems.
JAVA & OOP OOP · 01
SE CTIO N 0 4
Why OOP Exists
Procedural code works for small programs — but as a project grows, unrelated data
and functions tangle together. Object-Oriented Programming fixes this by modelling
your software as objects that own their data and their behaviour.
WITHOUT OOP WITH OOP
BankAccount
name, balance, rate
deposit() { ... } – balance
withdraw() { ... } + deposit()
applyInterest() { ... } + withdraw()
data & logic floating separately data + logic sealed together
Figure 3 — OOP bundles related data and behaviour into a self-managing object.
Pillar Core idea
Encapsulation Hide internal data; expose only safe, controlled access
Inheritance A child class reuses everything from its parent, then extends it
Polymorphism One method name, many behaviours depending on the object
Abstraction Define what an object must do, not how it does it
11
JAVA & OOP OOP · 02
SE CTIO N 0 4
Classes & Objects
A class is the blueprint. An object is a real thing built from it. One Student class can
produce thousands of distinct student objects, each with its own data.
Asha · marks 88
Student
objects — each
class · blueprint Ravi · marks 74 independent
Meera · marks 91
Figure 4 — One class, three independent objects.
CLASS DEFINITION
public class Student {
String name; // fields — data each object holds
int marks;
void display() { // method — what the object does
[Link](name + ": " + marks);
}
}
CREATING AND USING OBJECTS
Student s1 = new Student();
[Link] = "Asha"; [Link] = 88;
[Link](); // Asha: 88
Student s2 = new Student();
[Link] = "Ravi"; [Link] = 74; // s2 is completely separate from s1
12
JAVA & OOP OOP · 03
SE CTIO N 0 4
Constructors
Setting fields manually after new is error-prone — you might forget one and create a
half-built object. A constructor runs the moment an object is created, ensuring it's
born complete and valid.
CONSTRUCTOR — BUILDS A VALID OBJECT AT BIRTH
public class Student {
String name;
int marks;
// same name as class, no return type
public Student(String name, int marks) {
[Link] = name; // this = the object being built
[Link] = marks;
}
}
NOW CREATION IS ONE CLEAN, SAFE LINE
Student s1 = new Student("Asha", 88);
Student s2 = new Student("Ravi", 74);
// cannot forget a field — the compiler demands both arguments
THIS K E Y WO RD
When a constructor parameter and a field share the same name, [Link] means the
object field and plain name means the parameter.
CO NSTRUCTO R O VE RLO ADING
Define multiple constructors with different parameters. Java picks the right one based on
what you pass to new .
13
JAVA & OOP OOP · 04
SE CTIO N 0 4
Encapsulation
PILLAR 1 O F 4
Hide the data. Expose only safe controls. Make fields private so nothing outside the
class can access them directly, then offer public methods that enforce your business
rules.
A BANKACCOUNT THAT PROTECTS ITSELF
public class BankAccount {
private double balance; // locked — nothing can touch this directly
public BankAccount(double opening) {
balance = [Link](0, opening);
}
public void deposit(double amt) {
if (amt > 0) balance += amt;
}
public void withdraw(double amt) {
if (amt <= balance) balance -= amt;
else [Link]("Insufficient funds");
}
public double getBalance() { return balance; }
}
THE PRO TE CTIO N IN ACTIO N
There is no setBalance() method. Writing [Link] = 999999 from outside the
class will not compile. The only ways to change the balance are deposit() and
withdraw() , and both enforce rules. That is encapsulation.
14
JAVA & OOP OOP · 05
SE CTIO N 0 4
Inheritance
PILLAR 2 O F 4
Write shared code once in a parent; let children reuse it. Use extends to build the
relationship. super() calls the parent constructor.
Employee
name · baseSalary · work()
Developer Manager Intern
+ codeReview() + approveLeave() + submitReport()
Figure 5 — All three inherit name, baseSalary and work() from Employee.
PARENT CLASS
public class Employee {
protected String name;
protected double baseSalary;
public Employee(String n, double s) { name=n; baseSalary=s; }
public void work() { [Link](name + " is working"); }
}
CHILD — REUSES PARENT, ADDS ITS OWN
public class Developer extends Employee {
public Developer(String n, double s) { super(n, s); }
public void codeReview() { [Link](name + " reviewing PR"); }
}
PRO TE CTE D VS PRIVATE
Use private when only the class itself needs access. Use protected when child
classes also need direct access to a field.
15
JAVA & OOP OOP · 06
SE CTIO N 0 4
Polymorphism
PILLAR 3 O F 4
One name, many behaviours. Polymorphism lets you call the same method on
different objects and get the right behaviour for each — decided by Java at runtime, not
compile-time.
OVERRIDING — CHILD REDEFINES PARENT BEHAVIOUR
public class Manager extends Employee {
public Manager(String n, double s) { super(n, s); }
@Override
public void work() { // same name, new behaviour
[Link](name + " is planning the sprint");
}
}
ONE LOOP, DIFFERENT BEHAVIOUR PER OBJECT
Employee[] team = {
new Developer("Asha", 60000),
new Manager("Ravi", 90000)
};
for (Employee e : team) {
[Link](); // Asha: working | Ravi: planning the sprint
}
WHY @O VE RRIDE MATTE RS
Adding @Override is optional but valuable. If you mistype the method name, the
compiler catches it instead of silently creating a new method that never gets called.
16
JAVA & OOP OOP · 07
SE CTIO N 0 4
Abstraction
PILLAR 4 O F 4
Show what, hide how. An abstract class defines capabilities that every subclass must
implement — without saying how. It cannot be instantiated directly.
ABSTRACT CLASS — DEFINES WHAT, NOT HOW
public abstract class Employee {
protected String name;
protected double baseSalary;
public Employee(String n, double s) { name=n; baseSalary=s; }
public abstract double calculateSalary(); // no body — enforced
public void printName() { [Link](name); }
}
EACH CHILD SUPPLIES ITS OWN FORMULA
public class Developer extends Employee {
public Developer(String n, double s) { super(n, s); }
@Override
public double calculateSalary() { return baseSalary + 10000; }
}
THE E NFO RCE ME NT
Writing new Employee(...) will not compile. You are forced to create a concrete
Developer or Manager — and each is forced to provide calculateSalary() . The
abstract class guarantees the capability without prescribing the formula.
17
05
SECTIO N FIVE
Interfaces
Pure contracts — the most flexible tool in Java's design
toolkit.
JAVA & OOP I N TE RFA C E S · 01
SE CTIO N 0 5
Interfaces
An interface is a pure contract — a list of methods any implementing class must
provide. It lets completely unrelated classes be treated interchangeably.
THE CONTRACT
public interface PaymentMethod {
void pay(double amount); // no body — just the promise
}
UNRELATED CLASSES THAT HONOUR IT
class UpiPayment implements PaymentMethod {
public void pay(double amt) { [Link]("UPI: ₹"+amt); }
}
class CardPayment implements PaymentMethod {
public void pay(double amt) { [Link]("Card: ₹"+amt); }
}
class WalletPayment implements PaymentMethod {
public void pay(double amt) { [Link]("Wallet: ₹"+amt); }
}
CHECKOUT DOESN'T CARE WHICH METHOD
void checkout(PaymentMethod method, double amount) {
[Link](amount); // works for all three — and any future one
}
THE PAY O FF
Add Net Banking next month? Write one new class that implements PaymentMethod. The
checkout code never changes — that is the open/closed principle in practice.
19
JAVA & OOP I N TE RFA C E S · 02
SE CTIO N 0 5
Abstract Class vs Interface
They look similar — both can't be instantiated directly, both enforce method
implementation. The difference is in what relationship they model.
Abstract Class Interface
Can have fields, regular methods, and Mainly method signatures (no state)
abstract methods
A class can extend one only A class can implement many
Models an is-a family relationship Models a can-do capability
Shares common code among related Shares a common ability among strangers
classes
Developer extends Employee UpiPayment implements PaymentMethod
The decision rule
Related classes sharing code? → Abstract class. Developer, Manager, Intern are all
Employees.
Unrelated classes sharing a capability? → Interface. UPI, Card, Wallet can all pay().
Need multiple capabilities at once? → Interface — a class can implement many.
INTE RVIE W ANSWE R
Reach for an abstract class when subclasses are a true family sharing real code, and an
interface when you need to guarantee a capability across unrelated types — a class can
implement many interfaces but extend only one class.
20
06
SECTION SIX
Beyond the Basics
Exception handling, dynamic collections, and the essential
Java toolkit.
JAVA & OOP BE Y ON D TH E BA SI C S · 01
SE CTIO N 0 6
Exception Handling
Exceptions are runtime errors — things you can't catch at compile time. Java's
try/catch block lets you handle them gracefully instead of crashing.
TRY / CATCH / FINALLY
try {
int result = 100 / userInput; // may throw
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} catch (Exception e) {
[Link]("Something went wrong: " + [Link]());
} finally {
[Link]("This always runs");
}
THROWING YOUR OWN EXCEPTION
void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Age can't be negative");
[Link] = age;
}
FINALLY ALWAY S RUNS
finally executes whether or not an exception was thrown. Use it to close files, release
connections, or clean up resources that must always happen.
21
JAVA & OOP BE Y ON D TH E BA SI C S · 02
SE CTIO N 0 6
ArrayList
An ArrayList is a dynamically sized list — unlike arrays, it grows and shrinks
automatically. It's the most commonly used collection in everyday Java.
ARRAYLIST — A RESIZABLE LIST
import [Link];
ArrayList<String> skills = new ArrayList<>();
// add
[Link]("Java");
[Link]("Git");
[Link]("SQL");
// access & size
[Link](0); // "Java"
[Link](); // 3
// remove & check
[Link]("Git");
[Link]("SQL"); // true
// iterate
for (String s : skills) [Link](s);
ARRAY LIST VS ARRAY
Use a plain array when size is fixed and performance is critical. Use ArrayList for
everyday work where the collection size may change.
22
JAVA & OOP BE Y ON D TH E BA SI C S · 03
SE CTIO N 0 6
HashMap
A HashMap stores data as key → value pairs. Look up any value in O(1) time using its
key — perfect for dictionaries, caches, counts, and lookup tables.
HASHMAP — KEY → VALUE PAIRS
import [Link];
HashMap<String, Integer> scores = new HashMap<>();
// put (add / update)
[Link]("Asha", 88);
[Link]("Ravi", 74);
[Link]("Meera", 91);
// get
[Link]("Asha"); // 88
[Link]("Ravi"); // true
[Link]("Ravi");
// iterate all entries
for (String k : [Link]()) {
[Link](k + " → " + [Link](k));
}
K E Y MUST BE UNIQ UE
If you put() with an existing key, it overwrites the old value. Use containsKey() to check
before inserting if that matters.
23
07
SECTION SEVEN
Reference
The whole guide distilled. Keep this page.
JAVA & OOP RE FE RE N C E
SE CTIO N 0 7
Quick Reference
Concept In one line
JVM / JDK JVM runs bytecode · JDK is the full toolkit to write & compile
Variables Declare type before use: int age = 23;
Strings Use .equals() to compare — never ==
if / switch Ranges → if / else · Fixed values → switch + break
for / while Known count → for · Unknown count → while
Arrays Fixed size, index from 0, check .length
Methods One job per method · overload by changing parameters
OOP Pillar Core idea
Encapsulation private fields + public methods with rules
Inheritance extends — write common code once in parent
Polymorphism @Override — same call, right behaviour per object
Abstraction abstract — enforce what, not how
Interface implements — a capability contract for unrelated classes
Exceptions try / catch / finally — handle runtime errors gracefully
Collections ArrayList (ordered list) · HashMap (key → value lookup)
IF Y O U RE ME MBE R O NE THING
OOP is about modelling your problem as objects that own their data and own their
behaviour. Every pillar is a tool for doing that cleanly. Re-type the examples in this guide
— understanding lives in the fingers.
25
IN CLOSING
You can now
think in Java.
Syntax is the shallow end. The real depth is modelling a problem
as objects that own their data and behaviour — and knowing
which tool (class, interface, collection, exception) serves the
moment.
Make it stick
Rebuild the BankAccount from memory — feel encapsulation protect the data.
Recreate the Employee hierarchy — watch one call behave differently per
object.
Add a new payment method to the interface — without touching existing code.