More Java Ideas

Converting types

double d = 42;             // widening: automatic
int y = (int) 3.99;        // narrowing: cast, truncates → 3
int r = (int) Math.round(3.99);   // 4
int small = (int) bigLong; // may overflow silently

Text ↔ number:

Integer.parseInt("42")
Double.parseDouble("3.14")
Boolean.parseBoolean("true")

String.valueOf(42)
Integer.toString(42)

Integer.parseInt("abc")    // NumberFormatException
Integer.parseInt("ff", 16)   // 255
Integer.toBinaryString(10)   // "1010"
Integer.toHexString(255)     // "ff"
0b1010    0xFF               // literals

Strings, part 2

"a;b;c".split(";")
String.join("|", parts)
"line1\nline2".lines().toList()
"abc".compareTo("abd")       // negative
"Hello".toCharArray()

"%-10s|".formatted("left")      // "left      |"
"%,.2f".formatted(1234567.891)  // "1,234,567.89"
"%08.3f".formatted(3.14159)     // "0003.142"
String.format(Locale.US, "%,.2f", 1999.5);

Enums

A type with a fixed set of values:

enum Status { OPEN, IN_PROGRESS, DONE }

s == Status.OPEN        // == is correct for enums
s.name()                // "OPEN"
Status.valueOf("DONE")
Status.values()

They can carry data and behaviour:

enum Planet {
    EARTH(5.97e24, 6.371e6),
    MARS(6.42e23, 3.390e6);

    private final double mass, radius;

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

    double gravity() { return 6.67e-11 * mass / (radius * radius); }
}

In a switch the compiler checks completeness — no default needed.

Date and time

java.time types are immutable.

var today = LocalDate.now();
var birthday = LocalDate.of(1995, 4, 23);
var now = LocalDateTime.now();
var zoned = ZonedDateTime.now(ZoneId.of("America/New_York"));

today.plusDays(30)
today.minusMonths(2)
today.getDayOfWeek()
today.isBefore(birthday)

Period.between(birthday, today).getYears()
Duration.ofHours(3).plusMinutes(45).toMinutes()   // 225

var fmt = DateTimeFormatter.ofPattern("MM/dd/yyyy");
today.format(fmt)
LocalDate.parse("2026-12-24")     // ISO needs no formatter
Warning

Do not use java.util.Date, Calendar or SimpleDateFormat in new code.

Randomness

var r = RandomGenerator.getDefault();

r.nextInt(1, 7)       // a die
r.nextDouble()
r.nextBoolean()
r.ints(5, 1, 50).sorted().forEach(IO::println);

Collections.shuffle(cards);

Regular expressions

var email = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[a-z]{2,}$");
email.matcher("ann@example.com").matches();

var date = Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})");
var m = date.matcher("due 12/24/2026");
if (m.find()) IO.println(m.group(3) + "-" + m.group(1));

"a1b2".replaceAll("\\d", "#")   // "a#b#"
"a,b;c".split("[,;]")
"Test".matches("[A-Z]\\w+")

Backslashes must be doubled in Java strings: \d"\\d".

Handy helpers

Math.abs  Math.max  Math.min  Math.pow  Math.sqrt
Math.round  Math.floor  Math.ceil  Math.floorDiv

Objects.equals(a, b)      Objects.hash(a, b, c)
Objects.requireNonNull(x) Objects.toString(x, "empty")

List.copyOf(list)         Collections.sort(list)
Collections.reverse(list) Collections.unmodifiableList(list)

★ Exercises

  1. Format an amount as "$1,234.56".
  2. Write enum Weekday with an isWeekend() method.
  3. How many days until your next birthday?
  4. Validate US ZIP codes with a regex.
  5. Roll a die 10,000 times and print the frequency of each face.
  6. Convert "2026-08-12T14:30:00" into "Aug 12, 2026, 2:30 PM".