Ir para o conteúdo

Lição 195 · Practice and Review

Cheat sheet de Java

Um cheat sheet de uma página do Java 25 com sintaxe, tipos, strings, controle de fluxo, POO, records, exceções, coleções, lambdas, streams, datas, arquivos e threads.

Esta página condensa todo o curso de Java em uma única referência rolável: a sintaxe, os tipos e as APIs que você usa todos os dias, em trechos compactos que dá para escanear em segundos. Deixe-a aberta enquanto trabalha nos exercícios práticos, enquanto escreve seus próprios programas ou na véspera de uma entrevista.

Cada seção aponta para a lição que explica o assunto direito, com o raciocínio e as armadilhas para os quais um cheat sheet não tem espaço. As poucas regras que mais surpreendem as pessoas vêm com editores ao vivo, para que você possa executá-las e ver o comportamento com os próprios olhos. Tudo aqui é Java 25 moderno; os recursos adicionados em versões recentes indicam a versão que os introduziu.

Estrutura do programa

Duas formas de escrever um programa

Java
// Compact source file (Java 25): no class needed
void main() {
    IO.println("Hello, Java!");
}
Java
// Classic form: what most existing code and frameworks use
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Arquivos compactos importam automaticamente todo o java.base (List, Map, Path, ...). Arquivos clássicos precisam de imports para qualquer coisa fora de java.lang. Veja Primeiros passos, Sintaxe e O método main.

Compilar e executar

Terminal
java Main.java               # run a single source file directly (no javac step)
javac Main.java              # compile to Main.class (bytecode)
java Main                    # run the compiled class on the JVM
java -version                # which JDK is on the PATH
javac -d out src/app/*.java  # compile into an output folder

Veja Como o Java funciona e Ferramentas de build.

Comentários e nomenclatura

Java
// line comment
/* block comment */
/** Javadoc: @param, @return, @throws */
/// Markdown doc comment (Java 23+)

class OrderService {}             // classes, records, enums: PascalCase
int itemCount;                    // variables and methods: camelCase
static final int MAX_RETRIES = 3; // constants: UPPER_SNAKE_CASE
package com.example.shop;         // packages: lowercase, reversed domain

Veja Comentários e Javadoc e Palavras-chave e identificadores.

Saída e entrada

Imprimindo

Java
System.out.println("line");      // print + newline
System.out.print("no newline");
IO.println("Java 25 shortcut");  // also IO.print(...)
System.err.println("error stream");
System.out.printf("%s is %d%n", "Ada", 36);   // formatted (IO has no printf)
String s = "%.2f".formatted(3.14159);           // "3.14"
String t = String.format("%05d", 42);           // "00042"
Especificador Significado Exemplo → saída
%d inteiro %d, 42 → 42
%,d milhares agrupados %,d, 1234567 → 1,234,567
%05d largura 5 preenchida com zeros 42 → 00042
%.2f 2 casas decimais (arredonda) 3.14159 → 3.14
%8.2f largura 8, alinhado à direita 3.5 → 3.50
%s / %-10s string / alinhada à esquerda em 10 "ab" → ab
%x / %X hexadecimal 255 → ff / FF
%e científico 12345.0 → 1.234500e+04
%b %c %% %n boolean, char, um % literal, nova linha

Veja Imprimindo saída e Formatando strings.

Lendo entrada

Java
Scanner in = new Scanner(System.in);
String line = in.nextLine();     // whole line
int n = in.nextInt();            // one token; leaves the newline behind!
while (in.hasNextInt()) { ... }  // read until input runs out

String name = IO.readln("Name: ");          // Java 25: prompt + read a line
int age = Integer.parseInt(IO.readln());

var reader = new BufferedReader(new InputStreamReader(System.in));
String first = reader.readLine();           // null at end of input

A armadilha clássica: nextInt() seguido de nextLine() retorna uma string vazia, porque nextInt() para antes da quebra de linha. Execute para ver, e depois a correção:

Java A armadilha de nextInt mais nextLine

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A correção mais simples em geral: leia linhas inteiras e converta com Integer.parseInt(line.trim()). Veja Lendo a entrada do usuário.

