No Low-Level Access â Cannot directly manipulate hardware or memory.
Basics
Hello World & Entry Point
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}
main() is the program entry point, must be public static void.
System.out.println() prints to console with newline.
Comments
// Single line comment/* Multi-line comment *//** Javadoc comment * Used for documentation generation * @param name description * @return description */
Variables & Data Types
int age = 25; // Integer (4 bytes)long bigNum = 9999999999L; // Long (8 bytes)float price = 9.99f; // Float (4 bytes)double pi = 3.14159265; // Double (8 bytes)char grade = 'A'; // Character (2 bytes, Unicode)boolean isActive = true; // Boolean (true/false)String name = "Kiro"; // String (object, not primitive)// Constantsfinal int MAX = 100;final double TAX = 0.18;
Primitive Data Types Table
Type Size Range
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes ~6-7 decimal digits precision
double 8 bytes ~15-16 decimal digits precision
char 2 bytes 0 to 65,535 (Unicode)
boolean 1 byte true / false
Type Inference (var - Java 10+)
var x = 42; // intvar y = 3.14; // doublevar s = "hello"; // Stringvar list = new ArrayList<String>(); // ArrayList<String>// var only works for local variables with initializers
User Input
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); System.out.print("Enter your name: "); scanner.nextLine(); // consume newline String name = scanner.nextLine(); System.out.println("Hello " + name + ", you entered " + num); scanner.close(); }}
// Widening (automatic)int i = 9;double d = i; // 9.0// Narrowing (manual)double d = 9.78;int i = (int) d; // 9 (truncates)// Object castingObject obj = "Hello";String str = (String) obj; // downcast// Safe casting with instanceofif (obj instanceof String) { String s = (String) obj;}// Pattern matching (Java 16+)if (obj instanceof String s) { System.out.println(s.length()); // s is already cast}
Control Flow
if / else if / else
int score = 85;if (score >= 90) { System.out.println("A");} else if (score >= 80) { System.out.println("B");} else if (score >= 70) { System.out.println("C");} else { System.out.println("F");}// Output: B
Switch Statement
int day = 3;switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Other"); break;}// Switch Expression (Java 14+)String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Other";};
Ternary Operator
int max = (a > b) ? a : b;String label = (age >= 18) ? "Adult" : "Minor";
Loops
// for loopfor (int i = 0; i < 5; i++) { System.out.print(i + " ");}// Output: 0 1 2 3 4// while loopint i = 0;while (i < 5) { System.out.print(i++);}// do-while (executes at least once)int n = 0;do { System.out.print(n++);} while (n < 3);// enhanced for (for-each)int[] nums = {1, 2, 3, 4, 5};for (int num : nums) { System.out.print(num + " ");}
break / continue / labeled
for (int i = 0; i < 10; i++) { if (i == 3) continue; // skip 3 if (i == 7) break; // stop at 7 System.out.print(i + " ");}// Output: 0 1 2 4 5 6// Labeled break â exit outer loopouter:for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) break outer; System.out.println(i + "," + j); }}
Functions (Methods)
Declaration & Calling
public class Main { // static method â called without an object static int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(add(3, 4)); // 7 }}
Method Overloading
static int area(int side) { return side * side; }static int area(int w, int h) { return w * h; }static double area(double r) { return Math.PI * r * r; }System.out.println(area(5)); // 25System.out.println(area(3, 4)); // 12System.out.println(area(2.0)); // 12.566...
Varargs
static int sum(int... nums) { int total = 0; for (int n : nums) total += n; return total;}System.out.println(sum(1, 2, 3)); // 6System.out.println(sum(1, 2, 3, 4, 5)); // 15
Recursion
static int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1);}System.out.println(factorial(5)); // 120
Lambda Expressions (Java 8+)
import java.util.function.*;// (params) -> expression// (params) -> { body }// Functional interfaceRunnable r = () -> System.out.println("Hello");r.run(); // Hello// BiFunctionBiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;System.out.println(add.apply(3, 4)); // 7// PredicatePredicate<String> isEmpty = s -> s.isEmpty();System.out.println(isEmpty.test("")); // true// FunctionFunction<String, Integer> len = s -> s.length();System.out.println(len.apply("hello")); // 5// ConsumerConsumer<String> print = s -> System.out.println(s);print.accept("World"); // World// SupplierSupplier<String> greet = () -> "Hello!";System.out.println(greet.get()); // Hello!
// Mutable string â use for heavy concatenationStringBuilder sb = new StringBuilder();sb.append("Hello");sb.append(", ");sb.append("World!");sb.insert(5, " there");sb.delete(5, 11);sb.reverse();String result = sb.toString();System.out.println(sb.length()); // current length
public class Car { // Fields String brand; int year; // Method void display() { System.out.println(brand + " (" + year + ")"); }}Car c = new Car();c.brand = "Toyota";c.year = 2022;c.display(); // Toyota (2022)
Constructors
public class Person { String name; int age; // Default constructor Person() { this.name = "Unknown"; this.age = 0; } // Parameterized constructor Person(String name, int age) { this.name = name; this.age = age; } // Constructor chaining with this() Person(String name) { this(name, 0); // calls parameterized constructor } void show() { System.out.println(name + ", " + age); }}Person p1 = new Person("Alice", 30);p1.show(); // Alice, 30
Access Modifiers
public class BankAccount { public String owner; // accessible everywhere protected double balance; // accessible in class + subclasses + package int accountNum; // package-private (default) private String pin; // accessible only inside this class}// Modifier Class Package Subclass World// public Y Y Y Y// protected Y Y Y N// (default) Y Y N N// private Y N N N
Getters & Setters (Encapsulation)
public class Temperature { private double celsius; public void setCelsius(double c) { if (c >= -273.15) this.celsius = c; } public double getCelsius() { return celsius; } public double getFahrenheit() { return celsius * 9.0 / 5.0 + 32; }}Temperature t = new Temperature();t.setCelsius(100);System.out.println(t.getFahrenheit()); // 212.0
Static Members
public class Counter { static int count = 0; // shared across all instances Counter() { count++; } static int getCount() { return count; } // static method}new Counter(); new Counter(); new Counter();System.out.println(Counter.getCount()); // 3
Records (Java 16+)
// Immutable data class â auto-generates constructor, getters, equals, hashCode, toStringrecord Point(int x, int y) {}Point p = new Point(3, 4);System.out.println(p.x()); // 3System.out.println(p.y()); // 4System.out.println(p); // Point[x=3, y=4]// Custom compact constructorrecord Range(int min, int max) { Range { if (min > max) throw new IllegalArgumentException("min > max"); }}
OOP â Inheritance
Single Inheritance
class Animal { String name; Animal(String name) { this.name = name; } void eat() { System.out.println(name + " is eating"); }}class Dog extends Animal { Dog(String name) { super(name); } // call parent constructor void bark() { System.out.println(name + " says Woof!"); }}Dog d = new Dog("Rex");d.eat(); // Rex is eatingd.bark(); // Rex says Woof!
class Vehicle { String type = "Vehicle"; void info() { System.out.println("I am a " + type); }}class Car extends Vehicle { String type = "Car"; void info() { super.info(); // call parent method System.out.println("I am a " + type); System.out.println("Parent type: " + super.type); // parent field }}
final Keyword
final int MAX = 100; // constant â cannot reassignfinal class Immutable { ... } // cannot be subclassedclass Base { final void locked() { ... } // cannot be overridden}
Abstract Classes
abstract class Animal { abstract void sound(); // must be implemented by subclass void breathe() { System.out.println("Breathing..."); } // concrete method}// Animal a = new Animal(); // ERROR â cannot instantiate abstract classclass Dog extends Animal { @Override void sound() { System.out.println("Woof!"); }}Animal a = new Dog();a.sound(); // Woof!a.breathe(); // Breathing...
Interfaces
interface Flyable { void fly(); // abstract by default default void land() { // default method (Java 8+) System.out.println("Landing..."); } static void info() { // static method (Java 8+) System.out.println("Flyable interface"); }}interface Swimmable { void swim();}// A class can implement multiple interfacesclass Duck implements Flyable, Swimmable { public void fly() { System.out.println("Duck flying"); } public void swim() { System.out.println("Duck swimming"); }}Duck d = new Duck();d.fly(); // Duck flyingd.swim(); // Duck swimmingd.land(); // Landing... (default method)Flyable.info(); // Flyable interface (static method)
// Restrict which classes can extend/implementsealed class Shape permits Circle, Rectangle, Triangle {}final class Circle extends Shape { double r; }final class Rectangle extends Shape { double w, h; }non-sealed class Triangle extends Shape {} // can be extended freely// Works great with pattern matching switch (Java 21+)double area(Shape s) { return switch (s) { case Circle c -> Math.PI * c.r * c.r; case Rectangle r -> r.w * r.h; case Triangle t -> 0; // handle };}
OOP â Advanced Concepts
Generics
// Generic classclass Stack<T> { private List<T> data = new ArrayList<>(); public void push(T val) { data.add(val); } public T pop() { return data.remove(data.size() - 1); } public T peek() { return data.get(data.size() - 1); } public boolean isEmpty() { return data.isEmpty(); }}Stack<Integer> si = new Stack<>();si.push(1); si.push(2); si.push(3);System.out.println(si.peek()); // 3// Generic methodstatic <T extends Comparable<T>> T maxOf(T a, T b) { return (a.compareTo(b) > 0) ? a : b;}System.out.println(maxOf(3, 7)); // 7System.out.println(maxOf("apple", "banana")); // banana// Wildcardsvoid printList(List<?> list) { ... } // unknown typevoid addNumbers(List<? extends Number> list) { ... } // upper boundvoid addInts(List<? super Integer> list) { ... } // lower bound
Enums
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN}Day d = Day.WED;System.out.println(d); // WEDSystem.out.println(d.ordinal()); // 2System.out.println(d.name()); // WED// Enum with fields & methodsenum Planet { MERCURY(3.303e+23, 2.4397e6), EARTH(5.976e+24, 6.37814e6); private final double mass, radius; Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } double surfaceGravity() { return 6.67300E-11 * mass / (radius * radius); }}System.out.println(Planet.EARTH.surfaceGravity()); // 9.802...// Switch on enumswitch (d) { case SAT, SUN -> System.out.println("Weekend"); default -> System.out.println("Weekday");}
Functional Interfaces & @FunctionalInterface
@FunctionalInterfaceinterface Transformer<T, R> { R transform(T input);}Transformer<String, Integer> len = s -> s.length();System.out.println(len.transform("hello")); // 5// Built-in functional interfaces (java.util.function)// Function<T,R> â T -> R// BiFunction<T,U,R>â (T,U) -> R// Predicate<T> â T -> boolean// Consumer<T> â T -> void// Supplier<T> â () -> T// UnaryOperator<T> â T -> T// BinaryOperator<T>â (T,T) -> T
Collections Framework
Collections Overview
Interface Implementation Use Case
List ArrayList Dynamic array, fast random access
List LinkedList Fast insert/remove at ends
Set HashSet Unique elements, O(1) avg lookup
Set LinkedHashSet Unique elements, insertion order
Set TreeSet Unique sorted elements
Map HashMap Key-value, O(1) avg lookup
Map LinkedHashMap Key-value, insertion order
Map TreeMap Key-value, sorted by key
Queue ArrayDeque FIFO / LIFO (preferred over Stack)
Queue PriorityQueue Min-heap by default
List â ArrayList & LinkedList
import java.util.*;List<Integer> list = new ArrayList<>();list.add(1); list.add(2); list.add(3);list.add(1, 99); // insert at index 1 â [1,99,2,3]list.remove(Integer.valueOf(99)); // remove by valuelist.remove(0); // remove by indexSystem.out.println(list.get(0)); // 1System.out.println(list.size()); // 2System.out.println(list.contains(2)); // trueCollections.sort(list);Collections.reverse(list);Collections.shuffle(list);// Iteratefor (int x : list) System.out.print(x + " ");list.forEach(System.out::println);
// Checked â must declare with throws or catchvoid readFile(String path) throws IOException { FileReader fr = new FileReader(path); // throws FileNotFoundException}// Unchecked â RuntimeException, no need to declarevoid process(String s) { System.out.println(s.length()); // NullPointerException if s is null}
Custom Exceptions
class AppException extends RuntimeException { private final int code; AppException(String message, int code) { super(message); this.code = code; } int getCode() { return code; }}throw new AppException("Something went wrong", 500);
try-with-resources (Java 7+)
// AutoCloseable resources are closed automaticallytry (FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr)) { String line; while ((line = br.readLine()) != null) { System.out.println(line); }} catch (IOException e) { e.printStackTrace();}// fr and br are closed even if exception occurs