I'm always excited to take on new projects and collaborate with innovative minds.

Email

contact@niteshsynergy.com

Website

https://www.niteshsynergy.com/

Java 8 Features - Optional Classes & LocalDateTime

Key Features of Optional in Java:
Avoiding Null Checks: Optional helps avoid explicit null checks. Instead of checking if (object == null), you can use Optional to wrap a potentially null value, making it easier to handle the absence of a value without needing to explicitly check for null.

Key Features of Optional in Java:

  1. Avoiding Null Checks: Optional helps avoid explicit null checks. Instead of checking if (object == null), you can use Optional to wrap a potentially null value, making it easier to handle the absence of a value without needing to explicitly check for null.

Optional<String> name = Optional.ofNullable(someValue);
name.ifPresent(value -> System.out.println(value));  // Will only print if value is non-null
 

Fluent API: Optional provides a fluent API with methods like:

  • map(): Transforms the value inside Optional if present.
  • flatMap(): Similar to map(), but the result is another Optional.
  • filter(): Filters the value inside Optional based on a predicate.
  • ifPresent(): Executes a block of code if the value is present.
  • orElse(), orElseGet(): Returns a default value if no value is present.

Example using map():

 

Optional<String> name = Optional.ofNullable("Nitesh");
Optional<String> upperCaseName = name.map(String::toUpperCase);
upperCaseName.ifPresent(System.out::println);  // Outputs "NITESH"
 

 

Preventing NullPointerException: One of the most important benefits of Optional is that it helps prevent NullPointerException. By forcing the developer to handle the potential absence of a value, Optional avoids situations where methods or operations are called on null objects.

Example using orElse() to provide a default value:

 

Optional<String> name = Optional.ofNullable(null);
String result = name.orElse("Default Name");  // Avoids NPE, returns "Default Name"
 

 

Chaining Operations: You can chain multiple operations with Optional, which makes the code more readable and avoids nested null checks.

 

Optional<String> name = Optional.ofNullable("Nitesh");
Optional<String> result = name.filter(s -> s.startsWith("N"))
                             .map(String::toUpperCase);
result.ifPresent(System.out::println);  // Outputs "NITESH"
 

 

Handling Absence: With methods like ifPresentOrElse(), Optional allows handling both the presence and absence of values in a cleaner way.

 

Optional<String> name = Optional.ofNullable("Nitesh");
name.ifPresentOrElse(
   value -> System.out.println("Name is: " + value),
   () -> System.out.println("No name provided")
);
 

 

Key Features: Avoiding Null Checks: With Optional, you don’t need to check if an object is null explicitly. It provides methods to handle the absence of values gracefully. Fluent API: Optional provides various methods like map(), flatMap(), filter(), ifPresent(), and others to deal with the potential absence of values. Preventing NullPointerException: It helps avoid NullPointerException by forcing developers to explicitly handle the absence of values.

 

package com.niteshsynergy.java8;

import com.niteshsynergy.Emp;

import java.util.Optional;

public class OptionalClasses {
   public static void main(String[] args) {
       // Creating employee instances with names
       Emp emp1 = new Emp(1, "Alice", 75000);
       Emp emp2 = new Emp(2, null, 55000);  // emp2 has a null name

       // Example of Optional.ofNullable() to safely wrap potentially null values
       Optional<String> nameOpt1 = Optional.ofNullable(emp1.getName()); // emp1 has a valid name
       Optional<String> nameOpt2 = Optional.ofNullable(emp2.getName()); // emp2 has a null name

       // Using ifPresent() to execute logic if the value is present
       nameOpt1.ifPresent(name -> System.out.println("Name of emp1: " + name)); 
       // Output: Name of emp1: Alice
       nameOpt2.ifPresent(name -> System.out.println("Name of emp2: " + name)); 
       // No output since emp2's name is null

       // Using orElse() to provide a default value when the name is absent (null)
       System.out.println("Name of emp2: " + nameOpt2.orElse("Unknown")); 
       // Output: Unknown (default name is provided since emp2's name is null)

       // Using map() to transform the value if it's present (e.g., converting name to uppercase)
       Optional<String> upperNameOpt1 = nameOpt1.map(name -> name.toUpperCase()); 
       upperNameOpt1.ifPresent(name -> System.out.println("Uppercase Name of emp1: " + name));  
       // Output: Uppercase Name of emp1: ALICE
   }
}



LocalTime: Represents a time without a date (hours, minutes, seconds, and nanoseconds).

 

Examples: 14:30:00

Common methods:

LocalTime.now() — Returns the current time.

LocalTime.of(int hour, int minute) — Creates a time with specific hour and minute.

LocalTime.parse(CharSequence text) — Parses a time string into a LocalTime.

plusHours(long hoursToAdd) — Adds hours to the time.

minusMinutes(long minutesToSubtract) — Subtracts minutes from the time.

 

package com.niteshsynergy.java8;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class LocalDateExample {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("Current Date: " + date);

LocalDate specificDate = LocalDate.of(2024, 11, 17);
System.out.println("Specific Date: " + specificDate);

LocalDate nextWeek = date.plusWeeks(1);
System.out.println("One Week Later: " + nextWeek);
LocalTime time = LocalTime.now();
System.out.println("Current Time: " + time);

LocalTime specificTime = LocalTime.of(14, 30);
System.out.println("Specific Time: " + specificTime);

LocalTime nextHour = time.plusHours(1);
System.out.println("One Hour Later: " + nextHour);
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Current DateTime: " + dateTime);

LocalDateTime specificDateTime = LocalDateTime.of(2024, 11, 17, 14, 30);
System.out.println("Specific DateTime: " + specificDateTime);

LocalDateTime nextMonth = dateTime.plusMonths(1);
System.out.println("One Month Later: " + nextMonth);

ZonedDateTime dateTime1 = ZonedDateTime.now();
System.out.println("Current Zoned DateTime: " + dateTime);

ZonedDateTime specificZoneTime = ZonedDateTime.of(LocalDateTime.of(2024, 11, 17, 14, 30), ZoneId.of("Europe/Paris"));
System.out.println("Specific Zoned DateTime: " + specificZoneTime);

ZonedDateTime newYorkTime = dateTime1.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("Current Time in New York: " + newYorkTime);

LocalDate startDate = LocalDate.of(2024, 1, 1);
LocalDate endDate = LocalDate.of(2024, 11, 17);

Period period = Period.between(startDate, endDate);
System.out.println("Period: " + period.getMonths() + " months and " + period.getDays() + " days");

LocalDate date1 = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

String formattedDate = date1.format(formatter);
System.out.println("Formatted Date: " + formattedDate);

// Parse a string into a LocalDate
String dateStr = "17-11-2024";
LocalDate parsedDate = LocalDate.parse(dateStr, formatter);
System.out.println("Parsed Date: " + parsedDate);

/*
Summary of Key Java 8 Time Classes
LocalDate — Date without time.
LocalTime — Time without date.
LocalDateTime — Combines date and time.
ZonedDateTime — Date and time with time zone.
Duration — Represents an amount of time in seconds and nanoseconds.
Period — Represents a period of time in terms of years, months, and days.
DateTimeFormatter — Used for formatting and parsing date and time objects.
*/
}
}
6 min read
Nov 19, 2024
By Nitesh Synergy
Share