Java 9 - java.util.Objects new Utility methods

[Updated: Nov 14, 2017, Created: Nov 14, 2017]

Java 9 added new utility methods to java.util.Objects which are mainly useful for checking certain pre conditions before performing the operation on the input object. Following is a quick walk-through of these new methods with examples.

(1) requireNonNullElse()

public static <T> T requireNonNullElse(T obj,
                                       T defaultObj)

The second arguments acts as the default value of the target object, it is returned if the first argument is null, otherwise the first one is returned. This method is good for avoiding annoying null checking if-blocks.

package com.logicbig.example;

import java.math.BigDecimal;
import java.util.Objects;

public class RequireNonNullElseExample {
  public static void main(String[] args) {
      System.out.println(twice(BigDecimal.TEN));
      System.out.println(twice(null));
  }

  public static BigDecimal twice(BigDecimal input) {
      BigDecimal bd = Objects.requireNonNullElse(input, BigDecimal.ZERO);
      return bd.add(bd);
  }
}

Output

20
0

(2) requireNonNullElseGet()

public static <T> T requireNonNullElseGet(T obj,
                                          Supplier<? extends T> supplier)

The difference between this one the the last method is, the default object is created lazily via a supplier. This method is good for the cases where the default object's initialization is costly.

package com.logicbig.example;

import java.util.Arrays;
import java.util.Objects;

public class RequireNonNullElseGetExample {

  public static void main(String[] args) {
      int numbers[] = getSomeNumbers();
      numbers = Objects.requireNonNullElseGet(numbers, () -> new int[]{});
      int sum = Arrays.stream(numbers).sum();
      System.out.println(sum);
  }

  public static int[] getSomeNumbers() {
      //todo
      return null;
  }
}

Output

0

(3) checkIndex()

public static int checkIndex(int index,
                             int length)

This method is for precondition checking for 'index' being greater than zero and less than the 'length' value. An exception is thrown if the precondition fails. This method is useful for index based operations e.g. collections and strings where we want to pre check for the valid index value before exception is thrown elsewhere (which is usually difficult to figure out).

In the following example the precondition for the first call is successful but second one fails.

package com.logicbig.example;

import java.util.Objects;

public class CheckIndexExample {
  public static void main(String[] args) {

      String s = "my string";
      String result = splitTillPos(s, 2);
      System.out.println(result);

      result = splitTillPos(s, 10);
      System.out.println(result);
  }

  private static String splitTillPos(String input, int pos) {
      Objects.checkIndex(pos, input.length());
      return input.substring(0, pos);
  }
}

Output

my
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out-of-bounds for length 9
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at com.logicbig.example.CheckIndexExample.splitTillPos(CheckIndexExample.java:17)
at com.logicbig.example.CheckIndexExample.main(CheckIndexExample.java:12)

(4) checkFromToIndex()

public static int checkFromToIndex(int fromIndex,
                                   int toIndex,
                                   int length)

Similar to the last method but it is useful for those operations's precondition checking where both start and end indexes are involved.

package com.logicbig.example;

import java.util.Objects;

public class CheckFromToIndexExample {
  public static void main(String[] args) {
      String s = "my string";
      String result = getPart(s, 3, 9);
      System.out.println(result);

      result = getPart(s, 3, 10);
      System.out.println(result);
  }

  private static String getPart(String input, int from, int to) {
      Objects.checkFromToIndex(from, to, input.length());
      return input.substring(from, to);
  }
}

Output

string
Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [3, 10) out-of-bounds for length 9
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromToIndex(Preconditions.java:76)
at java.base/jdk.internal.util.Preconditions.checkFromToIndex(Preconditions.java:295)
at java.base/java.util.Objects.checkFromToIndex(Objects.java:398)
at com.logicbig.example.CheckFromToIndexExample.getPart(CheckFromToIndexExample.java:16)
at com.logicbig.example.CheckFromToIndexExample.main(CheckFromToIndexExample.java:11)

(5) checkFromIndexSize()

public static int checkFromIndexSize(int fromIndex,
                                     int size,
                                     int length)

Similar to the last method but instead of end index, the 'size' is used to evaluate the end index.

package com.logicbig.example;

import java.util.Objects;

public class CheckFromIndexSizeExample {
  public static void main(String[] args) {
      String s = "my string";
      String result = getPartByLength(s, 3, 4);
      System.out.println(result);

      result = getPartByLength(s, 3, 8);
      System.out.println(result);
  }

  private static String getPartByLength(String input, int start, int partLength) {
      Objects.checkFromIndexSize(start, partLength, input.length());
      return input.substring(start, start + partLength);
  }
}

Output

stri
Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [3, 3 + 8) out-of-bounds for length 9
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82)
at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343)
at java.base/java.util.Objects.checkFromIndexSize(Objects.java:424)
at com.logicbig.example.CheckFromIndexSizeExample.getPartByLength(CheckFromIndexSizeExample.java:16)
at com.logicbig.example.CheckFromIndexSizeExample.main(CheckFromIndexSizeExample.java:11)

Example Project

Dependencies and Technologies Used :

  • JDK 9.0.1
Java 9 Objects Examples Select All Download
  • java-9-object-util-changes
    • src
      • com
        • logicbig
          • example

See Also