Skip to main content

8.6 Default & Static Methods, Date/Time API & Other Features

← Back to Chapter 8: Java 8 Features

Beyond Lambdas, Streams, and Optional, Java 8 introduced critical architectural enhancements to interfaces, modern date-time handling, and core utility libraries.


1. Default & Static Methods in Interfaces​

Prior to Java 8, adding a new method to an interface broke every existing implementing class. Default methods allow interfaces to define method implementations while preserving backward compatibility.

Default Methods (default keyword)​

public interface Vehicle {
void drive(); // Abstract method

// Default method with standard fallback logic
default void honk() {
System.out.println("Default honk sound: Beep beep!");
}
}

The Multiple Inheritance Conflict (Diamond Problem):​

If a class implements two interfaces that provide the same default method signature, the compiler forces the class to override and resolve the ambiguity:

interface InterfaceA {
default void log() { System.out.println("Log from A"); }
}

interface InterfaceB {
default void log() { System.out.println("Log from B"); }
}

class Service implements InterfaceA, InterfaceB {
@Override
public void log() {
// Option 1: Provide own implementation
// Option 2: Explicitly delegate using super
InterfaceA.super.log();
}
}

Static Methods in Interfaces:​

Interfaces can now host static utility methods directly:

public interface MathUtility {
static int add(int a, int b) {
return a + b;
}
}
// Invocation: MathUtility.add(5, 10);

2. Modern Date and Time API (java.time / JSR-310)​

Legacy java.util.Date and Calendar had critical design flaws: they were mutable, not thread-safe, months were zero-indexed (0 = January), and timezone handling was brittle.

Java 8 introduced an immutable, thread-safe, domain-driven date-time library in java.time:

ClassRepresentsExample Output
LocalDateDate only (year, month, day)2026-09-09
LocalTimeTime only (hour, minute, second, nanos)14:30:15
LocalDateTimeCombined date and time without timezone2026-09-09T14:30:15
ZonedDateTimeDate and time with explicit timezone2026-09-09T14:30:15+05:30[Asia/Kolkata]
InstantMachine timestamp (seconds from epoch)2026-09-09T09:00:15Z
DurationTime-based amount (seconds, nanos)PT2H30M (2 hours 30 mins)
PeriodDate-based amount (years, months, days)P1Y2M3D (1 year, 2 months, 3 days)

Practical Usage:​

// Current date
LocalDate today = LocalDate.now();
LocalDate birthDate = LocalDate.of(1998, Month.AUGUST, 15);

// Fluent modifications (returns a new instance, immutable)
LocalDate nextWeek = today.plusDays(7);

// Parsing & Formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formatted = today.format(formatter);
LocalDate parsed = LocalDate.parse("15-08-1998", formatter);

3. Native Base64 Encoding & Decoding (java.util.Base64)​

Before Java 8, developers relied on third-party libraries (like Apache Commons Codec) or unstandardized internal APIs (sun.misc.BASE64Encoder). Java 8 added an optimized standard implementation:

String original = "CodeWithSarvy";

// Encode to Base64
String encoded = Base64.getEncoder().encodeToString(original.getBytes(StandardCharsets.UTF_8));
System.out.println(encoded); // Q29kZVdpdGhTYXJ2eQ==

// Decode from Base64
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println(decoded); // CodeWithSarvy

Variants supported:

  • Basic: RFC 4648 standard base64.
  • URL: URL-safe and filename-safe encoder (- and _ instead of + and /).
  • MIME: Generates MIME-friendly output limited to 76 characters per line.

4. Other Notable Java 8 Enhancements​

String.join()​

Easily join elements with a delimiter:

String csv = String.join(", ", "Apple", "Banana", "Cherry"); // "Apple, Banana, Cherry"

Repeating Annotations (@Repeatable)​

Allows applying the same annotation multiple times to a declaration without an explicit container annotation wrapper.

Concurrency Upgrades:​

  • CompletableFuture<T>: Asynchronous, non-blocking pipeline programming with callbacks (thenApply(), thenAccept(), allOf()).
  • LongAdder & LongAccumulator: High-throughput atomic counter alternatives to AtomicLong designed to reduce cache contention under high concurrency.