← Tutorials ☕ Java 🧩 DSA 🌿 Spring Boot 🚀 DevOps 🗂 MySQL 🏗 System Design ❓ FAQ 🌐 HTML 🔇 JavaScript ⚛ ReactJS 🌻 NodeJS 🐍 Python 🍏 MongoDB 📋 Cheatsheet
Tutorials › Java

Introduction to Java

☕ Java · Getting Started · 5 min read

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995 (now owned by Oracle). It follows the Write Once, Run Anywhere (WORA) principle — code compiled to bytecode runs on any platform with a JVM.

Why Learn Java?

  • Most popular language for enterprise backend development
  • Powers Android apps, Spring Boot APIs, and big-data tools
  • Strong type system catches bugs at compile time
  • Massive ecosystem — Maven, Gradle, Spring, Hibernate

Key Components

  • JDK — Java Development Kit (compiler + tools)
  • JRE — Java Runtime Environment (runs bytecode)
  • JVM — Java Virtual Machine (executes on the host OS)
💡 Use JDK 17 or 21 for new projects — both are LTS (Long-Term Support) versions.

Setup & Installation

☕ Java · Getting Started · 5 min read

Install the JDK and set up your development environment before writing your first line of Java.

Step 1 — Download JDK 21

Go to adoptium.net and download the Temurin JDK 21 for your OS. It's free and open source.

Step 2 — Verify Installation

java -version
javac -version

Step 3 — Choose an IDE

  • IntelliJ IDEA — best-in-class for Java (Community edition is free)
  • Eclipse — classic, used widely in enterprise
  • VS Code — lightweight with Java Extension Pack

Hello World

☕ Java · Getting Started · 3 min read

Every Java program starts with a class. The entry point is the main method.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

To Run

javac HelloWorld.java
java HelloWorld
💡 Since Java 11 you can also run a single-file program directly: java HelloWorld.java

Variables & Data Types

☕ Java · Core Concepts · 6 min read

Java is statically typed — every variable has a declared type that cannot change.

Primitive Types

int age = 25;
long population = 8_000_000_000L;
double price = 99.99;
boolean isActive = true;
char grade = 'A';
byte level = 5;
short code = 1234;
float temp = 36.6f;

Reference Types

String name = "Aftab";
int[] scores = {90, 85, 92};
Object obj = null;

var (Java 10+)

var message = "Hello"; // inferred as String
var count = 42; // inferred as int

Operators

☕ Java · Core Concepts · 4 min read

Arithmetic

int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1 (modulus)

Comparison & Logical

a == b; a != b; a > b; a < b; a >= b; a <= b;
(a > 5) && (b < 5); // AND
(a > 5) || (b > 5); // OR
!(a == b); // NOT

Ternary

String result = (a > b) ? "greater" : "not greater";

Control Flow

☕ Java · Core Concepts · 6 min read

if / else

if (score >= 90) {
    System.out.println("A");
} else if (score >= 75) {
    System.out.println("B");
} else {
    System.out.println("C");
}

switch (Java 14+ enhanced)

String day = "MON";
String type = switch (day) {
    case "SAT", "SUN" -> "Weekend";
    default -> "Weekday";
};

Loops

// for
for (int i = 0; i < 5; i++) { System.out.println(i); }

// while
int n = 0;
while (n < 5) { System.out.println(n++); }

// for-each
int[] nums = {1, 2, 3};
for (int x : nums) { System.out.println(x); }

Arrays

☕ Java · Core Concepts · 5 min read

Arrays in Java are fixed-size, zero-indexed, and hold elements of the same type.

int[] nums = new int[5]; // size 5, all zeros
int[] scores = {90, 85, 92, 78}; // initializer
scores[0] = 95; // update element
System.out.println(scores.length); // 4

2D Arrays

int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(matrix[1][2]); // 6

Arrays Utility

import java.util.Arrays;
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));

Strings

☕ Java · Core Concepts · 6 min read

Strings in Java are immutable objects of the String class.

String s = "Hello, Java";
s.length() // 11
s.toUpperCase() // "HELLO, JAVA"
s.substring(7) // "Java"
s.contains("Java") // true
s.replace("Java", "World") // "Hello, World"
s.split(", ") // ["Hello", "Java"]
s.trim() // removes leading/trailing spaces

