Sunday, 14 July 2024

Java 10 to 17 most features to optimizing the code in the application

 


Java 10

  1. Local-Variable Type Inference (var)

    • Description: Allows the type of local variables to be inferred by the compiler.
    • Example:
      var list = new ArrayList<String>();
    • Benefit: Reduces boilerplate code and makes code more readable.
  2. Application Class-Data Sharing (AppCDS)

    • Description: Extends CDS to allow application classes to be archived and shared.
    • Benefit: Reduces startup time and memory footprint.

Java 11

  1. New String Methods

    • Description: Adds methods like isBlank(), lines(), strip(), and repeat().
    • Example:
      String str = " ";
      System.out.println(str.isBlank()); // true
    • Benefit: Simplifies common string manipulations.
  2. Local-Variable Syntax for Lambda Parameters

    • Description: Allows var to be used in lambda parameters.
    • Example:
      (var s1, var s2) -> s1 + s2;
    • Benefit: Enables more consistent syntax and supports type inference in lambdas.
  3. HTTP Client (Standard)

    • Description: Introduces a new HTTP client API for handling HTTP requests.
    • Example:

      HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://example.com")).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    • Benefit: Provides a more efficient and feature-rich way to perform HTTP operations.

Java 12

  1. Switch Expressions (Preview)

    • Description: Extends the switch statement to be used as an expression.
    • Example:

      int num = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; };
    • Benefit: Simplifies switch statements and makes them more expressive.
  2. JVM Constants API

    • Description: Introduces an API to model nominal descriptions of key class-file and run-time artifacts.
    • Benefit: Enhances code maintenance and analysis tools.

Java 13

  1. Text Blocks (Preview)
    • Description: Introduces multiline string literals.
    • Example:
      String json = """ { "name": "John", "age": 30 } """;
    • Benefit: Simplifies writing and reading multiline strings.

Java 14

  1. Switch Expressions (Standard)

    • Description: Makes switch expressions a standard feature.
    • Benefit: Improves readability and reduces boilerplate code in switch statements.
  2. Pattern Matching for instanceof (Preview)

    • Description: Simplifies the use of instanceof by introducing pattern matching.
    • Example:

      if (obj instanceof String s) { System.out.println(s.toLowerCase()); }
    • Benefit: Reduces boilerplate code and makes type checks more readable.

Java 15

  1. Text Blocks (Standard)
    • Description: Makes text blocks a standard feature.
    • Benefit: Further simplifies handling of multiline strings.

Java 16

  1. Pattern Matching for instanceof (Standard)

    • Description: Makes pattern matching for instanceof a standard feature.
    • Benefit: Improves readability and reduces boilerplate in type checks.
  2. Records

    • Description: Introduces a new kind of class for immutable data carriers.
    • Example:

      public record Point(int x, int y) {}
    • Benefit: Reduces boilerplate code for data classes by automatically generating constructors, accessors, equals, hashCode, and toString methods.

Java 17

  1. Sealed Classes

    • Description: Allows a class or interface to restrict which other classes or interfaces may extend or implement it.
    • Example:

      public abstract sealed class Shape permits Circle, Square, Rectangle {}
    • Benefit: Provides more control over the class hierarchy and improves security and maintainability.
  2. Pattern Matching for switch (Preview)

    • Description: Extends switch expressions and statements with pattern matching.
    • Example:

      switch (obj) { case String s -> System.out.println(s.toLowerCase()); case Integer i -> System.out.println(i * 2); default -> throw new IllegalStateException("Unexpected value: " + obj); }
    • Benefit: Makes switch statements more powerful and expressive by enabling pattern matching.

Optimizing Code Using These Features

  1. Conciseness: Use lambda expressions, the Stream API, and text blocks to reduce boilerplate and make your code more concise and readable.
  2. Efficiency: Stream API, pattern matching, and records improve performance and reduce code complexity.
  3. Maintainability: The module system, sealed classes, and pattern matching improve code maintainability and readability.
  4. Safety: Optional, records, and sealed classes enhance type safety and reduce common errors.

By leveraging these features, you can write more efficient, maintainable, and readable Java code, significantly improving your applications.

Thursday, 4 July 2024

Java 9 features with explanation

 Java 9, released in September 2017, introduced a significant number of new features and enhancements, with the module system being the most notable. Here's a comprehensive overview of the major features in Java 9:

1. Java Platform Module System (Project Jigsaw)

  • Explanation: Introduced modularization to the Java platform, allowing developers to create and use modules. This feature helps in organizing large codebases and improving encapsulation.
  • Example:
    module com.example.module {
    requires java.base; exports com.example.package; }

