Java Cheatsheet

Classes and Objects

Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Class Declaration

[modifiers] class ClassName [extends SuperClass] [implements Interface1, Interface2] {
    // fields, constructors, methods, nested classes
}
public class Person {
    // fields
    private String name;
    private int age;

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

    // method
    public String getName() { return name; }
    public int    getAge()  { return age;  }
    public void   setAge(int age) {
        if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
        this.age = age;
    }

    @Override public String toString() { return "Person{name=" + name + ", age=" + age + "}"; }
    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person p)) return false;
        return age == p.age && Objects.equals(name, p.name);
    }
    @Override public int hashCode() { return Objects.hash(name, age); }
}

Fields

public class Example {
    // Instance fields
    private int value;              // per-object state
    public String label;

    // Static fields (class-level, shared)
    private static int count = 0;
    public static final double PI = 3.14159; // constant

    // Instance initializer block (runs before constructor body)
    {
        value = -1;
        count++;
    }

    // Static initializer block (runs once when class is loaded)
    static {
        System.out.println("Class loaded");
    }
}

Constructors

public class Rectangle {
    private final int width, height;

    // No-arg constructor
    public Rectangle() {
        this(1, 1);               // delegate to another constructor with this()
    }

    // Parameterized constructor
    public Rectangle(int width, int height) {
        this.width  = width;
        this.height = height;
    }

    // Copy constructor
    public Rectangle(Rectangle other) {
        this(other.width, other.height);
    }

    public int area() { return width * height; }
}

// If no constructor is defined, compiler provides a default no-arg one
// Once ANY constructor is defined, the default is NOT provided

Creating Objects

Person alice = new Person("Alice", 30);
Person bob   = new Person("Bob",   25);

// Anonymous object (reference discarded)
System.out.println(new Person("Anon", 0).getName());

// Object array
Person[] people = new Person[3];
people[0] = alice;

// Multiple references to same object
Person ref1 = alice;
Person ref2 = alice;    // ref1 == ref2 == alice (same object)

// null reference
Person nobody = null;
nobody.getName();       // NullPointerException!

this Keyword

public class Node {
    int val;
    Node next;

    Node(int val) {
        this.val  = val;    // disambiguate field from param
        this.next = null;
    }

    // Return this for fluent/chaining APIs
    Node setNext(Node n) {
        this.next = n;
        return this;
    }

    // Pass self as argument
    void register(Registry r) {
        r.add(this);
    }
}

Getters, Setters, and Encapsulation

public class BankAccount {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Must be positive");
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) throw new IllegalStateException("Insufficient funds");
        balance -= amount;
    }
}

Static Members

public class Counter {
    private static int count = 0;      // shared across all instances

    public Counter() { count++; }

    public static int getCount() { return count; }    // static method
    // static methods cannot access instance fields or call instance methods
    // static methods cannot use 'this'
}

int n = Counter.getCount();   // called on the class

Nested and Inner Classes

// Static nested class — no access to outer instance
public class Outer {
    private static int data = 10;

    static class Nested {
        void show() { System.out.println(data); } // can access outer static
    }
}
Outer.Nested n = new Outer.Nested();

// Non-static inner class — has access to outer instance
public class Outer {
    private int x = 5;

    class Inner {
        void show() { System.out.println(x); }  // accesses outer.x
    }
}
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

// Local class — defined inside a method
void process() {
    class Helper { void help() { ... } }
    new Helper().help();
}

// Anonymous class — one-off implementation
Runnable r = new Runnable() {
    @Override public void run() { System.out.println("running"); }
};

Object Methods (java.lang.Object)

Every class inherits these from Object:

MethodDescription
equals(Object o)Value equality; default is reference (==)
hashCode()Must be consistent with equals
toString()Default: ClassName@hashcode
getClass()Returns runtime Class<?> object
clone()Shallow copy; class must implement Cloneable
finalize()Deprecated; called before GC (avoid using)
wait() / notify() / notifyAll()Thread synchronization on object monitor
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof MyClass other)) return false;
    return Objects.equals(field1, other.field1) && field2 == other.field2;
}

