Java Tutorial: Complete Guide

Java Tutorial: Complete Guide with Examples & Visual Diagrams | TKTips.org
Complete Java Tutorial: Learn Programming with Interactive Examples & Visual Guides

Java Basics

Java is a powerful, object-oriented programming language used for building enterprise-scale applications, Android apps, and web applications.

Platform Independence

“Write Once, Run Anywhere” – Java code compiles to bytecode that runs on any Java Virtual Machine (JVM).

Memory Management

Automatic garbage collection manages memory allocation and deallocation automatically.

Object-Oriented

Everything in Java is an object, following principles of inheritance, polymorphism, and encapsulation.

Your First Java Program

HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
How Java Program Works
Java Source
.java file
β†’
Java Compiler
javac command
β†’
Bytecode
.class file
β†’
JVM
java command

Variables and Data Types

VariablesExample.java
public class VariablesExample {
    public static void main(String[] args) {
        // Primitive data types
        int age = 25;
        double price = 99.99;
        char grade = 'A';
        boolean isJavaFun = true;
        
        // Reference data type
        String name = "John Doe";
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Price: $" + price);
    }
}
Interactive Example: Variable Types

Change variable values and see the output:

Output will appear here…

Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code.

Vehicle
– brand: String
– speed: double
+ accelerate(): void
+ brake(): void
↓
Car extends Vehicle
– numDoors: int
– fuelType: String
+ honk(): void
+ openTrunk(): void

Four Pillars of OOP

Encapsulation

Bundling data and methods that operate on that data within a single unit (class).

private String name; public String getName() { … }

Inheritance

Creating new classes based on existing classes to reuse code and establish relationships.

class Car extends Vehicle { … }

Polymorphism

Ability of objects to take many forms – same method behaves differently based on the object.

Vehicle v = new Car(); v.accelerate(); // Calls Car’s accelerate

Abstraction

Hiding implementation details and showing only essential features to the user.

abstract class Shape { abstract void draw(); }

Java Memory Management

Stack vs Heap Memory
Stack Memory
main() method frame
car1 (reference) 0x1001
age 25
calculate() frame
result 42.5
Heap Memory
Car object @0x1001
brand “Toyota”
speed 60.5
String object
value “Hello”
OOP Example: Car Class
public class Car {
    // Attributes (Encapsulation)
    private String brand;
    private double speed;
    
    // Constructor
    public Car(String brand) {
        this.brand = brand;
        this.speed = 0;
    }
    
    // Methods
    public void accelerate(double amount) {
        this.speed += amount;
        System.out.println("Accelerating! Speed: " + speed);
    }
    
    public void brake(double amount) {
        this.speed = Math.max(0, speed - amount);
        System.out.println("Braking! Speed: " + speed);
    }
    
    // Getters and Setters (Encapsulation)
    public String getBrand() { return brand; }
    public void setBrand(String brand) { this.brand = brand; }
}
What is the output of this code?
Vehicle v = new Car();
if (v instanceof Car) {
    System.out.print("Car");
} else if (v instanceof Vehicle) {
    System.out.print("Vehicle");
}
  • A. Car
  • B. Vehicle
  • C. CarVehicle
  • D. Compilation Error

Collections Framework

The Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data.

Collections Hierarchy
Collections Framework Diagram
Simplified view of Java Collections Framework hierarchy

Common Collection Types

List

Ordered collection that allows duplicates. Elements can be accessed by index.

ArrayList<String>, LinkedList<Integer>

Set

Collection that contains no duplicate elements. Unordered by default.

HashSet<String>, TreeSet<Integer>

Map

Object that maps keys to values. Cannot contain duplicate keys.

HashMap<String, Integer>, TreeMap<Integer, String>
CollectionsExample.java
import java.util.*;

public class CollectionsExample {
    public static void main(String[] args) {
        // List Example
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        
        // Set Example
        Set<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(1); // Duplicate, won't be added
        
        // Map Example
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 95);
        scores.put("Bob", 87);
        
        // Iterating through collections
        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

Streams and Lambda Expressions (Java 8+)

StreamsExample.java
import java.util.*;
import java.util.stream.*;

public class StreamsExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
        
        // Filter even numbers and square them
        List<Integer> result = numbers.stream()
            .filter(n -> n % 2 == 0)   // Lambda expression
            .map(n -> n * n)           // Square each number
            .collect(Collectors.toList());
        
        System.out.println("Result: " + result);
        
        // Sum all numbers
        int sum = numbers.stream()
            .reduce(0, (a, b) -> a + b);
        
        System.out.println("Sum: " + sum);
    }
}
Interactive Stream Operations

Try different stream operations on a list of numbers:

Original: [5, 2, 9, 1, 7, 4, 8, 3, 6]

Advanced Java Topics

Explore advanced Java concepts including multithreading, exception handling, design patterns, and modern Java features.

Multithreading

Thread Lifecycle
NEW
New
β†’
RUNNABLE
Runnable
β†’
RUNNING
Running
β†’
TERMINATED
Terminated
ThreadExample.java
public class ThreadExample {
    public static void main(String[] args) {
        // Create threads
        Thread thread1 = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Thread 1: " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        Thread thread2 = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Thread 2: " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        // Start threads
        thread1.start();
        thread2.start();
    }
}

Exception Handling

ExceptionExample.java
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
            System.out.println("Exception details: " + e.getMessage());
        } finally {
            System.out.println("This always executes");
        }
    }
    
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
}

Modern Java Features

Records (Java 16)

Immutable data classes with automatically generated methods.

record Person(String name, int age) {}

Pattern Matching (Java 21)

Simplifies conditional extraction of data from objects.

if (obj instanceof String s) { // use s as String }

Virtual Threads (Java 21)

Lightweight threads for high-throughput concurrent applications.

Thread.startVirtualThread(() -> { // task });
What is the difference between ‘throw’ and ‘throws’ in Java?
  • A. ‘throw’ is used to explicitly throw an exception, ‘throws’ declares exceptions a method might throw
  • B. ‘throws’ is used to explicitly throw an exception, ‘throw’ declares exceptions
  • C. Both are used to throw exceptions
  • D. There is no difference