Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java 8 Features

  • Java 8 is a version of the Java programming language released by Oracle Corporation in March 2014. It introduced several new features and enhancements to the language, including lambdas, functional interfaces, streams, and default methods in interfaces
    • Lambdas are a new way to express code blocks in a more concise and functional style. They are particularly useful in functional programming and event-driven programming.
    • Functional interfaces are interfaces that contain only one abstract method and can be used as the basis for lambda expressions.
    • Streams are a new way to process collections of data in a parallel and functional way. They allow for more concise and efficient code that is easier to read and maintain.
Table Of Content

  • Java 8 Features
  • Lambda expressions in java
  • Method references in java
  • Functional interface in Java
  • Stream API in Java
  • Optional class in Java
  • Java 8 Security Enhancements






  • Default methods in interfaces allow developers to add methods to existing interfaces without breaking backwards compatibility. This makes it easier to evolve interfaces over time without having to refactor large amounts of code
  • Overall, we can say Java 8 introduced many new features and important part are the enhancements that made the language more powerful and expressive while still maintaining its backward compatibility and strong type safety.


Lambda expressions

A concise way of expressing a single method interface using an expression. This is helpful in writing functional programming style code.


Java example of Lambda expressions
 // Java example of Lambda expressions 
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);

// Using Lambda Expression
numbers.forEach(n -> System.out.println(n));

// Traditional way of looping
for (Integer n : numbers) {
    System.out.println(n);
}





Method references

A shorthand notation for invoking a method by name, which makes the code easier to read and reducing unnecessary repetition.


Java example of Method references
 // Java example of Method references 
List<String> names = Arrays.asList("John", "David", "Bob", "Alice");

// Using method reference
names.forEach(System.out::println);

// Traditional way of looping
for (String name : names) {
    System.out.println(name);
}

Functional interface

A new interface that has a single abstract method, which is used for functional programming in Java.


Java example of Functional interface
 // Java example of Functional interface 
@FunctionalInterface
interface MyInterface {
    void myMethod();
}
public class Main {
    public static void main(String[] args) {
        // Using anonymous inner class
        MyInterface obj = new MyInterface() {
            @Override
            public void myMethod() {
                System.out.println("Hello World");
            }
        };
        obj.myMethod();

        // Using Lambda Expression
        MyInterface obj1 = () -> System.out.println("Hello World");
        obj1.myMethod();
    }
}




Stream API

The Stream API, fantastic tools introduced in Java 8 belongs to the java.util.stream package and includes classes, interfaces, and an enum that enable functional-style operations on elements. Stream API is its lazy computation, meaning it executes operations only when needed.


Java example of Stream API
 // Java example of Stream API 
List<String> names = Arrays.asList("John", "David", "Bob", "Alice");

// Using Stream API
names.stream()
    .filter(name -> name.startsWith("J"))
    .map(String::toUpperCase)
    .forEach(System.out::println);

// Traditional way of looping
for (String name : names) {
    if (name.startsWith("J")) {
        System.out.println(name.toUpperCase());
    }
}




Default methods

Java 8 introduced Default methods, which act like helpful shortcuts in interfaces. It allow to create default methods inside the interface. Method that declared with default keyword inside interface are known as default method. These default methods are non-abstract means these methods can have method body.


Java example of Default methods
 // Java example of Default methods 
interface MyInterface {
    default void myMethod() {
        System.out.println("Hello World");
    }
}

public class Main implements MyInterface {
    public static void main(String[] args) {
        Main obj = new Main();
        obj.myMethod();
    }
}

Base64 Encode Decode

A new class introduced in Java 8, that allows you to encode and decode the data in Base64 format.


Java example of Base64 Encode Decode
// Java example of Base64 Encode Decode
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        String original = "Hello World";
        String encoded = Base64.getEncoder().encodeToString(original.getBytes());
        System.out.println("Encoded String: " + encoded);
        byte[] decodedBytes = Base64.getDecoder().decode(encoded);
        String decoded = new String(decodedBytes);
        System.out.println("Decoded String: " + decoded);
    }
}




Static methods in interface

A new feature of Java 8 that allows you to define static methods inside an interface.


Java example of Static methods in interface
 // Java example of Static methods in interface 
interface MyInterface {
    static void myMethod() {
        System.out.println("Hello World");
    }
}
public class Main {
    public static void main(String[] args) {
        MyInterface.myMethod();
    }
}

Optional class

