Install Java: Download JDK from
adoptium.net (free). Then install VS Code + "Extension Pack for Java". Or use replit.com โ free, no install, Java ready in seconds.Chapter 1 โ What is Java?
Java is a strongly-typed, object-oriented language that runs on the JVM (Java Virtual Machine). Write once, run anywhere โ same code works on Windows, Mac, Linux, Android.
Used for: Android apps, enterprise backends (Spring), banking systems, Minecraft, Hadoop.
Chapter 2 โ Setup & Hello World
// File MUST be named exactly like the class: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// Compile and run:
javac HelloWorld.java // compile โ creates HelloWorld.class
java HelloWorld // run
// System.out.println() = print + newline
// System.out.print() = print WITHOUT newline
// System.out.printf() = formatted print
System.out.printf("Name: %s, Age: %d%n", "Uzair", 25);
// Name: Uzair, Age: 25
Chapter 3 โ Variables & Data Types
// Java is STATICALLY typed โ you must declare the type
int age = 25; // whole number (-2B to 2B)
long big = 9999999999L; // large whole number (add L)
double price = 9.99; // decimal (64-bit)
float pi = 3.14f; // decimal (32-bit, add f)
char grade = 'A'; // single character (single quotes)
boolean active = true; // true or false
String name = "Uzair"; // text (capital S โ it's a class)
// var (Java 10+) โ type inferred automatically:
var city = "Lahore"; // still String, just inferred
// Constants (final = can't be changed):
final int MAX_AGE = 120;
final double TAX_RATE = 0.2;
// Type casting:
int x = (int) 9.99; // 9 (truncates)
double d = (double) 5 / 2; // 2.5
String s = String.valueOf(42); // "42"
int n = Integer.parseInt("42"); // 42
// String methods:
String str = "Hello, World!";
System.out.println(str.length()); // 13
System.out.println(str.toUpperCase()); // HELLO, WORLD!
System.out.println(str.substring(0, 5)); // Hello
System.out.println(str.contains("World")); // true
System.out.println(str.replace("World", "Java")); // Hello, Java!
System.out.println(str.trim()); // removes whitespace
System.out.println(str.split(", ")[0]); // Hello
Chapter 4 โ Operators & Control Flow
// Arithmetic (same as most languages):
int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a / b); // 3 (integer division!)
System.out.println(a % b); // 1 (remainder)
System.out.println((double)a / b); // 3.333...
// if / else if / else:
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}
// Switch (Java 14+ enhanced switch):
String day = "Monday";
String type = switch (day) {
case "Saturday", "Sunday" -> "Weekend";
default -> "Weekday";
};
// for loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop:
int n = 0;
while (n < 5) {
System.out.println(n++);
}
// do-while (runs at least once):
int x = 0;
do {
System.out.println(x++);
} while (x < 3);
Chapter 5 โ Methods
public class Methods {
// Basic method:
static void sayHello() {
System.out.println("Hello!");
}
// Method with parameters and return:
static int add(int a, int b) {
return a + b;
}
// Method overloading โ same name, different params:
static double add(double a, double b) {
return a + b;
}
// Varargs (variable arguments):
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static void main(String[] args) {
sayHello(); // Hello!
System.out.println(add(3, 4)); // 7
System.out.println(add(1.5, 2.5)); // 4.0
System.out.println(sum(1, 2, 3, 4, 5)); // 15
}
}
Chapter 6 โ Arrays
// Declare and initialise:
int[] nums = {1, 2, 3, 4, 5};
String[] names = new String[3]; // array of 3 strings (null)
names[0] = "Alice";
names[1] = "Bob";
// Access and length:
System.out.println(nums[0]); // 1
System.out.println(nums.length); // 5
// Enhanced for loop (for-each):
for (int n : nums) {
System.out.println(n);
}
// Sort and search:
import java.util.Arrays;
Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [1, 2, 3, 4, 5]
int idx = Arrays.binarySearch(nums, 3); // index of 3
// 2D array (matrix):
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(grid[1][2]); // 6
for (int[] row : grid) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
Chapter 7 โ Classes & Objects
// Define a class:
public class Person {
// Fields (attributes):
private String name;
private int age;
// Constructor โ called when creating an object:
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters:
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
// Method:
public String greet() {
return "Hi, I'm " + name + " and I'm " + age;
}
// toString โ called by System.out.println:
@Override
public String toString() {
return "Person{name=" + name + ", age=" + age + "}";
}
}
// Use the class:
Person p = new Person("Uzair", 25);
System.out.println(p.getName()); // Uzair
System.out.println(p.greet()); // Hi, I'm Uzair and I'm 25
System.out.println(p); // Person{name=Uzair, age=25}
p.setName("Ali");
Chapter 8 โ Inheritance
// Base class:
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " makes a sound.");
}
}
// Subclass โ inherits from Animal:
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // call parent constructor
this.breed = breed;
}
@Override // override parent method
public void speak() {
System.out.println(name + " barks!");
}
public void fetch() {
System.out.println(name + " fetches the ball!");
}
}
// Polymorphism:
Animal a = new Dog("Rex", "Labrador");
a.speak(); // Rex barks! (calls Dog's version)
// Check type:
if (a instanceof Dog d) {
d.fetch(); // Rex fetches the ball!
}
Chapter 9 โ Interfaces
// Interface = contract โ says WHAT a class must do
public interface Drawable {
void draw(); // abstract method โ no body
default String colour() { return "black"; } // default method
}
public interface Resizable {
void resize(double factor);
}
// Class can implement multiple interfaces:
public class Circle implements Drawable, Resizable {
private double radius;
public Circle(double radius) { this.radius = radius; }
@Override
public void draw() {
System.out.println("Drawing circle with radius " + radius);
}
@Override
public void resize(double factor) {
radius *= factor;
}
}
Circle c = new Circle(5.0);
c.draw(); // Drawing circle with radius 5.0
c.resize(2.0);
c.draw(); // Drawing circle with radius 10.0
System.out.println(c.colour()); // black
Chapter 10 โ Collections
import java.util.*;
// ArrayList โ resizable array:
ArrayList<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("banana");
fruits.add("cherry");
System.out.println(fruits.get(0)); // apple
System.out.println(fruits.size()); // 3
fruits.remove("banana");
fruits.set(0, "mango");
Collections.sort(fruits);
for (String f : fruits) System.out.println(f);
// HashMap โ key โ value pairs:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);
System.out.println(scores.get("Alice")); // 95
scores.put("Alice", 98); // update
scores.remove("Bob");
System.out.println(scores.containsKey("Charlie")); // true
for (Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
// HashSet โ unique values:
HashSet<Integer> set = new HashSet<>(Arrays.asList(1,2,3,3,4));
System.out.println(set); // [1, 2, 3, 4] โ no duplicate!
Chapter 11 โ Exception Handling
// try-catch:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage()); // / by zero
}
// Multiple catch blocks:
try {
int[] arr = {1, 2, 3};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range!");
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
} finally {
System.out.println("Always runs!");
}
// Throw exceptions:
static void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Age can't be negative");
System.out.println("Age set to: " + age);
}
// Custom exception:
class InvalidScoreException extends RuntimeException {
public InvalidScoreException(String msg) { super(msg); }
}
static void validateScore(int score) {
if (score < 0 || score > 100) {
throw new InvalidScoreException("Score must be 0-100, got: " + score);
}
}
Chapter 12 โ File I/O & Projects
import java.io.*;
import java.util.Scanner;
// Write to file:
try (FileWriter fw = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Hello, World!");
bw.newLine();
bw.write("Second line");
} catch (IOException e) {
e.printStackTrace();
}
// Read from file:
try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// PROJECT: Student Grade Calculator
public class GradeCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many students? ");
int n = sc.nextInt();
double total = 0;
for (int i = 0; i < n; i++) {
System.out.print("Score for student " + (i+1) + ": ");
total += sc.nextDouble();
}
double avg = total / n;
System.out.printf("Average: %.2f%n", avg);
System.out.println("Grade: " + (avg >= 90 ? "A" : avg >= 80 ? "B" : "C"));
sc.close();
}
}
Workbook Complete! Java is everywhere โ Android, banking, enterprise. Next steps: Spring Boot for web APIs, Android Studio for mobile, or Java algorithms for coding interviews.