Posts

Showing posts from October, 2024

Optional in Java

Optional : In order to get rid of NullPointerException. Java8 introduced a new class   in the java.util.Optional It is a container object , which value may or may not contain null value. It is a value based class , use of ==, identity hash code, synchronisation, may give unpredictable results and avoided. It is type safe way of dealing with values which might be null. It is elegant way of dealing with nulls in functional code. How we can prevent these null checks? To indicate that a method   can return an actual value or null value, we can wrap the returned object in an Optional. It deals with null value at compile time level rather than at run time level. Runtime exceptions discovered in production become compile time concerns during development. It contains some useful methods as below: public static <T> Optional<T> of (T value)   ——> it can throw null pointer exception if value is null public static <T> Optional<T> ofNullable (T value)—>...

Heap Pollution in Varargs

  Heap pollution with varargs Heap pollution refers to a situation where the type safety of a collection is compromised due to incorrect use of generic types. While varargs themselves do not directly cause heap pollution, improper usage of varargs can lead to heap pollution if generic types are involved. Let's explore how this can occur: Mixing Generic Types: When using varargs with generic types, it is possible to pass arguments of incompatible types, resulting in unchecked conversions and potential type mismatches. This can lead to heap pollution if the collection is later accessed with incorrect assumptions about its element types. java void processList(List<String>... lists) {     Object[] objects = lists; // Unchecked conversion     objects[0] = Arrays.asList(1, 2, 3); // Heap pollution     String str = lists[0].get(0); // ClassCastException at runtime } In the example above, a varargs parameter is used to accept lists of strings. However, t...