☕ Java Notes
A Complete Beginner-to-Intermediate Reference
Mirrors the structure of Easiest Python Notes
Chapter 1 — Introduction to Java
Java is a statically-typed, object-oriented, compiled language that runs on the Java Virtual Machine
(JVM). Write once, run anywhere.
💡 Java requires you to declare types for every variable — unlike Python, which infers types at
runtime.
1.1 What is Java?
• Compiled to bytecode (.class files), then interpreted by the JVM
• Strongly and statically typed
• Object-Oriented — everything lives inside a class
• Platform-independent via the JVM
• Used in Android apps, enterprise software, web back-ends, games (Minecraft)
1.2 Setting Up
• Install JDK (Java Development Kit) from [Link] or [Link]
• Check version: run javac -version and java -version in terminal
• Popular IDEs: IntelliJ IDEA, Eclipse, VS Code (with Java Extension Pack)
1.3 Hello, World!
Java
// [Link]
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
To compile and run from the terminal:
Java
javac [Link] // produces [Link]
java HelloWorld // runs it
💡 The filename must match the public class name exactly, including capitalisation.
1.4 Java vs Python — Quick Look
Concept Python Java
Print print('hi') [Link]("hi"
);
Variable x = 5 int x = 5;
Comment # this // this or /* this */
Code block indentation { curly braces }
End of line newline semicolon ;
Chapter 2 — Variables & Data Types
Java is statically typed — every variable must have a declared type before use.
2.1 Primitive Data Types
Type Size Example Range / Notes
byte 8-bit byte b = 100; -128 to 127
short 16-bit short s = 30000; -32,768 to
32,767
int 32-bit int i = 42; -2^31 to 2^31-1
(most common)
long 64-bit long l = Add L suffix
9999999999L;
float 32-bit float f = 3.14f; Add f suffix
double 64-bit double d = Default decimal
3.14159; type
char 16-bit char c = 'A'; Single Unicode
character
boolean 1-bit boolean b = true or false
true; only
2.2 Declaring & Initialising Variables
Java
int age = 25;
double price = 9.99;
char grade = 'A';
boolean isStudent = true;
String name = "Alice"; // String is a class, not a primitive
2.3 The String Class
String is an object (reference type) in Java, not a primitive. Strings are immutable.
Java
String s = "Hello";
int len = [Link](); // 5
String upper = [Link](); // "HELLO"
String lower = [Link](); // "hello"
boolean eq = [Link]("Hello"); // true (use equals, NOT ==)
String sub = [Link](1, 3); // "el"
int idx = [Link]('l'); // 2
String rep = [Link]('l','r'); // "Herro"
String trim = " hi ".trim(); // "hi"
String[] arr = "a,b,c".split(","); // ["a","b","c"]
2.4 String Concatenation & Formatting
Java
String name = "Bob";
int age = 30;
// Concatenation
String s1 = "Name: " + name + ", Age: " + age;
// [Link] (like Python's f-strings)
String s2 = [Link]("Name: %s, Age: %d", name, age);
// printf (prints directly)
[Link]("Name: %s, Age: %d%n", name, age);
// Text block (Java 13+)
String json = """
{
\"name\": \"Bob\"
}
""";
2.5 var — Local Type Inference (Java 10+)
Java
var x = 42; // inferred as int
var name = "Ada"; // inferred as String
var pi = 3.14; // inferred as double
// var is only allowed for local variables
💡 var doesn't make Java dynamically typed — the type is still fixed at compile time.
2.6 Type Casting
Java
// Widening (automatic)
int i = 10;
double d = i; // 10.0
// Narrowing (explicit cast required)
double pi = 3.14159;
int approx = (int) pi; // 3 (truncates, does not round)
// String conversions
int num = [Link]("42");
double dbl = [Link]("3.14");
String str = [Link](100); // "100"
String str2 = [Link](100); // "100"
Chapter 3 — Operators
3.1 Arithmetic Operators
Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2 (integer
division!)
% Modulus 5 % 2 1
++ Increment i++ i = i + 1
-- Decrement i-- i = i - 1
💡 5 / 2 = 2 in Java (integer division). Use 5.0 / 2 or (double)5 / 2 to get 2.5.
3.2 Assignment & Compound Operators
Java
int x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2
3.3 Comparison Operators
Operator Meaning Example
== Equal to x == 5
!= Not equal to x != 5
> Greater than x > 3
< Less than x < 3
>= Greater than or equal x >= 5
<= Less than or equal x <= 5
💡 Use == for primitives. For objects (like String), always use .equals().
3.4 Logical Operators
Operator Meaning Example Note
&& Logical AND x > 0 && x < 10 Both must be
true
|| Logical OR x < 0 || x > 10 At least one
true
! Logical NOT !(x == 5) Inverts boolean
Chapter 4 — Control Flow
4.1 if / else if / else
Java
int score = 75;
if (score >= 90) {
[Link]("A");
} else if (score >= 80) {
[Link]("B");
} else if (score >= 70) {
[Link]("C");
} else {
[Link]("F");
}
4.2 Ternary Operator
Java
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
[Link](status); // Adult
4.3 switch Statement
Java
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Other");
}
4.4 switch Expression (Java 14+)
Java
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other";
};
💡 The arrow -> switch expression doesn't fall through and doesn't need break.
Chapter 5 — Loops
5.1 for Loop
Java
for (int i = 0; i < 5; i++) {
[Link](i);
}
// Prints: 0 1 2 3 4
5.2 while Loop
Java
int count = 0;
while (count < 5) {
[Link](count);
count++;
}
5.3 do-while Loop
Java
int count = 0;
do {
[Link](count);
count++;
} while (count < 5);
// Executes body at least once, even if condition is false initially
5.4 Enhanced for Loop (for-each)
Java
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
[Link](num);
}
// Works with any Iterable (arrays, lists, sets...)
List<String> names = [Link]("Alice", "Bob", "Charlie");
for (String name : names) {
[Link](name);
}
5.5 break & continue
Java
// break — exits the loop
for (int i = 0; i < 10; i++) {
if (i == 5) break;
[Link](i + " "); // 0 1 2 3 4
}
// continue — skips current iteration
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
[Link](i + " "); // 1 3 5 7 9
}
Chapter 6 — Arrays
Arrays in Java are fixed-size, zero-indexed collections of the same type.
6.1 Declaring & Creating Arrays
Java
// Declaration and creation
int[] numbers = new int[5]; // [0, 0, 0, 0, 0]
String[] names = new String[3]; // [null, null, null]
// Declaration with initialisation
int[] primes = {2, 3, 5, 7, 11};
String[] fruits = {"apple", "banana", "cherry"};
6.2 Accessing & Modifying Elements
Java
int[] arr = {10, 20, 30, 40, 50};
[Link](arr[0]); // 10 (first element)
[Link](arr[4]); // 50 (last element)
[Link]([Link]); // 5 (not [Link]())
arr[2] = 99; // change element
[Link](arr[2]); // 99
6.3 Iterating Arrays
Java
int[] scores = {85, 92, 78, 96, 88};
// Traditional for
for (int i = 0; i < [Link]; i++) {
[Link]("Index " + i + ": " + scores[i]);
}
// Enhanced for
for (int score : scores) {
[Link](score + " ");
}
6.4 Arrays Utility Class
Java
import [Link];
int[] arr = {5, 2, 8, 1, 9, 3};
[Link](arr); // [1, 2, 3, 5, 8, 9]
[Link]([Link](arr)); // "[1, 2, 3, 5, 8, 9]"
int idx = [Link](arr, 5); // index of 5 (after sort)
int[] copy = [Link](arr, 4); // [1, 2, 3, 5]
int[] rangeCopy = [Link](arr, 1, 4); // [2, 3, 5]
[Link](arr, 0); // [0, 0, 0, 0, 0, 0]
6.5 Multi-Dimensional Arrays
Java
// 2D array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link](matrix[1][2]); // 6 (row 1, col 2)
// Iterate 2D
for (int[] row : matrix) {
for (int val : row) {
[Link](val + " ");
}
[Link]();
}
Chapter 7 — Methods
Methods are named blocks of reusable code. In Java, all methods must be inside a class.
7.1 Defining a Method
Java
// Syntax:
// [access modifier] returnType methodName(parameters) { body }
public static int add(int a, int b) {
return a + b;
}
public static void greet(String name) {
[Link]("Hello, " + name + "!");
// void means no return value
}
7.2 Calling Methods
Java
public class Methods {
public static void main(String[] args) {
int sum = add(3, 7);
[Link](sum); // 10
greet("Alice"); // Hello, Alice!
}
public static int add(int a, int b) { return a + b; }
public static void greet(String name) { [Link]("Hello, "
+ name + "!"); }
}
7.3 Method Overloading
Java
// Same name, different parameter lists
public static int add(int a, int b) { return a + b; }
public static double add(double a, double b) { return a + b; }
public static int add(int a, int b, int c) { return a + b + c; }
// Java chooses the right one at compile time
[Link](add(2, 3)); // 5
[Link](add(2.5, 3.5)); // 6.0
[Link](add(1, 2, 3)); // 6
7.4 Varargs (Variable Arguments)
Java
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
[Link](sum(1, 2)); // 3
[Link](sum(1, 2, 3, 4)); // 10
[Link](sum(10, 20, 30)); // 60
7.5 Recursion
Java
public static int factorial(int n) {
if (n == 0 || n == 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
[Link](factorial(5)); // 120
[Link](factorial(0)); // 1
Chapter 8 — Object-Oriented Programming
Java is built around OOP. The four pillars are: Encapsulation, Inheritance, Polymorphism, Abstraction.
8.1 Classes & Objects
Java
public class Dog {
// Fields (attributes / instance variables)
String name;
String breed;
int age;
// Constructor
public Dog(String name, String breed, int age) {
[Link] = name;
[Link] = breed;
[Link] = age;
}
// Method (behaviour)
public void bark() {
[Link](name + " says: Woof!");
}
// toString override
@Override
public String toString() {
return name + " (" + breed + ", age " + age + ")";
}
}
// Creating objects
Dog d1 = new Dog("Rex", "Husky", 3);
Dog d2 = new Dog("Bella", "Labrador", 5);
[Link](); // Rex says: Woof!
[Link](d2); // Bella (Labrador, age 5)
8.2 Encapsulation — Getters & Setters
Java
public class BankAccount {
private double balance; // private — hidden from outside
public BankAccount(double initial) { [Link] = initial; }
public double getBalance() { return balance; } // getter
public void deposit(double amount) { // setter with logic
if (amount > 0) balance += amount;
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
else [Link]("Insufficient funds");
}
}
8.3 Inheritance
Java
// Parent class
public class Animal {
String name;
public Animal(String name) { [Link] = name; }
public void eat() { [Link](name + " is eating"); }
public void sleep() { [Link](name + " is sleeping"); }
}
// Child class — extends parent
public class Cat extends Animal {
String colour;
public Cat(String name, String colour) {
super(name); // call parent constructor
[Link] = colour;
}
public void meow() { [Link](name + " says: Meow!"); }
@Override
public void eat() {
[Link](name + " is eating fish"); // overriding
}
}
Cat c = new Cat("Whiskers", "orange");
[Link](); // Whiskers is eating fish
[Link](); // Whiskers is sleeping (inherited)
[Link](); // Whiskers says: Meow!
8.4 Interfaces & Abstract Classes
Java
// Interface — defines a contract
public interface Drawable {
void draw(); // abstract by default
default void describe() { // default method (Java 8+)
[Link]("I am drawable");
}
}
// Abstract class — partially implemented
public abstract class Shape {
String colour;
public Shape(String colour) { [Link] = colour; }
public abstract double area(); // must be overridden
public void printColour() { [Link](colour); }
}
// Concrete class
public class Circle extends Shape implements Drawable {
double radius;
public Circle(String colour, double radius) {
super(colour);
[Link] = radius;
}
@Override public double area() { return [Link] * radius * radius; }
@Override public void draw() { [Link]("Drawing circle");
}
}
Chapter 9 — Collections Framework
The Java Collections Framework provides dynamic, resizable data structures. Import from [Link].
9.1 ArrayList (like Python list)
Java
import [Link];
ArrayList<String> fruits = new ArrayList<>();
[Link]("apple");
[Link]("banana");
[Link]("cherry");
[Link](fruits); // [apple, banana, cherry]
[Link]([Link](0)); // apple
[Link]([Link]()); // 3
[Link](1, "blueberry"); // replace index 1
[Link]("cherry"); // remove by value
[Link](0); // remove by index
boolean has = [Link]("apple"); // true/false
for (String f : fruits) {
[Link](f);
}
9.2 HashMap (like Python dict)
Java
import [Link];
HashMap<String, Integer> scores = new HashMap<>();
[Link]("Alice", 95);
[Link]("Bob", 87);
[Link]("Charlie", 92);
[Link]([Link]("Alice")); // 95
[Link]([Link]("Bob")); // true
[Link]("Charlie");
[Link]("Alice", 98); // update value
// Iterating
for (String key : [Link]()) {
[Link](key + " -> " + [Link](key));
}
// getOrDefault — safe retrieval
int s = [Link]("Dave", 0); // 0 if key absent
9.3 HashSet (like Python set)
Java
import [Link];
HashSet<String> set = new HashSet<>();
[Link]("red");
[Link]("green");
[Link]("blue");
[Link]("red"); // duplicate — ignored
[Link]([Link]()); // 3
[Link]([Link]("red")); // true
[Link]("green");
9.4 Collections Utility Methods
Java
import [Link];
import [Link];
ArrayList<Integer> nums = new ArrayList<>();
[Link](5); [Link](1); [Link](3); [Link](8); [Link](2);
[Link](nums); // [1, 2, 3, 5, 8]
[Link](nums); // [8, 5, 3, 2, 1]
[Link](nums); // random order
int max = [Link](nums);
int min = [Link](nums);
[Link](nums, 0); // fill all with 0
Chapter 10 — Exception Handling
10.1 try / catch / finally
Java
try {
int result = 10 / 0; // throws ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Always runs"); // cleanup code here
}
10.2 Multiple catch Blocks
Java
String[] arr = {"10", "abc", null};
for (String s : arr) {
try {
int n = [Link](s); // NumberFormatException if 'abc'
[Link](n * 2);
} catch (NumberFormatException e) {
[Link]("Not a number: " + s);
} catch (NullPointerException e) {
[Link]("Null value!");
}
}
10.3 Common Exceptions
Exception Cause
NullPointerException Using a null reference
ArrayIndexOutOfBoundsException Accessing invalid array index
NumberFormatException Parsing non-numeric String
ArithmeticException Division by zero
ClassCastException Invalid type cast
StackOverflowError Infinite recursion
IOException File / stream read errors
10.4 Throwing Exceptions
Java
public static double divide(double a, double b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
// Custom exception
public class AgeException extends Exception {
public AgeException(String msg) { super(msg); }
}
public static void setAge(int age) throws AgeException {
if (age < 0) throw new AgeException("Age cannot be negative: " +
age);
}
10.5 try-with-resources
Java
// Automatically closes the resource
try ([Link] br = new [Link](
new [Link]("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch ([Link] e) {
[Link]("File error: " + [Link]());
}
Chapter 11 — File Input / Output
11.1 Writing to a File
Java
import [Link];
import [Link];
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Hello, File!\n");
[Link]("Line 2\n");
} catch (IOException e) {
[Link]("Write error: " + [Link]());
}
// Append mode
try (FileWriter fw = new FileWriter("[Link]", true)) {
[Link]("Appended line\n");
} catch (IOException e) { [Link](); }
11.2 Reading from a File
Java
import [Link];
import [Link];
import [Link];
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Read error: " + [Link]());
}
11.3 Using [Link] (Modern I/O)
Java
import [Link].*;
import [Link];
// Write all lines
List<String> lines = [Link]("Line 1", "Line 2", "Line 3");
[Link]([Link]("[Link]"), lines);
// Read all lines
List<String> read = [Link]([Link]("[Link]"));
[Link]([Link]::println);
// Read entire file as String
String content = [Link]([Link]("[Link]"));
// Check if file exists
boolean exists = [Link]([Link]("[Link]"));
Chapter 12 — Lambdas & Streams (Java 8+)
Lambdas and Streams enable functional-style programming in Java — similar to Python's list
comprehensions and map/filter/reduce.
12.1 Lambda Expressions
Java
// Traditional anonymous class
Runnable r1 = new Runnable() {
public void run() { [Link]("Hello"); }
};
// Lambda equivalent
Runnable r2 = () -> [Link]("Hello");
// Lambda with parameters
[Link]<Integer, Integer, Integer> add = (a, b) ->
a + b;
[Link]([Link](3, 4)); // 7
// Sorting with lambda
[Link]<String> names = new [Link]<>();
[Link]("Charlie"); [Link]("Alice"); [Link]("Bob");
[Link]((a, b) -> [Link](b));
[Link](names); // [Alice, Bob, Charlie]
12.2 Common Functional Interfaces
Interface Method Equivalent Python
Predicate<T> test(T t) -> boolean lambda x: bool
Function<T,R> apply(T t) -> R lambda x: expr
Consumer<T> accept(T t) -> void lambda x: side-effect
Supplier<T> get() -> T lambda: value
BiFunction<T,U,R> apply(T,U) -> R lambda x,y: expr
12.3 Stream API
Java
import [Link];
import [Link].*;
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// filter + map + collect (like Python: [x*2 for x in nums if x%2==0])
List<Integer> result = [Link]()
.filter(n -> n % 2 == 0) // keep evens
.map(n -> n * 2) // double them
.collect([Link]()); // [4, 8, 12, 16, 20]
// reduce (like Python's [Link])
int sum = [Link]()
.reduce(0, Integer::sum); // 55
// count, min, max
long count = [Link]().filter(n -> n > 5).count(); // 5
int max = [Link]().mapToInt(Integer::intValue).max().getAsInt();
// 10
// forEach
[Link]().forEach([Link]::println);
// sorted, distinct, limit, skip
List<Integer> top3 = [Link]()
.sorted([Link]())
.limit(3)
.collect([Link]()); // [10, 9, 8]
Chapter 13 — Generics
Generics allow classes and methods to work with any type while maintaining type safety.
13.1 Generic Class
Java
public class Box<T> {
private T value;
public Box(T value) { [Link] = value; }
public T getValue() { return value; }
public void setValue(T value) { [Link] = value; }
}
Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>("Hello");
[Link]([Link]()); // 42
[Link]([Link]()); // Hello
13.2 Generic Method
Java
public static <T> void printArray(T[] arr) {
for (T element : arr) {
[Link](element + " ");
}
[Link]();
}
Integer[] ints = {1, 2, 3};
String[] strs = {"a", "b", "c"};
printArray(ints); // 1 2 3
printArray(strs); // a b c
13.3 Bounded Type Parameters
Java
// T must be a Number (or subclass)
public static <T extends Number> double sum(T a, T b) {
return [Link]() + [Link]();
}
[Link](sum(3, 4)); // 7.0
[Link](sum(2.5, 3.5)); // 6.0
Chapter 14 — Useful Built-in Classes
14.1 Math Class
Java
[Link](-5) // 5
[Link](3, 7) // 7
[Link](3, 7) // 3
[Link](2, 10) // 1024.0
[Link](16) // 4.0
[Link](3.9) // 3.0
[Link](3.1) // 4.0
[Link](3.5) // 4
[Link] // 3.141592653589793
Math.E // 2.718281828459045
[Link]() // random double [0.0, 1.0)
// Random int between 1 and 100
int rand = (int)([Link]() * 100) + 1;
14.2 StringBuilder (Mutable Strings)
Java
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link](", ");
[Link]("World");
[Link](5, "!"); // insert at index
[Link](5, 6); // delete from 5 to 6
[Link]();
String result = [Link]();
// StringBuilder is much faster than String + String in loops
14.3 Scanner (User Input)
Java
import [Link];
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Enter your GPA: ");
double gpa = [Link]();
[Link]("Hi %s! Age: %d, GPA: %.2f%n", name, age, gpa);
[Link]();
14.4 Optional (Null Safety, Java 8+)
Java
import [Link];
Optional<String> opt1 = [Link]("Hello");
Optional<String> opt2 = [Link]();
[Link](); // true
[Link](); // "Hello"
[Link]("default"); // "default"
[Link](String::toUpperCase); // Optional[HELLO]
[Link]([Link]::println); // prints Hello
Chapter 15 — Quick Reference Cheat Sheet
Java vs Python Syntax Comparison
Task Python Java
Print print('hi') [Link]("hi"
);
Variables x = 5 int x = 5;
String s = 'hello' String s = "hello";
If if x > 5: if (x > 5) {
For range for i in range(5): for (int i=0; i<5; i++)
{
For-each for item in list: for (int n : arr) {
While while x < 5: while (x < 5) {
Function def add(a, b): int add(int a, int b) {
List lst = [] ArrayList<T> lst = new
ArrayList<>();
Dict d = {} HashMap<K,V> map = new
HashMap<>();
Length len(x) [Link]() or [Link]
String format f'Hi {name}' [Link]("Hi %s",
name)
Input x = input('Enter: ') String x =
[Link]();
Cast to int int(x) (int) x or
[Link](x)
Try/catch try: ... except E: try { ... } catch (E e)
{
Null None null
And / Or / Not && / || / ! && / || / !
Inheritance class B(A): class B extends A {
Primitive Type Defaults
Type Default Value
int / short / byte / long 0
float / double 0.0
char '\u0000' (null char)
boolean false
Object / String / array null
Access Modifiers
Modifier Same Class Same Package Subclass Everywhere
private Yes No No No
(default) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
Keep coding. Keep building. ☕