The snippet library.
Small, practical examples. Search by task or narrow things down below.
Count Unicode code points
Java: Use codePointCount when supplementary characters should count as one rather than two UTF-16 units.
Java✓ Tested
Count word frequencies
Use Map.merge to count repeated words in Java.
Java✓ Tested
Create and clean up a temporary file
Java: Create a unique file and remove it in finally even when the operation fails.
Java✓ Tested
Create nested directories
Create missing parent directories with Java Files.createDirectories.
Java✓ Tested
Decode a form query parameter
Java: URLDecoder reverses form encoding and treats plus as a space.
Java✓ Tested
Define an immutable data record
Java: A local record gives a small Java data carrier named accessors and value semantics.
Java✓ Tested
Delete a known temporary file if present
Java: deleteIfExists returns whether a file was removed and still reports other I/O errors.
Java✓ Tested
Detect integer addition overflow
Java: Math.addExact throws rather than silently wrapping on overflow.
Java✓ Tested
Display an integer as unsigned
Java: Use unsigned conversion methods when interpreting a fixed-width bit pattern.
Java✓ Tested
Divide decimal values with controlled precision
Java: Choose both scale and rounding for a quotient that does not terminate in base ten.
Java✓ Tested
Divide negative integers with floor rounding
Java: floorDiv and floorMod provide consistent floor-based quotient and remainder.
Java✓ Tested
Divide using a fractional number
Java: Use a floating-point operand to preserve the fractional part of a division.
Java✓ Tested