The Optional class serves as a versatile container, capable of holding a value that may or may not contain a non-null value. It is used to avoid null pointer exceptions when accessing objects. Optional class provides methods to check the presence of a value and perform actions based on that.


Java example of Optional class
 // Java example of Optional class 
Optional<String> name = Optional.ofNullable(null);

// check if value is present
if (name.isPresent()) {
   System.out.println(name.get());
} else {
   System.out.println("Name is null");
}




Collectors class

Java 8's Collectors class is a powerful tool and it is final class that extends objects class. It provide manipulate collections by using intuitive methods like summing, averaging, and counting elements. With Java 8 Collectors, you can efficiently manage data, streamline code, and enhance performance,


Java example of Collectors class
 // Java example of Collectors class 
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
String result = names.stream()
                    .collect(Collectors.joining(", "));

System.out.println(result);

ForEach() method

The forEach() method is used to perform an action on each element of a collection. It is used with the Stream API.


Java example of ForEach() method
 // Java example of ForEach() method 
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
names.stream()
     .forEach(System.out::println);




Nashorn JavaScript Engine

The Nashorn JavaScript Engine is a JavaScript engine for the Java Virtual Machine. It provides a way to execute JavaScript code from within a Java application.


Java example of Nashorn JavaScript Engine
 // Java example of Nashorn JavaScript Engine 
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval("print('Hello, world!');");

Parallel Array Sorting

Parallel Array Sorting is a way to sort large arrays in parallel using multiple threads. It is used to improve the performance of sorting large arrays


Java example of Parallel Array Sorting
 // Java example of Parallel Array Sorting
int[] numbers = {5, 2, 7, 1, 8, 4, 9, 3, 6};
Arrays.parallelSort(numbers);
System.out.println(Arrays.toString(numbers));




Type and Repating Annotations

Type and Repeating Annotations are used to provide additional metadata to Java classes and methods. They are used to specify attributes, behaviors, and restrictions for classes and methods.


Java example of Type and Repating Annotations
 // Java example of Type and Repating Annotations
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(TestCases.class)
public @interface TestCase {
   String value();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestCases {
   TestCase[] value();
}

IO Enhancements Sorting

IO Enhancements are improvements made to the Input/Output (IO) functionality in Java. They include new APIs and classes that provide better performance, security, and functionality.


Java example of IO Enhancements
 // Java example of IO Enhancements
try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"))) {
    String line;
   while ((line = reader.readLine()) != null) {
       System.out.println(line);
   }
} catch (IOException e) {
   e.printStackTrace();
}




Concurrency Enhancements

Concurrency Enhancements are improvements made to the Java Concurrency API. They include new classes and methods that make it easier to write concurrent code.


Java example of Concurrency Enhancements
 // Java example of Concurrency Enhancements
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // Some long running task
   return "Hello, world!";
});

future.thenAccept(System.out::println);

JDBC Enhancements

JDBC (Java Database Connectivity) Enhancements are improvements made to the Java API for database connectivity. They provide new features and improved performance for accessing databases from Java applications


Java example of JDBC Enhancements
 // Java example of JDBC Enhancements
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
     ResultSet resultSet = statement.executeQuery("SELECT * FROM employees")) {
    // process the result set
} catch (SQLException e) {
    e.printStackTrace();
}





