Posts

Java 8 - Optional

Java 8 - Optional In this blog, I’ll discuss about Optional class which was introduced in JDK8 under java.util.package. Optional class is used to represent a value is present or absent. With Optional class, developers have to less worry about NullPointerException and can work on neat and clean code. It contains at most one value. Advantages: · No need to check for null · No more NullPointerException at runtime Public final class Optional<T> extends Object { } Let’s understand all its usage with the help of example 1. Optional.empty() To create an empty Optional object we simply need to write // How to create empty Optional              Optional<String> optional = Optional. empty ();              System. out .println( "1. Optional: " + optional );     Output:             1. Optional: Optiona...

Java 9 - Try with resources Improvement

Java 9   -   Try with resources Improvement In this blog, I’ll discuss about try with resources which was introduced with JDK 7 and what enhancement has been done in JDK 9. Try with resources is a great feature which was introduced in JDK 7 that helps in closing resources automatically after being used. Any class can be used as resources if that class implements AutoClosable Interface. Advantages As try with resources closes all the resources file Automatically which prevents memory leaks. M ore readable code as you don’t have to write unnecessary code.   Let’s understand it with an example import java.io.FileNotFoundException; import java.io.FileOutputStream; /**  * This class will explain the try with resources which was introduced with  * JDK7.  *  * @author AbdulWaheed18 @gmail.com  *  */ public class ExmapleWithJava7 {        public static void...

Supplier Functional Interface - JAVA 8

Supplier Functional Interface Supplier is an in-built functional interface introduced in Java 8 in the  java.util.function  package. Supplier does not expect any input but returns the output. This interface can be handy where you want to generate some data like OTP, currentTime or even GUID The functional method of Supplier is get(T t). Here is a simple source code of java.util.function.Supplier @FunctionalInterface public interface Supplier<T> {     /**      * Gets a result.      * @return a result      */     T get(); } Where T get () is an abstract method where T is the return type of the function. Example 1: import java.util.Date; import java.util.function.Supplier; public class SupplierExample {        public static void main(String[] args ) {    ...