2. JShell: The Interactive Java REPL

  • Explanation: JShell provides an interactive command-line tool to evaluate Java code snippets without the need for a full development environment. It helps in quick testing and learning.
  • Example:
    jshell> int x = 10;
    jshell> System.out.println(x + 2);

3. Collection Factory Methods

  • Explanation: Simplified creation of immutable collections using static factory methods in List, Set, and Map interfaces.
  • Example:
    List<String> list = List.of("a", "b", "c"); Set<String> set = Set.of("a", "b", "c"); Map<String, String> map = Map.of("key1", "value1", "key2", "value2");

4. Private Interface Methods

  • Explanation: Allows interfaces to have private methods, which can be used to share common code between default and static methods.
  • Example:
    interface MyInterface { private void privateMethod() { // Common code } default void defaultMethod() { privateMethod(); } }

5. Stream API Enhancements

  • Explanation: Added new methods to the Stream API, such as takeWhile(), dropWhile(), iterate(), and ofNullable().
  • Example:
    List<Integer> list = List.of(1, 2, 3, 4, 5); list.stream().takeWhile(n -> n < 4).forEach(System.out::println);

6. Optional Enhancements

  • Explanation: Added new methods like ifPresentOrElse(), or(), and stream() to the Optional class.
  • Example:
    Optional<String> optional = Optional.of("Hello"); optional.ifPresentOrElse(System.out::println, () -> System.out.println("Value is absent"));

7. HTTP/2 Client (Incubator)

  • Explanation: Introduced a new HTTP client API to support HTTP/2 and WebSocket. Initially provided as an incubator module (jdk.incubator.http).
  • Example:
    HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://example.com")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());

8. Multi-Release JAR Files

  • Explanation: Allows JAR files to contain version-specific class files, enabling compatibility with multiple versions of the Java runtime.
  • Example:
    mylibrary.jar ├── META-INF │ └── versions │ └── 9 │ └── com │ └── example │ └── MyClass.class └── com └── example └── MyClass.class

9. Process API Improvements

  • Explanation: Enhanced the Process API to provide more control and information about operating system processes.
  • Example:
    ProcessHandle currentProcess = ProcessHandle.current(); System.out.println("PID: " + currentProcess.pid()); currentProcess.children().forEach(child -> System.out.println("Child PID: " + child.pid()));

10. Deprecated and Removed Features

  • Explanation: Deprecated some older features and APIs, including the Applet API, and removed features like the JVM options -Xprof and -Xfuture.

11. Multi-Resolution Images API

  • Explanation: Added a new java.awt.image.MultiResolutionImage API to support multiple versions of an image in a single image object.
  • Example:
    MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image; Image variant = multiResolutionImage.getResolutionVariant(32, 32);

12. Enhanced Deprecation

  • Explanation: Added the ability to specify forRemoval and since attributes in the @Deprecated annotation.
  • Example:
    @Deprecated(since = "9", forRemoval = true) public void oldMethod() { // Code }

13. Unified JVM Logging

  • Explanation: Introduced a common logging system for all components of the JVM, making it easier to configure and manage logs.
  • Example:
    java -Xlog:gc*=info:file=gc.log

14. Stack-Walking API

  • Explanation: Introduced the java.lang.StackWalker API to provide a more flexible and efficient mechanism for stack walking.
  • Example:
    StackWalker walker = StackWalker.getInstance(); walker.forEach(frame -> System.out.println(frame.getClassName() + " " + frame.getMethodName()));

15. Compact Strings

  • Explanation: Optimized the String class to use a more compact representation internally, reducing memory footprint.
  • Impact: Improves memory efficiency without changing the external behavior of the String class.

16. Segmented Code Cache

  • Explanation: Improved performance by dividing the code cache into distinct segments: non-method, profiled, and non-profiled methods.
  • Impact: Enhances JVM performance and maintainability.

These features collectively make Java 9 a significant release, enhancing modularity, performance, and ease of use for developers.

Java 8 features with explanation

 Java 8, released in March 2014, introduced a significant number of new features and enhancements aimed at improving productivity, performance, security, and ease of use. Here are some of the most notable features:

1. Lambda Expressions:

Explanation: A Lambda Expression is a short, anonymous function introduced in Java 8 that enables functional programming in Java. It allows you to write inline implementations of functional interfaces (interfaces with a single abstract method), making your code shorter, cleaner, and more expressive..

Example1:

// Traditional way

Runnable r1 = new Runnable() {

    @Override

    public void run() {

        System.out.println("Hello world one!");

    }

};


// Using lambda expression

Runnable r2 = () -> System.out.println("Hello world two!");

Example2:

List<String> list = Arrays.asList("a", "b", "c");

list.forEach(element -> System.out.println(element));

Example3:

import java.util.stream.IntStream;

public class LambdaPrintExample {

    public static void main(String[] args) {

        IntStream.rangeClosed(1, 100)

                 .forEach(n -> System.out.println(n));

(OR)

List<Integer> numbers = IntStream.rangeClosed(1, 100)

                                         .boxed()  // Convert IntStream to Stream<Integer>

                                         .collect(Collectors.toList());

        // Print each number using a lambda

        numbers.forEach(n -> System.out.println(n));

    }

}

🧠 Summary

FeatureLambda Expression Example
No arguments() -> System.out.println("Hi")
One argumentx -> x * x
Multiple arguments(a, b) -> a + b
With block(a, b) -> { return a * b; }

2.Functional Interfaces:

Explanation: A functional interface is an interface that contains only one abstract method, annotated with @FunctionalInterface. It can have multiple default or static methods. They can be used with lambda expressions and method references.

Example

✅ Example: Custom Functional Interface

@FunctionalInterface interface MyPrinter { void print(String message); // Single abstract method }

✅ Usage with Lambda:

MyPrinter printer = msg -> System.out.println("Message: " + msg); printer.print("Hello Functional Interface!");

✅ Common Built-in Functional Interfaces (in java.util.function)

InterfaceMethodUse CaseLambda Example
Predicate<T>test(T)Returns booleanx -> x > 10
Function<T, R>apply(T)Converts type T to type Rs -> s.length()
Consumer<T>accept(T)Takes a value and returns nothingx -> System.out.println(x)
Supplier<T>get()Provides a value() -> "Hello"
UnaryOperator<T>apply(T)Operates on a single type Tx -> x * x
BinaryOperator<T>apply(T, T)Operates on two values of same type(a, b) -> a + b

✅ Examples:

🔹 Predicate<T>:

Predicate<String> isLong = s -> s.length() > 5; System.out.println(isLong.test("hello")); // false

🔹 Function<T, R>:

Function<String, Integer> lengthFunction = s -> s.length(); System.out.println(lengthFunction.apply("Java")); // 4

🔹 Consumer<T>:

Consumer<String> printer = s -> System.out.println(s); printer.accept("Lambda Rocks!");

🔹 Supplier<T>:

Supplier<Double> randomSupplier = () -> Math.random(); System.out.println(randomSupplier.get());

✅ Why Use Functional Interfaces?

  • Enable cleaner, more expressive code using lambdas.

  • Power the Stream API, event handlers, concurrency utilities, etc.

  • Provide building blocks for custom behavior injection.

3.Stream API:

Explanation: The Stream API provides a powerful way to process sequences of elements (such as collections) in a functional style. Streams support operations like map, filter, reduce, and more.

Example1:

List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList

    .stream()

    .filter(s -> s.startsWith("c"))

    .map(String::toUpperCase)

    .sorted()

    .forEach(System.out::println);

Example2:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> squares = numbers

                               .stream()

                               .map(n -> n * n)

                               .collect(Collectors.toList());


4.Default Methods:

Explanation: Default methods allow you to add new methods to interfaces without breaking the existing implementations. They provide a default implementation that can be overridden by implementing classes.

Example:

interface MyInterface {

    default void newMethod() {

        System.out.println("Newly added default method");

    }

   void existingMethod();

}


5.Optional Class:

Explanation: The Optional class in Java is a container object introduced in Java 8 to avoid NullPointerException by representing the presence or absence of a value in a type-safe way.

✅ Why use Optional?

Traditionally:


String value = getValue(); // might return null if (value != null) { System.out.println(value.length()); }

With Optional:

Optional<String> value = getValue(); value.ifPresent(v -> System.out.println(v.length()));

✅ Creating Optional Instances:

Optional<String> opt1 = Optional.of("Hello"); // Non-null value Optional<String> opt2 = Optional.ofNullable(null); // Might be null Optional<String> opt3 = Optional.empty(); // No value
Method Description
Optional.of(value) Throws NullPointerException if value is null Optional.ofNullable(value) Allows null Optional.empty() Returns an empty Optional

✅ Common Methods of Optional:

MethodDescription
isPresent()Returns true if value is present
ifPresent(Consumer)Executes block if value is present
get()Returns the value (throws exception if absent)
orElse(default)Returns value or default
orElseGet(Supplier)Returns value or lazy-default
orElseThrow()Throws NoSuchElementException if empty
map(Function)Transforms value if present
flatMap(Function)Like map, but flattens nested Optional
filter(Predicate)Returns Optional if value passes condition

Example 1:

Optional<String> optional = Optional.of("Hello");

optional.ifPresent(System.out::println);

Example 2:

public Optional<String> getUserNameById(int id) {

    if (id == 1) {

        return Optional.of("Alice");

    } else {

        return Optional.empty();

    }

}

// Usage

Optional<String> name = getUserNameById(1);

// Safe access

name.ifPresent(n -> System.out.println("User: " + n));

// Default value

String result = name.orElse("Unknown");

System.out.println(result);

✅ Real-world Use Case:

public Optional<User> findByEmail(String email) {
return userRepository.stream() .filter(u -> u.getEmail().equals(email)) .findFirst(); // Returns Optional<User> } findByEmail("john@email.com") .map(User::getName) .ifPresent(System.out::println);

6.Method References:

Explanation: Method references provide a way to refer to methods without executing them. They are a shorthand for lambda expressions that only call an existing method.

Example

// Using lambda expression

List<String> names = Arrays.asList("Swamy", "Java", "Spring");

list.forEach(item -> System.out.println(item));


// Using method reference

list.forEach(System.out::println);

7.Date and Time API:

Explanation: Java 8 introduced a new Date and Time API (java.time package) that is more comprehensive model for date and time that is more readable and less error-prone than the previous java.util.Date and java.util.Calendar classes.

✅ Key Features of java.time

  • Immutable and thread-safe

  • Fluent and easy-to-read API

  • Clear separation of date, time, date-time, instant, and zone

  • Better time zone support

  • Built-in parsing and formatting

  • Inspired by the Joda-Time library

Example

        LocalDate date = LocalDate.now();             // e.g. 2025-06-19

        LocalTime time = LocalTime.now();             // e.g. 09:41:32.123

        LocalDateTime dateTime = LocalDateTime.now(); // e.g. 2025-06-19T09:41:32.123


8. Nashorn JavaScript Engine

Explanation: A JavaScript engine for executing embedded JavaScript code within Java applications. Provides improved performance and compliance with ECMAScript standards.

Example

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");

engine.eval("print('Hello, World!');");

9. Base64 Encoding and Decoding

Explanation: Java 8 introduced the java.util.Base64 class for encoding and decoding data in Base64 format.

Example

String originalInput = "test input";
String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);

10. Parallel Array Sorting

Explanation: Java 8 introduced the Arrays.parallelSort() method, which uses the Fork/Join framework to sort arrays in parallel.

Example

int[] array = {5, 3, 8, 1, 2};
Arrays.parallelSort(array);

11. Stamps and Counters

Explanation: New classes introduced for concurrent programming, such as StampedLock and LongAdder.

Example:

StampedLock lock = new StampedLock();
long stamp = lock.writeLock();
try {
    // critical section
} finally {
    lock.unlockWrite(stamp);
}

12. Concurrent Adders

Explanation: LongAdder and DoubleAdder are new classes that provide better performance in highly-concurrent scenarios.

Example

LongAdder adder = new LongAdder();
adder.increment();
System.out.println(adder.sum());

13. PermGen Removal

  • Explanation: The permanent generation (PermGen) space was removed and replaced with Metaspace, which automatically grows as needed.
  • Impact: Reduces OutOfMemoryError related to PermGen space and improves performance.


14. JavaFX Enhancements

  • Explanation: JavaFX was enhanced with new UI controls, 3D graphics features, and new packaging tools.
  • Example:
// Example code for JavaFX application
public class MyJavaFXApp extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(event -> System.out.println("Hello World!"));

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


15. Repeating Annotations

  • Explanation: Java 8 allows the same annotation to be used multiple times on the same declaration or type use.
  • Example:
@Repeatable(Schedules.class)
@interface Schedule {
    String dayOfWeek();
    String hour();
}

@Schedule(dayOfWeek = "Monday", hour = "10:00")
@Schedule(dayOfWeek = "Tuesday", hour = "11:00")
public void scheduledTask() {
    // Task code
}


16. Type Annotations

Explanation: Java 8 allows annotations to be used in more places than before, such as on any type use.

Example

public class MyClass<@NonNull T> {
    // Code
}

17. Improved Collections API

Explanation: The Collections API was improved with methods like removeIf(), forEach(), replaceAll(), and sort().

Example:

List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
list.removeIf(s -> s.startsWith("t"));
list.forEach(System.out::println);