Major Java 8 Features Introduced

Optional Wonders & Date/Time Dynamics: Modern Solutions Unveiled

Learning Outcome

5

Calculate date and time differences using Duration and Period.

4

Use classes like LocalDate, LocalDateTime, and ZonedDateTime.

3

Explain why the java.time API replaced old Date/Calendar.

2

Use Optional methods to handle missing values safely.

1

Understand how Optional prevents NullPointerException.

Null Values in Java
What null means and how NullPointerException occurs.

 

Conditional Statements
if, else — used earlier for null checks and time comparisons.

 

Basic Date Usage
Awareness that Java had Date and Calendar classes before Java 8.

 

Methods & Return Types
Knowing that methods can return values (like String, Date, etc.).

 

Before Starting ,Lets Recall

Before Optional...

Null values were a big problem:

String name = getUserName();   // might return null

System.out.println(name.length()); //NullPointerException

Developers had to write many null checks:

if(name != null) {

    System.out.println(name.length());

}

Optional in Java.

  • Optional is a container class in java.util that may or may not contain a non-null value.
  • It is used to avoid NullPointerException (NPE) and make code more safe, readable, and expressive

Advantages of Using Optional

Makes null handling explicit

Avoids NullPointerException

 Improves code readability

Works smoothly with Lambdas

Optional.empty()--Creates empty Optional

Optional<String> name = Optional.empty();

Creating Optionals in Java

Optional.of()--Used when value is guaranteed not null

Optional<String> name = Optional.of("Java");

Optional.ofNullable()--Used when value may be null

Optional<String> name = Optional.ofNullable(null);

public Optional<String> findUserEmail(int id) {

    if(id == 1) return Optional.of("user@gmail.com");

    return Optional.empty();

}

public static void main(String[] args) {

    Optional<String> email = findUserEmail(2);

    System.out.println(email.orElse("Email not found"));

}

Real-World Example

Date/Time API

Problems with Old API (java.util.Date, java.util.Calendar)

Mutable

Not thread-safe, changes affect all references

Confusing Api

Complex constructors and inconsistent methods

No Time Zones

Poor time zone handling and support

Problem Example

Date date = new Date();
date.setHours(12);

// Affects ALL references!

New Date-Time API in Java 8

Java 8 introduced a new Date and Time API in the java.time package to address the shortcomings of the older java.util.Date and java.util.Calendar classes.

Well-Designed API

Simple, well-structured classes replace confusing Date and Calender

Fluent Method Chaining

Supports readable chained operations

Better Time Zone Handling

Accurate zone management with ZoneId and ZonedDateTime.

Immutable

Objects cannot be modified, making them safe for multi-threaded applications.

Key Classes of java.time package

Class

Purpose

LocalDate

Date without time

LocalTime

Time without date

LocalDateTime

Date and time without timezone

ZonedDateTime

ZoneId

Date, time, and timezone

Time zone info

Duration /Period

Time differences

1. When user places an order:

import java.time.LocalDateTime;

LocalDateTime orderTime = LocalDateTime.now();

System.out.println("Order Placed At: " + orderTime);

2. Delivery Date After 5 Days

import java.time.LocalDate;

LocalDate deliveryDate = LocalDate.now().plusDays(5);

System.out.println("Expected Delivery: " + deliveryDate);

Real Time example:

Store Order Date & Time

 3. Handle Time Zones (User in US, Server in India)

import java.time.ZonedDateTime;

import java.time.ZoneId;

 

ZonedDateTime indiaTime = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

ZonedDateTime usTime = indiaTime.withZoneSameInstant(ZoneId.of("America/New_York"));

 

System.out.println("India Time: " + indiaTime);

System.out.println("US Time: " + usTime);

 4. Offer Expiry Check

import java.time.LocalDate;

 

LocalDate today = LocalDate.now();

LocalDate offerEnd = LocalDate.of(2026, 1, 31);

 

if(today.isAfter(offerEnd)) {

    System.out.println("Offer Expired");

} else {

    System.out.println("Offer Active");

}

 

5. Check Store Working Hours

import java.time.LocalTime;

 

LocalTime now = LocalTime.now();

LocalTime open = LocalTime.of(9, 0);

LocalTime close = LocalTime.of(18, 0);

 

if(now.isAfter(open) && now.isBefore(close)) {

    System.out.println("Store is Open");

} else {

    System.out.println("Store is Closed");

}

 

6. Calculate Delivery Duration

import java.time.Duration;

import java.time.LocalDateTime;

 

LocalDateTime start = LocalDateTime.now();

LocalDateTime end = start.plusHours(36);

 

Duration duration = Duration.between(start, end);

System.out.println("Delivery Time in Hours: " + duration.toHours());

 

 7. Subscription Validity (Period)

import java.time.Period;

import java.time.LocalDate;

 

LocalDate startDate = LocalDate.now();

LocalDate endDate = startDate.plusMonths(6);

 

Period period = Period.between(startDate, endDate);

System.out.println("Subscription Valid for: " + period.getMonths() + " months");

Summary

4

Java 8 introduced the java.time package with immutable and thread-safe classes

3

Old Date/Time API had issues like mutability & poor timezone support.

2

It makes null handling explicit

1

Optional is a container t used to prevent NullPointerException.

Quiz

Which class is used to represent date and time with timezone in Java 8?

A. LocalDate

B. LocalTime

C. LocalDateTime

D. ZonedDateTime

Which class is used to represent date and time with timezone in Java 8?

A. LocalDate

B. LocalTime

C. LocalDateTime

D. ZonedDateTime

Quiz-Answer