Chuleta de Java

Tipos, control de flujo, arrays, colecciones, clases y excepciones en tablas para consultar rápido.

Referencia rápida. Para aprender cada tema a fondo, ve a los ejemplos interactivos de Java.

Tipos y 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 de flujo

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 y colecciones

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

Clases

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); }
}

Excepciones y entrada

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();
}

Otras chuletas

Python · JavaScript · SQL · Git