Variáveis e tipos

Tipos primitivos

Tipo Tamanho Intervalo / valores Padrão (campos) Literal
byte 8 bits -128 a 127 0 (byte) 10
short 16 bits -32.768 a 32.767 0 (short) 10
int 32 bits cerca de ±2,1 bilhões 0 42, 1_000_000, 0xFF, 0b1010, 017
long 64 bits cerca de ±9,2 × 10¹⁸ 0L 42L
float 32 bits cerca de 7 dígitos significativos 0.0f 3.14f
double 64 bits cerca de 15–16 dígitos significativos 0.0 3.14, 1e-3
char 16 bits uma unidade de código UTF-16 '\u0000' 'A', '\n'
boolean – true, false false true

Todo o resto é um tipo de referência (String, arrays, objetos), cujos campos têm null como padrão. Variáveis locais não têm valor padrão: precisam ser atribuídas antes do uso. Veja Tipos de dados primitivos e Variáveis.

Declarações, var e final

Java
int count = 0;
double price = 9.99, tax = 0.2;
var names = new ArrayList<String>();   // type inferred: ArrayList<String>
final int limit = 10;                  // can't be reassigned
static final double VAT = 0.21;        // a constant (inside a class)

var funciona apenas para variáveis locais com inicializador (não para campos, parâmetros nem var x = null;). Veja var e Constantes e final.

Conversões

Java
long big = 42;                    // widening: automatic
int whole = (int) 3.99;           // narrowing: 3 (truncates toward zero)
byte wrapped = (byte) 200;        // -56 (keeps the low 8 bits)
int n = Integer.parseInt("123");  // NumberFormatException on "12a"
double d = Double.parseDouble("2.5");
String s = String.valueOf(42);    // or "" + 42, or Integer.toString(42)
int code = 'A';                   // 65
char next = (char) ('A' + 1);     // 'B'

Veja Conversão e casting de tipos e Classes wrapper.

Operadores

Java
7 / 2          // 3      int division truncates
-7 / 2         // -3     toward zero
7 % 3          // 1
-7 % 3         // -1     sign follows the left operand
Math.floorMod(-7, 3)   // 2
7 / 2.0        // 3.5    one double makes it double division
1 + 2 + "3"    // "33"   left to right: 3, then "33"
"1" + 2 + 3    // "123"

x += 5;  x -= 1;  x *= 2;  x /= 3;  x %= 4;
i++  // use, then add 1      ++i  // add 1, then use

a == b, a != b, a < b, a >= b
a && b, a || b, !a     // short-circuit: b may not be evaluated
a & b, a | b, a ^ b    // on booleans: always evaluate both
int max = a > b ? a : b;           // ternary
obj instanceof String str          // type test + pattern variable

5 & 3 /* 1 */, 5 | 3 /* 7 */, 5 ^ 3 /* 6 */, ~5 /* -6 */
1 << 4 /* 16 */, -16 >> 2 /* -4 */, -16 >>> 28 /* 15 */

Precedência, da mais alta para a mais baixa: pós-fixo x++ → unários ++x -x ! ~ (cast) → * / % → + - → deslocamentos → < > <= >= instanceof → == != → & → ^ → | → && → || → ?: → atribuição. Na dúvida, use parênteses. Veja Operadores aritméticos, Operadores de comparação e lógicos, Operadores bit a bit e de deslocamento e Precedência de operadores.

Surpresas numéricas

Java Surpresas numéricas em uma execução

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

O overflow de int e long dá a volta sem aviso; Math.addExact, multiplyExact e similares lançam exceção. Use BigDecimal para dinheiro. Veja Trabalhando com números, Operadores de atribuição e BigInteger e BigDecimal.

A classe Math