@Override
public int hashCode() {
    return Objects.hash(field1, field2);
}

@Override
public String toString() {
    return "MyClass{field1=" + field1 + ", field2=" + field2 + "}";
}

Records (Java 16+)

Immutable value carriers — compiler generates constructor, accessors, equals, hashCode, toString.

record Point(double x, double y) {
    // Compact canonical constructor (validation)
    Point {
        if (Double.isNaN(x) || Double.isNaN(y))
            throw new IllegalArgumentException("NaN not allowed");
    }

    // Custom method
    double distanceTo(Point other) {
        return Math.sqrt(Math.pow(x - other.x, 2) + Math.pow(y - other.y, 2));
    }
}

Point p = new Point(3.0, 4.0);
p.x()           // 3.0 (accessor, not getX())
p.y()           // 4.0
p.toString()    // "Point[x=3.0, y=4.0]"

Builder Pattern

Common for classes with many optional fields.

public class HttpRequest {
    private final String url;
    private final String method;
    private final String body;
    private final int timeoutMs;

    private HttpRequest(Builder b) {
        this.url       = b.url;
        this.method    = b.method;
        this.body      = b.body;
        this.timeoutMs = b.timeoutMs;
    }

    public static class Builder {
        private final String url;
        private String method    = "GET";
        private String body      = "";
        private int    timeoutMs = 5000;

        public Builder(String url) { this.url = url; }
        public Builder method(String m) { method = m; return this; }
        public Builder body(String b)   { body   = b; return this; }
        public Builder timeout(int ms)  { timeoutMs = ms; return this; }
        public HttpRequest build()      { return new HttpRequest(this); }
    }
}

HttpRequest req = new HttpRequest.Builder("https://example.com")
    .method("POST")
    .body("{\"key\":\"value\"}")
    .timeout(3000)
    .build();

Singleton Pattern

public class Config {
    private static final Config INSTANCE = new Config();    // eager
    private Config() {}
    public static Config getInstance() { return INSTANCE; }

    // Or lazy + thread-safe with initialization-on-demand holder:
    private static class Holder {
        static final Config INSTANCE = new Config();
    }
    public static Config get() { return Holder.INSTANCE; }
}

Comparable and Comparator

// Comparable: natural ordering built into the class
public class Student implements Comparable<Student> {
    String name;
    double gpa;

    @Override
    public int compareTo(Student other) {
        return Double.compare(this.gpa, other.gpa); // ascending GPA
    }
}

List<Student> students = ...;
Collections.sort(students);          // uses compareTo

// Comparator: external, reusable ordering
Comparator<Student> byName = Comparator.comparing(s -> s.name);
Comparator<Student> byGpaDesc = Comparator.comparingDouble((Student s) -> s.gpa)
                                          .reversed();
Comparator<Student> byGpaThenName = Comparator
    .comparingDouble((Student s) -> s.gpa)
    .thenComparing(s -> s.name);

students.sort(byGpaDesc);
students.sort(Comparator.naturalOrder());
students.sort(Comparator.reverseOrder());

Cloning Objects

// Shallow clone via Cloneable
public class Config implements Cloneable {
    int[] values;

    @Override
    public Config clone() {
        try {
            Config c = (Config) super.clone();  // copies all fields shallowly
            c.values = values.clone();           // deep copy mutable fields manually
            return c;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

Class Metadata (Reflection Basics)

Class<?> cls = obj.getClass();
cls.getName()                          // fully-qualified class name
cls.getSimpleName()                    // "Person"
cls.getMethods()                       // public methods (incl. inherited)
cls.getDeclaredFields()                // all fields declared in this class
cls.getDeclaredMethod("greet", String.class)
cls.isInstance(obj)                    // like instanceof

// Check type at runtime
boolean is = obj instanceof String;