String Comparison

s.equals("Hello, Java") // true — use this!
s.equalsIgnoreCase("hello, java") // true
s == "Hello, Java" // may be false — avoid!

StringBuilder (mutable)

StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" Java");
System.out.println(sb.toString()); // "Hello Java"

Classes & Objects

☕ Java · OOP · 7 min read

A class is a blueprint; an object is an instance of that class.

public class Person {
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String greet() {
        return "Hi, I'm " + name;
    }
}

// Usage
Person p = new Person("Aftab", 30);
System.out.println(p.greet());

Inheritance

☕ Java · OOP · 6 min read

Inheritance lets a child class reuse code from a parent class using extends.

public class Animal {
    public void eat() { System.out.println("eating"); }
}

public class Dog extends Animal {
    public void bark() { System.out.println("woof!"); }
}

Dog d = new Dog();
d.eat(); // inherited
d.bark(); // own method
💡 Java supports only single inheritance for classes. Use interfaces for multiple inheritance of type.

Polymorphism

☕ Java · OOP · 5 min read

Polymorphism means "many forms." A parent reference can hold a child object and call overridden methods.

class Shape {
    public String draw() { return "shape"; }
}
class Circle extends Shape {
    @Override public String draw() { return "circle"; }
}
class Square extends Shape {
    @Override public String draw() { return "square"; }
}

Shape s = new Circle();
System.out.println(s.draw()); // "circle" — runtime dispatch

Interfaces & Abstract Classes

☕ Java · OOP · 6 min read
interface Flyable {
    void fly(); // implicitly public abstract
    default void land() { System.out.println("landing"); }
}

class Bird implements Flyable {
    @Override public void fly() { System.out.println("flap flap"); }
}

Abstract Class

abstract class Vehicle {
    abstract void move();
    void stop() { System.out.println("stopped"); }
}
💡 Use an interface when unrelated classes share a capability. Use an abstract class when related classes share state/behaviour.

Encapsulation

☕ Java · OOP · 4 min read

Hide internal state behind private fields and expose it through public getters/setters.

public class BankAccount {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
}

Collections Framework

☕ Java · Advanced · 8 min read

List

List<String> names = new ArrayList<>();
names.add("Alice"); names.add("Bob");
names.get(0); // "Alice"
names.size(); // 2
names.remove("Bob");

Map

Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.get("Alice"); // 95
scores.containsKey("Bob"); // false

Set

Set<Integer> unique = new HashSet<>(List.of(1,2,2,3));
// {1, 2, 3} — duplicates removed

Generics

☕ Java · Advanced · 5 min read

Generics let you write type-safe code that works for any type without casting.

public class Box<T> {
    private T value;
    public Box(T value) { this.value = value; }
    public T get() { return value; }
}

Box<String> strBox = new Box<>("hello");
Box<Integer> intBox = new Box<>(42);

Exception Handling

☕ Java · Advanced · 6 min read
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("always runs");
}

Custom Exception

public class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException(String msg) { super(msg); }
}

Streams & Lambda (Java 8+)

☕ Java · Advanced · 8 min read

Streams allow functional-style operations on collections — filter, map, reduce — without loops.

List<Integer> nums = List.of(1,2,3,4,5,6);

// filter evens, square them, collect
List<Integer> result = nums.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .collect(Collectors.toList());
// [4, 16, 36]

Common Stream Operations

nums.stream().reduce(0, Integer::sum); // sum = 21
nums.stream().count(); // 6
nums.stream().anyMatch(n -> n > 5); // true
nums.stream().sorted().toList(); // [1,2,3,4,5,6]

Multithreading

☕ Java · Advanced · 8 min read

Creating Threads

// Using Runnable (preferred)
Thread t = new Thread(() -> {
    System.out.println("Running in thread: " + Thread.currentThread().getName());
});
t.start();

ExecutorService

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("task 1"));
pool.submit(() -> System.out.println("task 2"));
pool.shutdown();

synchronized

public synchronized void increment() {
    count++; // thread-safe
}
💡 Prefer java.util.concurrent classes (AtomicInteger, ConcurrentHashMap, ExecutorService) over raw synchronized for most use cases.