Java
Math.abs(-5)  Math.max(a, b)  Math.min(a, b)
Math.pow(2, 10)        // 1024.0 (a double)
Math.sqrt(16)  Math.cbrt(27)  Math.hypot(3, 4)   // 4.0 3.0 5.0
Math.round(2.4)        // 2 (a long for double arguments)
Math.floor(2.7)  Math.ceil(2.1)                  // 2.0 3.0
Math.floorDiv(-7, 2)   // -4
Math.clamp(150, 0, 100)                          // 100 (Java 21)
Math.random()          // 0.0 <= x < 1.0
RandomGenerator.getDefault().nextInt(1, 7)       // 1..6 (dice)

Veja A classe Math e Números aleatórios.

Strings

Métodos de String do dia a dia

Java
String s = "Hello, World";
s.length()                 // 12
s.charAt(0)                // 'H'
s.substring(7)             // "World"
s.substring(0, 5)          // "Hello" (end index excluded)
s.indexOf("o")             // 4      lastIndexOf("o") → 8, -1 if missing
s.contains("World")        // true
s.startsWith("He")  s.endsWith("!")
s.toUpperCase()  s.toLowerCase()
"  hi  ".strip()           // "hi"   (Unicode-aware; trim() is ASCII-only)
"".isEmpty()  "  ".isBlank()        // true true
s.replace('l', 'L')        // "HeLLo, WorLd"
"a1b22".replaceAll("\\d+", "#")      // "a#b#" (regex)
"a,b,,c,".split(",")       // [a, b, , c] (trailing empties dropped)
String.join("-", "a", "b") // "a-b"
"ab".repeat(3)             // "ababab"
"line1\nline2".lines()     // Stream<String>
s.toCharArray()            // char[]
s.chars()                  // IntStream of chars
s.equals(other)  s.equalsIgnoreCase(other)
s.compareTo("Help")        // negative: "Hello" sorts first

As strings são imutáveis: todo método retorna uma nova string, então escreva s = s.trim();. Veja Strings, Métodos de String e Comparando e convertendo strings.

== versus equals

Java Comparando strings e wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

== compara referências; equals compara conteúdos. Qualquer "true" que você obtenha de == em strings ou números encaixotados é sorte (pool ou cache), nunca algo em que se possa confiar.

StringBuilder e blocos de texto

Java
var sb = new StringBuilder();
sb.append("Hi").append(' ').append(42);   // "Hi 42"
sb.insert(0, ">> ");  sb.reverse();  sb.setLength(0);
String csv = String.join(",", list);      // or Collectors.joining(",")

String json = """
    {
      "name": "Ada",
      "age": 36
    }
    """;   // indentation relative to the closing """ is removed

Use StringBuilder ao montar strings em laços. Veja StringBuilder, StringBuffer, StringJoiner e StringTokenizer e Blocos de texto.

Controle de fluxo

if e switch

Java
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else {
    grade = 'C';
}

String type = switch (day) {              // switch expression
    case SATURDAY, SUNDAY -> "weekend";
    case MONDAY -> {
        log("start");
        yield "weekday";                  // yield returns from a block
    }
    default -> "weekday";
};

switch (command) {                        // classic statement: needs break
    case "start":
        start();
        break;
    case "stop":
    case "halt":                          // fall-through groups labels
        stop();
        break;
    default:
        help();
}

O switch funciona com tipos semelhantes a int, char, String, enums e (com padrões) qualquer tipo. Veja if, else if e else e switch.

Laços

Java
for (int i = 0; i < 10; i++) { ... }
for (String name : names) { ... }          // arrays and any Iterable
while (condition) { ... }
do { ... } while (condition);              // body runs at least once

outer:
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        if (grid[r][c] == target) break outer;   // leaves both loops
        if (grid[r][c] < 0) continue;            // next c
    }
}

Veja while e do-while, Laços for e break, continue e rótulos.

Arrays

Java
int[] nums = new int[5];                   // [0, 0, 0, 0, 0]
int[] primes = {2, 3, 5, 7};
String[] names = new String[3];            // [null, null, null]
nums.length                                // a field, not a method
int[][] grid = new int[3][4];              // 3 rows, 4 columns
int[][] jagged = {{1}, {2, 3}, {4, 5, 6}};