Java 8 Security Enhancements

  • The Transport Layer Security (TLS) 1.1 and TLS 1.2 protocols are enabled by default on the client side by the Java Secure Socket Extension (JSSE) provider.
  • A better technique With the addition of AccessController.doPrivileged, code can now assert a portion of its privileges while still allowing a full stack traversal to check for other permissions.
  • The SunJCE provider now includes the Advanced Encryption Standard (AES) and Password-Based Encryption (PBE) algorithms PBEWithSHA256AndAES 128 and PBEWithSHA512AndAES 256.



  • Server Name Indication (SNI) extension is supported for server applications in JDK 8 and is enabled by default for client applications in Java Secure Socket Extension (SunJSSE). The SNI extension is a feature that allows clients to specify the server name they are trying to connect to during handshaking using the SSL/TLS protocols.
  • SunJSSE now includes support for Authenticated Encryption with Associated Data (AEAD) algorithms, allowing for more secure data encryption. The Java Cryptography Extension (SunJCE) provider now includes parameters for the Galois/Counter Mode (GCM) algorithm and implements AES/GCM/NoPadding cipher, enhancing encryption capabilities.
  • The keytool utility now has a new command flag named -importpassword. It is utilized to recognize passwords and safely store them as secret keys. such as java.security classes. Java.security and DomainLoadStoreParameter In order to support DKS keystore type, PKCS12Attribute is added.
  • The SHA-224 variant of the SHA-2 family of message-digest implementations has been added to JDK 8 to improve the cryptographic algorithms.



  • NSA Suite B Cryptography Has Improved Support. The following is included in this:
    • NSA Suite B cryptography algorithms OID registration
    • SHA224 and SHA256 with DSA are two additional signature algorithms for 2048-bit DSA keys that are supported by the SUN provider.
    • Removal of the Diffie-Hellman keysize restriction from 1024 to 2048, according to SunJCE provider (DH)
  • The SecureRandom class, which can be used to generate secure random numbers as well as cyphers, signed messages, private keys, and public keys, was introduced with the Java Development Kit (JDK) 8. Here, the getInstanceStrong() method, which returns the strongest instance of SecureRandom that is currently available. It is recommended to use this method whenever RSA private and public keys need to be generated. Additionally, SecureRandom has unveiled two cutting-edge UNIX platform-specific implementations. These implementations support a variety of use cases for improved performance and security by providing both blocking and non-blocking behaviour.



  • There is now a new PKIXRevocationChecker class that uses the PKIX algorithm to check the revocation status of certificates. It supports mechanisms-specific options, end-entity certificate checking, and best effort verification.
  • Windows now supports 64-bit as part of the PKCS 11 provider support. See the JDK 8 PKCS#11 Reference Guide's 2.1 Requirements section, JEP 131, and RFE 6880559.
  • In Kerberos 5, two brand-new rcache types are included. Type none denotes the absence of any rcache, and type dfl denotes a file-based rcache in the DFL fashion. Also supported now is the subkey that the acceptor requested. The system properties sun.security.krb5.rcache and sun.security.krb5.acceptor.subkey are used to configure them.
  • Constrained delegation and the Kerberos 5 protocol transition are supported by JDK 8 within the same realm.
  • The default implementation of Kerberos 5 does not support the DES-related encryption types. Allow weak crypto=true in the krb5.conf file enables these encryption types, but DES-related encryption types are thought to be extremely insecure and ought to be avoided.



  • An unbound acceptor can be indicated by setting the Krb5LoginModule principal value in a JAAS configuration file to an asterisk (*) on the acceptor side. This implies that if the acceptor possesses the long-term secret keys for a given service, the initiator can access the server using any service principal name. After the context is established, the acceptor can obtain the name using the GSSContext.getTargName() method.
  • The server name can be set to null when creating an SASL server to indicate an unbound server, meaning a client can request the service using any server name. The name can be retrieved by the server after a context has been established using the key name SASL.BOUND SERVER NAME.
  • On Mac OS X, the JNI bridge now includes support for JGSS (Java Generic Security Service). To enable this feature, you can activate it by setting the system property "sun.security.jgss.native" to true. This allows for enhanced security capabilities within Java applications.
  • During SSL/TLS handshaking in the SunJSSE provider, make sure the length of the ephemeral DH key matches the length of the certificate key. To change the ephemeral DH key sizes, a new system property called jdk.tls.ephemeralDHKeySize is defined. With the exception of exportable cipher suites and the legacy mode (jdk.tls.ephemeralDHKeySize=legacy), the minimum allowable size for Diffie-Hellman (DH) keys is set at 1024 bits. This requirement was implemented based on RFE 6956398, which aimed to enhance security standards and mitigate potential vulnerabilities in cryptographic protocols. Additionally, users now have the flexibility to customize the size of ephemeral DH keys, further empowering them to adapt their security measures according to their specific needs. Embracing these advancements ensures a robust and secure communication environment for applications utilizing the Java Development Kit (JDK).



  • The cipher suite preference of the client is respected by the SunJSSE provider by default. By calling SSLParameters, the behavior can be altered to respect the server's preferred cipher suite. the server's setUseCipherSuitesOrder(true) command.

Example of Java 8's security enhancements
 // Java Abstract classes example  
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        String password = "myPassword123";
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
        byte[] digest = md.digest();
        System.out.println("SHA-256 hash of the password: " + bytesToHex(digest));
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}



In the example above, we use the MessageDigest class to compute the SHA-256 hash of a password. This is an example of a cryptographic operation that can be performed using Java 8's security enhancements.


Java Lambda Expressions Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.