Practice library / More programming languages
Workbook · Easy · 6 hours
Java Fundamentals
Java OOP, JVM, serialisation, and security-relevant Java concepts.
On this page 12 sections
- ·Chapter 1 — What is Java?
- ·Chapter 2 — Setup & Hello World
- ·Chapter 3 — Variables & Data Types
- ·Chapter 4 — Operators & Control Flow
- ·Chapter 5 — Methods
- ·Chapter 6 — Arrays
- ·Chapter 7 — Classes & Objects
- ·Chapter 8 — Inheritance
- ·Chapter 9 — Interfaces
- ·Chapter 10 — Collections
- ·Chapter 11 — Exception Handling
- ·Chapter 12 — File I/O & Projects
Java runs behind many banks, Android phones, and large enterprise stacks. Its wide use makes it a common target: a deserialisation bug or a vulnerable library can affect a very large number of servers. A security engineer who reads Java well can audit a backend service, reproduce a CVE, and reason about Android apps. This workbook covers the language from zero: variables, control flow, classes, inheritance, interfaces, collections, generics, and exceptions. It shows the JVM, the build process, and the parts of Java that matter for security work. The paired lab explores insecure deserialisation, a serious Java attack path in production systems.
Install Java. Download the JDK from adoptium.net (free). Then install VS Code and the "Extension Pack for Java". Alternatively, use replit.com, which is free and needs no installation.
Chapter 1 — What is Java?
Java is a strongly typed, object-oriented language that runs on the JVM (Java Virtual Machine). Its slogan is "write once, run anywhere": the same code works on Windows, macOS, Linux and Android.
Java is used for Android apps, enterprise backends (Spring), banking systems, Minecraft and 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: 25Chapter 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]); // HelloChapter 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()); // blackChapter 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 widely used in Android, banking and enterprise systems. Next steps: Spring Boot for web APIs, Android Studio for mobile apps, or Java algorithms for coding interviews.
Sign in to track progress and send feedback.