Arrays.toString(primes)                    // "[2, 3, 5, 7]"
Arrays.deepToString(grid)                  // nested arrays
Arrays.sort(nums);                         // ascending
Arrays.sort(words, Comparator.reverseOrder());   // objects only
Arrays.binarySearch(primes, 5)             // 2 (array must be sorted)
Arrays.fill(nums, -1);
int[] copy = Arrays.copyOf(nums, 10);      // pads with 0
int[] part = Arrays.copyOfRange(nums, 1, 3);
Arrays.equals(a, b)                        // contents; a.equals(b) is identity
List<String> view = Arrays.asList(names);  // fixed size: add() throws
int sum = Arrays.stream(primes).sum();     // 17

Os índices vão de 0 a length - 1; qualquer outro lança ArrayIndexOutOfBoundsException. Veja Arrays, Percorrendo arrays, Arrays multidimensionais e A classe Arrays.

Métodos

Java
static int add(int a, int b) {             // static: call as add(1, 2)
    return a + b;
}
static double add(double a, double b) { ... }  // overload: different parameters
static int sum(int... values) { ... }      // varargs: sum(), sum(1, 2, 3)
record MinMax(int min, int max) {}         // return several values
static MinMax range(int[] a) { ... }

long factorial(int n) {                    // recursion needs a base case
    return n <= 1 ? 1 : n * factorial(n - 1);
}

Java é sempre passagem por valor: um método recebe uma cópia de um primitivo, ou uma cópia de uma referência (então pode alterar o objeto, mas não qual objeto a variável do chamador aponta). Veja Métodos, Parâmetros e valores de retorno, Sobrecarga de métodos, Recursão, Varargs e Escopo de variáveis.

Classes e objetos

Uma classe completa

Java
public class Account {
    private static int created = 0;        // shared by all accounts
    private final String owner;            // set once
    private double balance;

    public Account(String owner) {
        this(owner, 0);                    // call another constructor
    }

    public Account(String owner, double balance) {
        if (balance < 0) throw new IllegalArgumentException("negative balance");
        this.owner = owner;                // this. disambiguates the field
        this.balance = balance;
        created++;
    }

    public double getBalance() { return balance; }
    public void deposit(double amount) { balance += amount; }
    public static int created() { return created; }

    @Override
    public String toString() { return owner + ": " + balance; }
}

Account acc = new Account("Ada", 100);
acc.deposit(50);

Veja Classes e objetos, Construtores, A palavra-chave this, Encapsulamento e Membros estáticos.

Modificadores de acesso

Modificador Mesma classe Mesmo pacote Subclasse (outro pacote) Em qualquer lugar
public sim sim sim sim
protected sim sim sim não
(nenhum) package-private sim sim não não
private sim não não não

Veja Modificadores de acesso.

Herança, classes abstratas e interfaces

Java
abstract class Shape {
    abstract double area();                       // no body: subclasses must implement
    String describe() { return "Area " + area(); }
}

class Circle extends Shape {                      // one superclass only
    private final double r;
    Circle(double r) { super(); this.r = r; }     // super(...) calls the parent constructor
    @Override double area() { return Math.PI * r * r; }
}

interface Drawable {
    void draw();                                  // implicitly public abstract
    default void drawTwice() { draw(); draw(); }  // default method
    static Drawable noop() { return () -> {}; }
}

class Square extends Shape implements Drawable, Comparable<Square> { ... }

Shape s = new Circle(2);                          // upcast: always allowed
if (s instanceof Circle c) { ... }                // safe downcast with a pattern

Veja Herança, super, Polimorfismo, Classes abstratas, Interfaces e Composição.

Records, enums e classes aninhadas

Java
record Point(int x, int y) {                      // final fields, accessors x() and y(),
    Point {                                       // equals/hashCode/toString for free
        if (x < 0) throw new IllegalArgumentException("x < 0");  // compact constructor
    }
    Point withX(int nx) { return new Point(nx, y); }
}

enum Planet {
    MERCURY(3.303e23), EARTH(5.976e24);
    private final double mass;
    Planet(double mass) { this.mass = mass; }
    double mass() { return mass; }
}
Planet.values()  Planet.valueOf("EARTH")  Planet.EARTH.ordinal()  // 1

