Skip to main content

Java 8 Features

Java 8 Features 

  1. Interface Default and Static Methods
  2. Method References 
  3. Functional Interfaces and Lambda Expressions
  4. Java Stream API for Bulk Data Operations on Collections
  5. Optional Class
  6. Java Time API
  7. StringJoiner
  8. Java Parallel Array Sorting
  9. forEach() method in Iterable interface
  10. Collection API improvements
  11. Concurrency API improvements
  12. Java IO improvements
  13. Collectors Class
  14. Base64 Encoder

Interface Default and Static Methods

interface Example{
   
    static String sayHello() {
        System.out.println("Hello");
        return "Hello";
    }
    //can be overridden.
    default String sayBye() {
        return "bye";
    }
}

Method References

Reference to a Static Method

Syntax :- ContainingClass::methodName.
numList.forEach(System.out::println);

Reference to an Instance Method

syntax containingInstance::methodName.

FuncExample x = s::isMarried;//can be any method returns boolean

@FunctionalInterface
interface FuncExample {
    boolean isAnything();
}

Reference to an Instance Method of an Object of a Particular Type

syntax ContainingType::methodName.
listStudent.stream().filter(Student::isMarried).collect(Collectors.toList());

Optional

// set an optional empty value. optinal.get() will throw NPE
Optional<String> optional = Optional.empty();

String str = "value";
Optional<String> optiona2 = Optional.of(str);
// if str null will throw NPE only for non null objec
Optional<String> optiona2 = Optional.ofNullable(getString());
// null is allowed

List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());
// if the getList() returns null it will create an empty array

Optional<User> user = Optional.ofNullable(getUser());
String result = user.map(User::getAddress)
                .map(Address::getStreet).orElse("Address N/A");

Throwing Custom Exception

String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();

Date/Time API

LocalDateTime dateAndTime = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(dateAndTime );

LocalTime time = LocalTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(time);

LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);


ZonedDateTime date = ZonedDateTime.now();
System.out.println(date);
//2023-02-23T18:59:33.506042900+08:00[Asia/Singapore]

ZonedDateTime zoneDateById = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(zoneDateById);
//2023-02-23T16:29:33.509040100+05:30[Asia/Kolkata]

OffsetTime date = OffsetTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);
// 16:32:38.897413600+05:30

OffsetDateTime date = OffsetDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);
// 2023-02-23T16:33:44.422517600+05:30

And more classes :
StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter

// Adding values to StringJoiner
joinNames.add("Select name");
joinNames.add("age");
joinNames.add(" from");

StringJoiner tableData = new StringJoiner(" ");
tableData.add("Student");
tableData.add("where");
tableData.add("something;");

joinNames.merge(tableData);


System.out.println(joinNames);
//Select name,age, from,Student where something;

Java Parallel Array Sorting


int[] arr = {20,5,6,3,80,8};
Arrays.parallelSort(arr);
System.out.println(Arrays.toString(arr));
//Suitable for large array sorting

Stream for Arrays Class


int chars[] = new int[10];
int max = Arrays.stream(chars).max().getAsInt();

IO Enhancements 

// Files in a directory
Files.list(Path.of("C:\\Users\\Dayalan\\Downloads\\")).forEach(System.out::println);
// File content as stream of strings
Files.lines(Path.of("C:\\Users\\Dayalan\\Downloads\\addresses.csv")).forEach(System.out::println);

// Files.find(startPath,searchDepth,findCondition,followLink-Optional)
List<Path> listOfPath = Files.find(
        Path.of("D:\\Entertainment"),
        Integer.MAX_VALUE,
        (a, b) -> a.getFileName().toString().equals("Rockabye.mp3"))
        .collect(Collectors.toList());
listOfPath.forEach(System.out::println); // Ref:
// https://mkyong.com/java/java-files-find-examples/

BufferedReader.lines()


FileReader f = new FileReader("C:\\Users\\Dayalan\\Downloads\\addresses.csv");
BufferedReader bR = new BufferedReader(f);
bR.lines().filter(n -> n.contains("John")).findAny().ifPresent(System.out::println);

Miscellaneous Java 8 Core API improvements

Some miscellaneous API improvements that might come handy are: 
  1. ThreadLocal static method withInitial(Supplier supplier) to create instances easily. 
  2. The Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order, etc. 
  3. min(), max() and sum() methods in Integer, Long and Double wrapper classes.
  4. logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
  5.  ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file. 
  6. Several utility methods in Math class.
  7. jjs command is added to invoke Nashorn Engine. 
  8. jdeps command is added to analyze class files 
  9. JDBC-ODBC Bridge has been removed.
  10. PermGen memory space has been removed and MetaSpace introduced 

