Java Cheatsheet

Data Types

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

Primitive Types

TypeSizeDefaultMinMaxLiteral Example
byte8-bit0-128127(byte) 127
short16-bit0-32,76832,767(short) 1000
int32-bit0-2,147,483,6482,147,483,64742
long64-bit0L-2^632^63-19_999L
float32-bit0.0f~1.4e-45~3.4e383.14f
double64-bit0.0d~5.0e-324~1.8e3083.14
char16-bit'''' (0)'￿' (65,535)'A'
boolean1-bitfalsetrue / false
byte  b = 127;
short s = 32_000;
int   i = 2_147_483_647;
long  l = 9_223_372_036_854_775_807L;
float f  = 3.14f;
double d = 3.141592653589793;
char   c = 'A';        // or 'A'
boolean flag = true;

Numeric Literals

int decimal = 1_000_000;        // underscores allowed anywhere (Java 7+)
int hex     = 0xFF;             // 255
int octal   = 0755;             // 493
int binary  = 0b1010_1100;      // 172 (Java 7+)

long big    = 9_876_543_210L;   // L suffix required beyond int range
float  f    = 1.5f;             // F or f
double d    = 1.5e10;           // scientific notation → 15000000000.0
double d2   = 0x1.fp10;         // hex float

Wrapper Classes

Every primitive has a corresponding wrapper class in java.lang.

PrimitiveWrapper
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
Integer a = Integer.valueOf(42);      // explicit boxing
int     x = a.intValue();            // explicit unboxing
Integer b = 42;                       // autoboxing
int     y = b;                        // autounboxing

NullPointerException trap: Integer n = null; int x = n; throws NPE during autounboxing.

Wrapper Utility Methods

// Integer
Integer.parseInt("123")             // String → int (throws NumberFormatException)
Integer.parseInt("FF", 16)          // parse hex → 255
Integer.toString(255)               // int → String "255"
Integer.toBinaryString(10)          // "1010"
Integer.toHexString(255)            // "ff"
Integer.toOctalString(8)            // "10"
Integer.MAX_VALUE                   // 2147483647
Integer.MIN_VALUE                   // -2147483648
Integer.bitCount(255)               // 8 (number of 1-bits)
Integer.reverse(1)                  // reverses bit order
Integer.compare(a, b)               // negative/0/positive
Integer.sum(a, b)                   // a + b (useful as method ref)

// Double
Double.parseDouble("3.14")
Double.isNaN(0.0 / 0.0)            // true
Double.isInfinite(1.0 / 0.0)       // true
Double.MAX_VALUE
Double.MIN_VALUE                    // smallest positive non-zero

// Character
Character.isDigit('5')             // true
Character.isLetter('a')            // true
Character.isLetterOrDigit('_')     // false
Character.isWhitespace(' ')        // true
Character.isUpperCase('A')         // true
Character.isLowerCase('a')         // true
Character.toUpperCase('a')         // 'A'
Character.toLowerCase('A')         // 'a'
Character.getNumericValue('9')     // 9

// Boolean
Boolean.parseBoolean("true")       // true
Boolean.parseBoolean("TRUE")       // true (case-insensitive)
Boolean.parseBoolean("yes")        // false (only "true" is true)
Boolean.toString(true)             // "true"

Arrays

// Declaration and initialization
int[] arr = new int[5];                     // [0, 0, 0, 0, 0]
int[] arr2 = {1, 2, 3, 4, 5};              // array literal
int[] arr3 = new int[]{1, 2, 3};

// Multi-dimensional
int[][] matrix = new int[3][4];
int[][] grid = {{1, 2}, {3, 4}, {5, 6}};
int[][] jagged = new int[3][];              // rows have different lengths
jagged[0] = new int[2];
jagged[1] = new int[5];

// Access
arr[0] = 10;
System.out.println(arr.length);    // 5 (field, not method)

// Copy
int[] copy = arr.clone();
int[] copy2 = Arrays.copyOf(arr, arr.length);
int[] slice = Arrays.copyOfRange(arr, 1, 4); // [1,4) exclusive end
System.arraycopy(src, srcPos, dest, destPos, length);

// Sort / Search
Arrays.sort(arr);
Arrays.sort(arr, 1, 4);                         // sort [1,4) subrange
int idx = Arrays.binarySearch(arr, 3);          // requires sorted
Arrays.sort(strArr, Comparator.reverseOrder());  // reverse sort (Object[])

// Fill and compare
Arrays.fill(arr, 0);
Arrays.fill(arr, 2, 5, -1);       // fill [2,5) with -1
boolean eq = Arrays.equals(arr, arr2);
boolean deepEq = Arrays.deepEquals(matrix, matrix2);

// String representation
System.out.println(Arrays.toString(arr));        // [1, 2, 3]
System.out.println(Arrays.deepToString(matrix)); // [[1,2],[3,4]]

// Stream from array (Java 8+)
int sum = Arrays.stream(arr).sum();
IntStream s = Arrays.stream(arr, 1, 4);         // subrange stream

String (Reference Type)

String s = "hello";           // string literal (pooled)
String s2 = new String("hello"); // new object (avoid)
String s3 = null;             // reference can be null

See the Strings cheatsheet for full method coverage.

var — Local Type Inference (Java 10+)

var x = 42;                          // int
var list = new ArrayList<String>();  // ArrayList<String>
var map = new HashMap<String, List<Integer>>(); // inferred

// Restrictions
var x;            // ERROR: must initialize
var x = null;     // ERROR: cannot infer type from null
// Only for local variables, for-each variables, and try-with-resources

Records (Java 16+)

Immutable data carriers. Compiler generates constructor, accessors, equals, hashCode, toString.

record Point(int x, int y) {}

Point p = new Point(3, 4);
p.x()          // 3
p.y()          // 4
p.toString()   // "Point[x=3, y=4]"

// Custom compact constructor (validate/normalize)
record Range(int lo, int hi) {
    Range {
        if (lo > hi) throw new IllegalArgumentException();
    }
}

// Records can implement interfaces
record Color(int r, int g, int b) implements Comparable<Color> {
    @Override public int compareTo(Color o) { ... }
}

Enums

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

Day d = Day.MON;
d.name()            // "MON"
d.ordinal()         // 0
Day.valueOf("FRI")  // Day.FRI
Day[] all = Day.values();

// Enum with fields and methods
enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS  (4.869e+24, 6.0518e6),
    EARTH  (5.976e+24, 6.37814e6);

    private final double mass;
    private final double radius;

    Planet(double mass, double radius) {
        this.mass   = mass;
        this.radius = radius;
    }

    double surfaceGravity() {
        final double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}

// Enum in switch
switch (d) {
    case MON, TUE, WED, THU, FRI -> System.out.println("Weekday");
    case SAT, SUN                 -> System.out.println("Weekend");
}

Sealed Classes (Java 17+)

Restrict which classes can extend or implement a type.

sealed interface Shape permits Circle, Rectangle, Triangle {}

record Circle(double radius)         implements Shape {}
record Rectangle(double w, double h) implements Shape {}
final class Triangle                 implements Shape {
    final double base, height;
    Triangle(double b, double h) { base = b; height = h; }
}

// Pattern matching switch (Java 21+)
double area = switch (shape) {
    case Circle c       -> Math.PI * c.radius() * c.radius();
    case Rectangle r    -> r.w() * r.h();
    case Triangle t     -> 0.5 * t.base * t.height;
};

Optional (Java 8+)

Avoids returning null from methods.

Optional<String> opt = Optional.of("hello");
Optional<String> empty = Optional.empty();
Optional<String> maybe = Optional.ofNullable(possiblyNull);

opt.isPresent()                 // true
opt.isEmpty()                   // false (Java 11+)
opt.get()                       // "hello" — throws if empty
opt.orElse("default")           // value or "default"
opt.orElseGet(() -> compute())  // lazy supplier
opt.orElseThrow()               // throws NoSuchElementException if empty
opt.orElseThrow(RuntimeException::new)
opt.map(String::toUpperCase)    // Optional<String> "HELLO"
opt.flatMap(s -> Optional.of(s.length())) // Optional<Integer>
opt.filter(s -> s.length() > 3)           // same or empty
opt.ifPresent(System.out::println)
opt.ifPresentOrElse(System.out::println, () -> System.out.println("empty"));

Type Casting and instanceof

// Widening (implicit)
int i = 42;
long l  = i;
float f = i;
double d = i;

// Narrowing (explicit, may lose precision or cause overflow)
double pi = 3.99;
int n = (int) pi;          // 3 — truncates toward zero

// Reference casting
Object obj = "text";
if (obj instanceof String) {
    String s = (String) obj;          // explicit cast
}

// Pattern matching instanceof (Java 16+) — preferred
if (obj instanceof String s) {
    System.out.println(s.toUpperCase());
}

// Guarded pattern (Java 21+)
if (obj instanceof String s && s.length() > 3) { ... }

Special Float/Double Values

double inf     = Double.POSITIVE_INFINITY;    // 1.0 / 0.0
double negInf  = Double.NEGATIVE_INFINITY;    // -1.0 / 0.0
double nan     = Double.NaN;                  // 0.0 / 0.0

Double.isInfinite(inf)    // true
Double.isNaN(nan)         // true
nan == nan                // false! — always use Double.isNaN()