class Outer {
    static class Nested {}        // no link to an Outer instance
    class Inner {}                // needs one: outer.new Inner()
}
Runnable r = new Runnable() {     // anonymous class
    public void run() { IO.println("run"); }
};

Veja Records, Enums, Classes aninhadas e Classes imutáveis.

Tipos selados e pattern matching

Java Interface selada, records e um switch com padrões

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Como Shape é selada, o compilador conhece todos os subtipos, então um switch que os cobre todos não precisa de default, e adicionar um novo subtipo transforma todo switch incompleto em um erro de compilação. Veja Classes seladas e Pattern matching.

equals, hashCode e toString

Java
@Override
public boolean equals(Object o) {
    return o instanceof Isbn other && code.equals(other.code);
}
@Override
public int hashCode() { return Objects.hash(code); }   // equal objects → equal hashes
@Override
public String toString() { return "Isbn[" + code + "]"; }

Objects.equals(a, b)                     // null-safe
Objects.requireNonNull(name, "name")     // fail fast

Sobrescreva equals e hashCode juntos, ou as coleções baseadas em hash quebram. Veja A classe Object e Copiando objetos.

Exceções

Java
try {
    int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
    IO.println("Not a number: " + e.getMessage());
} catch (IllegalStateException | ArithmeticException e) {   // multi-catch
    throw new AppException("calculation failed", e);           // keep the cause
} finally {
    IO.println("always runs");
}

try (var reader = Files.newBufferedReader(path)) {   // closed automatically,
    return reader.readLine();                        // in reverse order
}

void load(Path p) throws IOException { ... }         // checked: declare or catch

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String message) { super(message); }
}
Tipo Estende Precisa ser capturada ou declarada? Exemplos
Checked (verificada) Exception sim IOException, SQLException, InterruptedException
Unchecked (não verificada) RuntimeException não NullPointerException, IllegalArgumentException, IndexOutOfBoundsException
Error Error não (não capture) OutOfMemoryError, StackOverflowError

Veja Exceções, Lançando exceções, Exceções personalizadas, try-with-resources, Boas práticas e Depuração.

Coleções

Qual usar?

Necessidade Use Observações
Lista ordenada, acesso por índice ArrayList a lista padrão
Itens únicos, busca rápida HashSet sem ordem
Itens únicos, ordem de inserção LinkedHashSet
Itens únicos, ordenados TreeSet first, floor, ceiling
Chave → valor HashMap uma chave null permitida
Chave → valor, ordem de inserção/acesso LinkedHashMap caches LRU
Chave → valor, chaves ordenadas TreeMap headMap, floorKey
Pilha ou fila ArrayDeque não Stack/LinkedList
Sempre pegar o menor/maior PriorityQueue um heap binário
Compartilhada entre threads ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
Operação ArrayList LinkedList HashMap/HashSet TreeMap/TreeSet
obter por índice / chave O(1) O(n) O(1) em média O(log n)
adicionar no fim / put O(1) amortizado O(1) O(1) em média O(log n)
inserir/remover no meio O(n) O(n) para achar, O(1) para desligar – –
contains O(n) O(n) O(1) em média O(log n)

Veja O framework de coleções e Escolhendo a coleção certa.

Listas, conjuntos e mapas na prática

Java
List<String> list = new ArrayList<>();
list.add("b");  list.add(0, "a");  list.get(0);  list.set(0, "z");
list.remove("z");  list.remove(0);  list.size();  list.contains("b");
list.removeIf(s -> s.isBlank());
list.sort(Comparator.naturalOrder());
list.getFirst();  list.getLast();  list.reversed();     // Java 21

Set<Integer> set = new HashSet<>(List.of(3, 1, 2));
set.add(1);                     // false: already there
set.retainAll(other);           // intersection (addAll = union, removeAll = difference)

