Java cheat sheet

Types, control flow, arrays, collections, classes and exceptions in tables for quick reference.

Quick reference. To learn each topic in depth, go to the interactive Java examples.

Types and variables

int edad = 30;
double altura = 1.75;
boolean activo = true;
char inicial = 'A';
String nombre = "Ana";           // objeto, no primitivo

final double PI = 3.1416;         // constante
var lista = new ArrayList<String>();  // inferencia (Java 10+)

Integer.parseInt("42");  String.valueOf(42);
"" + 42;                 // int -> String rápido

String

s.length()          s.charAt(0)        s.substring(1, 4)
s.toUpperCase()     s.trim()           s.isEmpty()
s.equals(otro)      s.equalsIgnoreCase(otro)   // NUNCA ==
s.contains("ab")    s.indexOf("a")     s.replace("a", "b")
s.split(",")        String.join("-", partes)
String.format("%d de %d", i, n)

Control flow

if (edad >= 18) { ... } else if (edad >= 13) { ... } else { ... }

switch (dia) {
    case 6, 7 -> System.out.println("finde");
    default   -> System.out.println("laborable");
}

for (int i = 0; i < n; i++) { ... }
for (String x : lista) { ... }
while (cond) { ... }
do { ... } while (cond);

Arrays and collections

int[] nums = {1, 2, 3};
nums.length;   nums[0];

List<String> lista = new ArrayList<>();
lista.add("a");  lista.get(0);  lista.size();  lista.contains("a");  lista.remove(0);

Map<String, Integer> mapa = new HashMap<>();
mapa.put("a", 1);  mapa.get("a");  mapa.getOrDefault("b", 0);  mapa.containsKey("a");
for (var e : mapa.entrySet()) { e.getKey(); e.getValue(); }

Set<Integer> set = new HashSet<>();   // sin duplicados

Classes

public class Perro {
    private String nombre;

    public Perro(String nombre) { this.nombre = nombre; }

    public String getNombre() { return nombre; }

    @Override
    public String toString() { return "Perro(" + nombre + ")"; }
}

class Cachorro extends Perro {          // herencia
    Cachorro(String n) { super(n); }
}

Exceptions and input

import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String linea = sc.nextLine();

try {
    int x = Integer.parseInt(entrada);
} catch (NumberFormatException e) {
    System.out.println("no es un número");
} finally {
    sc.close();
}

Other cheat sheets

Python · JavaScript · SQL · Git