Posts

Showing posts from January, 2019

Understanding Optional.orElse() vs Optional.orElseGet()

In Java, Optional provides a way to handle potentially null values safely. The methods orElse() and orElseGet() are used to provide default values when an Optional is empty. However, the difference between these two methods is important depending on the cost of the default value computation. Step 1: Define the Default Method Let's assume we have a method that returns a default value of type String : public String getDefault () { System. out .println( "Getting Default Value" ); return "Default Value" ; } Step 2: Examine the Two Cases Case 1: Using orElseGet() String name = Optional.of(value) .orElseGet(() -> getDefault()); Here, getDefault() is called only if value is null . This means getDefault() is evaluated lazily (only when needed). Case 2 : Using orElse() String name = Optional.of(value) .orElse(getDefault()); In this case, getDefault() is called always , regardless of whether value is null or not. This means getD...

How to use Interfaces in Java?

In Java, interfaces play a crucial role in defining contract-based programming . They provide a way to define method signatures without implementing them, which can be later implemented by different classes. The reason for using interfaces is to achieve abstraction , loose coupling , and flexibility in your code. Benefits of Using Interfaces: Decoupling : Interfaces allow you to separate the definition of functionality from its implementation. This way, the code that uses the interface doesn't need to know the specific implementation details, only the methods it should call. Multiple Implementations : An interface can be implemented by multiple classes, providing flexibility to have different implementations of the same behavior. Supports Multiple Inheritance : In Java, a class can only inherit from one class (single inheritance), but it can implement multiple interfaces. This is a key advantage of interfaces in Java. Functional Programming : Interfaces, especially functional int...