Map<String, Integer> map = new HashMap<>();
map.put("apples", 3);
map.get("pears")                       // null when missing
map.getOrDefault("pears", 0)           // 0
map.putIfAbsent("pears", 1);
map.merge(word, 1, Integer::sum);      // counting in one line
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);   // grouping
for (Map.Entry<String, Integer> e : map.entrySet()) { e.getKey(); e.getValue(); }
map.forEach((k, v) -> IO.println(k + "=" + v));

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);  stack.pop();  stack.peek();
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1);  queue.poll();  queue.peek();         // null when empty
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));

List.of(1, 2, 3)  Set.of("a")  Map.of("k", 1)        // immutable, no nulls
List.copyOf(list)                                     // immutable copy
Collections.unmodifiableList(list)                    // read-only view
Collections.frequency(list, "b")  Collections.max(list)  Collections.shuffle(list)

Modificar uma coleção enquanto você a percorre com for-each lança ConcurrentModificationException; use removeIf ou o remove() de um Iterator. Veja ArrayList, HashMap, HashSet, TreeMap e TreeSet, Filas e deques, Iteradores e Coleções imutáveis.

Ordenação

Java
record Person(String name, int age) {}
people.sort(Comparator.comparing(Person::name));
people.sort(Comparator.comparingInt(Person::age).reversed());
people.sort(Comparator.comparing(Person::age).thenComparing(Person::name));
names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));

class Version implements Comparable<Version> {
    public int compareTo(Version o) { return Integer.compare(major, o.major); }
}

Nunca escreva return a - b; em um comparador: ele sofre overflow com valores grandes. Use Integer.compare. Veja Comparable e Comparator.

Generics e programação funcional

Generics

Java
class Box<T> {
    private final T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
}
Box<String> box = new Box<>("hi");                     // diamond <>

static <T extends Comparable<T>> T max(List<T> items) { ... }   // bounded type
double sum(List<? extends Number> nums) { ... }        // read from a producer
void fill(List<? super Integer> out) { ... }           // write to a consumer

PECS: Producer extends, Consumer super. Os generics são apagados em tempo de execução: nada de new T(), nada de List<int> (use List<Integer>), nada de instanceof List<String>. Veja Generics, Tipos limitados e curingas e Type erasure.

Lambdas, interfaces funcionais e referências a métodos

Interface Método Forma Exemplo
Function<T, R> apply T → R s -> s.length()
BiFunction<T, U, R> apply (T, U) → R (a, b) -> a + b
Predicate<T> test T → boolean n -> n > 0
Consumer<T> accept T → void IO::println
Supplier<T> get () → T ArrayList::new
UnaryOperator<T> apply T → T String::trim
BinaryOperator<T> apply (T, T) → T Integer::sum
Runnable / Callable<V> run / call () → void / V tarefas para threads
Java
Function<Integer, Integer> twice = x -> x * 2;
Function<Integer, Integer> plusOne = x -> x + 1;
twice.andThen(plusOne).apply(5)     // 11
twice.compose(plusOne).apply(5)     // 12
Predicate<String> empty = String::isEmpty;
empty.negate().and(s -> s.length() < 5)

String::toUpperCase     // instance method of an arbitrary object: s -> s.toUpperCase()
System.out::println     // instance method of a particular object
Integer::parseInt       // static method
ArrayList::new          // constructor

Lambdas só podem usar variáveis locais se forem efetivamente finais. Veja Lambdas, Interfaces funcionais, Referências a métodos e Programação funcional.

Streams

Java
List<String> result = names.stream()
    .filter(n -> n.length() > 3)          // intermediate: lazy
    .map(String::toUpperCase)
    .sorted()
    .distinct()
    .limit(10)
    .toList();                            // terminal: runs the pipeline (Java 16)