Java 11

  1. Local-Variable Syntax for Lambda Parameters: The ability to use var in the parameters of a lambda expression, which makes the code more concise.
  2. HTTP Client API: The new HTTP client API provides a more efficient and flexible way to perform HTTP requests and handle responses.
  3. Epsilon: A new experimental garbage collector that is designed to handle very short-lived objects, reducing the impact on overall application performance.
  4. ZGC: A new experimental low-latency garbage collector that is designed for large heaps and that can handle multi-terabyte heaps.
  5. Flight Recorder: A new tool that allows you to collect detailed information about the behavior of your application, which can help you diagnose issues and optimize performance.
  6. Dynamic Class-File Constants: A new constant pool form that allows constants to be defined at runtime, enabling improved performance and reducing the memory footprint of some applications.
  7. Unicode 10: Java 11 includes support for Unicode 10, which adds new characters and scripts, including the bitcoin symbol.
  8. Enhanced Deprecation: A new @Deprecated annotation that allows developers to indicate when a feature will be removed or become obsolete, and to provide additional information about the deprecation.
  9. JEP 321: The specification of the Java EE and CORBA modules has been removed, as they are no longer needed in the modern Java ecosystem.
  10. Other improvements: Java 11 also includes various other improvements, such as better support for dynamic class loading, better performance for string concatenation, and improved startup time for small applications.
Local-Variable Syntax

    var list = Arrays.asList(10,2,36,5,4,8);
    //Type of list automatically identified based on the right side definition
    list.stream().forEach( ( var n)-> System.out.println(n));

Using inside lambda 
The () are must, we can skip them,
(var s1) -> s1 + s1;
If we use var for one variable others can not be skipped or mixed with different variable types.



Comments

Popular posts from this blog

Spring Boot 4 Ready

Spring Boot 4.x Features Explained:  Java 25, AI Agents, MCP, Resilience, gRPC & Cloud Native Evolution Building on the massive architectural shift introduced in version 3, Spring Boot 4.x bridges the gap between traditional enterprise stability and the rapid demands of modern cloud architecture and AI integration. While Spring Boot 3 introduced the foundations for GraalVM Native Images and Virtual Threads , Spring Boot 4 takes these capabilities mainstream, introduces native resilience patterns, and upgrades the underlying Spring ecosystem. Spring Boot 4 Major Theme: Modern enterprise development with cloud-native architecture, AI integration, improved resilience, better modularity, and optimized JVM performance. Table of Contents 1. Upgraded Foundation & Baselines 2. Built-in Core Resilience Features 3. First-Class Agentic AI & Model Context Protocol (MCP) 4. Native API Versioning Strategy 5. Modern...

Most questions in 2025

Java Spring Boot Senior Engineer Interview Questions & Answers A complete interview preparation guide for Senior Java Engineers, Spring Boot Developers, and Backend Technical Leads covering Java, Spring Boot, Microservices, Cloud, Database, Security, and Performance Engineering concepts. Target Audience: Senior Java Developers Spring Boot Engineers Microservice Architects Backend Technical Leads Table of Contents 1. Describe Yourself 2. RESTful APIs and Standards 3. Latest Spring Boot Version & Features 4. Java Optional 5. WebFlux Reactive Programming 6. WebFlux Retry Mechanism 7. WebFlux Pagination APIs 8. Circuit Breaker 9. Resilience Patterns 10. Rate Limiter 1. Describe Yourself A senior engineer introduction should highlight technical experience, architecture knowledge, ownership, and problem-solving capabilities. Sample Answer I am a Java backend engineer with 7+ years of experience desi...

Data Structure

Java Data Structures A highly-scannable architectural cheat sheet for developers and technical interviews. 1. Linear vs. Non-Linear: The Core Division Data Structure Classification Hierarchy ┌───────────────────────┐ │ Data Structures │ └───────────┬───────────┘ │ ┌───────────────┴───────────────┐ ▼ ▼ ┌────────────────────┐ ┌────────────────────┐ │ Linear (Seq) │ │ Non-Linear │ └──────────┬─────────┘ └──────────┬─────────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ▼ ▼ ▼ ▼ [Static] [Dynamic] [Trees] [Graphs] (Array) (Queue, Stack) (BST) (Network) ...