IntStream.range(0, 5)                     // 0..4  (rangeClosed(1, 5) → 1..5)
Stream.of("a", "b")  Arrays.stream(array)  list.stream()
stream.count()  .anyMatch(p)  .allMatch(p)  .noneMatch(p)
stream.findFirst()                        // Optional
stream.reduce(0, Integer::sum)
ints.mapToInt(Integer::intValue).sum()    // also average(), max(), summaryStatistics()
lists.stream().flatMap(List::stream)      // flatten
Java
Collectors.joining(", ", "[", "]")
Collectors.groupingBy(Person::city)                         // Map<City, List<Person>>
Collectors.groupingBy(Person::city, Collectors.counting())  // Map<City, Long>
Collectors.partitioningBy(p -> p.age() >= 18)               // Map<Boolean, List<...>>
Collectors.toMap(Person::name, Person::age, (a, b) -> a)    // merge on duplicate keys
Collectors.averagingInt(Person::age)
Java Um pipeline de stream com collectors

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Um stream só pode ser usado uma vez, e não faz nada até que uma operação terminal seja executada. Veja Streams, Coletando resultados de streams e Streams avançados.

Optional

Java
Optional<User> found = repo.findById(id);
found.map(User::email).orElse("none");
found.orElseGet(() -> loadDefault());     // lazy fallback
found.orElseThrow();                      // NoSuchElementException if empty
found.ifPresentOrElse(u -> greet(u), () -> IO.println("not found"));
Optional.ofNullable(maybeNull)            // Optional.of(null) throws

Use Optional como tipo de retorno para "talvez nenhum resultado", não para campos ou parâmetros. Veja Optional.

Trabalhando com dados

Datas e horas (java.time)

Java
LocalDate today = LocalDate.now();
LocalDate due = LocalDate.of(2026, 3, 15).plusWeeks(2);
LocalDateTime meeting = LocalDateTime.of(2026, 5, 1, 9, 30);
ZonedDateTime tokyo = meeting.atZone(ZoneId.of("Asia/Tokyo"));
Instant now = Instant.now();                         // a point on the UTC timeline
Duration d = Duration.ofMinutes(90);                 // time-based: 1h30m
Period p = Period.between(birthday, today);          // date-based: years/months/days
long days = ChronoUnit.DAYS.between(start, end);
var fmt = DateTimeFormatter.ofPattern("dd.MM.yyyy");
fmt.format(today);  LocalDate.parse("01.02.2026", fmt);
today.with(TemporalAdjusters.lastDayOfMonth());
today.getDayOfWeek()                                 // e.g. MONDAY

Todos os tipos de java.time são imutáveis: plusDays retorna um novo valor. Evite as legadas Date e Calendar. Veja Datas e horas.

Regex, números grandes, UUIDs

Java
Pattern p = Pattern.compile("(?<year>\\d{4})-(\\d{2})");   // compile once, reuse
Matcher m = p.matcher("Due 2026-03");
if (m.find()) { m.group("year"); m.group(2); }              // "2026", "03"
"2026-03".matches("\\d{4}-\\d{2}")                          // whole string must match

new BigDecimal("0.10").add(new BigDecimal("0.20"))          // 0.30 exactly
amount.setScale(2, RoundingMode.HALF_EVEN)
a.compareTo(b) == 0                    // equals() also compares the scale: 2.0 ≠ 2.00
BigInteger.TWO.pow(100)

UUID.randomUUID()
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
Base64.getEncoder().encodeToString(bytes)

Veja Expressões regulares, BigInteger e BigDecimal, UUIDs, hashing e Base64 e Internacionalização.

Arquivos

Java
Path path = Path.of("data", "notes.txt");
Files.createDirectories(path.getParent());
Files.writeString(path, "first line\n");
Files.writeString(path, "more\n", StandardOpenOption.APPEND);
String text = Files.readString(path);
List<String> lines = Files.readAllLines(path);
try (Stream<String> stream = Files.lines(path)) { ... }   // large files: close it!
Files.exists(path)  Files.size(path)  Files.delete(path)
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
try (Stream<Path> all = Files.walk(Path.of("."))) { ... }

As APIs de Files usam UTF-8 por padrão. Veja Lendo e escrevendo arquivos, Streams de bytes e de caracteres, Trabalhando com diretórios, Serialização, Conjuntos de caracteres e Arquivos de propriedades.

Concorrência

Java
Thread t = new Thread(() -> work());
t.start();                    // run() would execute on the current thread
t.join();                     // wait for it to finish

synchronized (lock) { count++; }          // one thread at a time
private volatile boolean running = true;  // visibility only, not atomicity
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(key, 1, Integer::sum);       // atomic

try (ExecutorService pool = Executors.newFixedThreadPool(4)) {   // close() waits (Java 19+)
    Future<Integer> f = pool.submit(() -> compute());
    int value = f.get();
}

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {  // Java 21
    for (int i = 0; i < 10_000; i++) executor.submit(() -> blockingCall());
}

CompletableFuture.supplyAsync(() -> fetch())
    .thenApply(String::length)
    .exceptionally(ex -> -1)
    .join();

Veja Threads, Sincronização, Locks, Variáveis atômicas, Executors, CompletableFuture, Coleções concorrentes e Threads virtuais.

Destaques das versões

Versão Recursos de destaque
8 (2014) lambdas, streams, Optional, java.time, métodos default
9–11 módulos, List.of, var (10), HttpClient, String.strip/isBlank/repeat (11, LTS)
14–17 expressões switch (14), blocos de texto (15), records (16), classes seladas (17, LTS)
21 (LTS) threads virtuais, pattern matching para switch, padrões de record, coleções sequenciadas
22–24 variáveis sem nome _ (22), comentários de documentação em Markdown (23), stream gatherers (24)
25 (LTS) arquivos-fonte compactos e main de instância, classe IO, imports de módulo, corpos de construtor flexíveis, scoped values

Veja Versões e história do Java, Boas práticas e, para bancos de dados, aplicações web e Spring, o curso Advanced Java.

Verifique seu entendimento

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. O que IO.println(1 + 2 + "3" + 4 + 5); imprime?

    A avaliação vai da esquerda para a direita. 1 + 2 é o int 3; somar "3" dá a string "33"; a partir daí todo + é concatenação de strings, então o resultado é "3345".
  2. 2. Qual coleção mantém as chaves ordenadas e consegue responder "a maior chave menor que 50"?

    TreeMap é um NavigableMap apoiado em uma árvore rubro-negra, então lowerKey(50) ou floorKey(50) respondem isso em O(log n). HashMap não tem ordem, e LinkedHashMap só lembra a ordem de inserção ou de acesso.
  3. 3. int n = in.nextInt(); String s = in.nextLine(); com a entrada 5 e depois Ada na linha seguinte. Quanto vale s?

    nextInt() lê o token 5 e para antes da quebra de linha, então nextLine() retorna o resto dessa linha, que é vazio. Chame um nextLine() extra ou leia linhas inteiras e converta-as.
  4. 4. Por que Comparator<Integer> c = (a, b) -> a - b; é um comparador ruim?

    Por exemplo, Integer.MIN_VALUE - 1 sofre overflow e vira um número positivo grande. Integer.compare(a, b) ou Comparator.naturalOrder() sempre acerta o sinal.

Resumo

  • Um programa Java 25 pode ser um arquivo compacto com void main() ou um clássico public class Main com public static void main(String[] args); imprima com IO.println ou System.out.println e formate com printf/formatted.
  • Conheça os oito primitivos, a divisão inteira e o overflow, o cast implícito na atribuição composta e por que == em strings e números encaixotados é um bug.
  • Expressões switch, records, enums, tipos selados e pattern matching tornam o código Java moderno curto e seguro; sobrescreva equals e hashCode juntos.
  • Escolha coleções pela necessidade: ArrayList, HashMap, HashSet por padrão; Tree* para ordenação, LinkedHash* para ordem, ArrayDeque para pilhas e filas.
  • Lambdas, referências a métodos, streams e Optional cobrem a maior parte do processamento de dados; java.time, Files e java.util.concurrent cobrem datas, arquivos e threads.

A seguir: Programas Java: 40 exemplos clássicos, onde você vai praticar esses blocos de construção em programas curtos e executáveis.

Acompanhe seu progresso

Crie uma conta gratuita para marcar lições como concluídas e retomar de onde parou em qualquer dispositivo.