Clamp and other new Java 21 methods

A Java developer always likes to look into the JDK, like a magician in his old tomes, to see if there is an unknown spell, er method, with which he can improve his source code. In fact, Java 21 has introduced a lot of new methods that make everyday life a little easier.

Throughout all Java versions, there has been the annoying task of limiting the value range of a number. This was often because a position in a list, a string or a file had to be accessed. As jumping to a non-existent position causes an exception thrown, it is therefore usual to check whether the index lies in a special interval. For a long time, the following code was a common solution.

private int checkValue(int x) {
  return Math.max(0, Math.min(100, x));
}

Math#min and Math#max are used to prevent the respective limit from being exceeded. With Java 21, it is now possible to simplify this expression using the Math#clamp method.

private int checkValue(int x) {
  return Math.clamp(x, 0, 100);
}

Strictly speaking, the first construct has no longer been necessary since Java 9 because the Objects#checkIndex, Objects#checkFromToIndex and Objects#checkFromIndexSize methods are available for this purpose. These check whether an index or sub-interval is in the correct value range. Otherwise an IndexOutOfBoundsException is thrown. Three new methods have been added with Java 21, because the previous methods only work on int parameters. The new methods work on long parameters.

The String class has also been given a new indexOf method, which can now search in a subinterval. This eliminates annoying substring operations.

Six new methods for handling the first and last element of a list improve poorly readable addressing. Until now, accessing the first and last elements of a list always required the following code.

E first = list.get(0);
E last = list.get(list.size() - 1);

But now there are finally List#getFirst and List#getLast, which significantly increases the readability of the source code.

E first = list.getFirst();
E last = list.getLast();

There are also List#addFirst, List#addLast, List#removeFirst and List#removeLast for inserting and deleting at these positions.

Finally, a small method for all those who have always been annoyed that it is not clear what the delimiter looks like when splitting. As a regular expression can be specified as delimiter in the String#split method, each delimiter in a String can look different. But unfortunately the developer doesn’t know. In addition, there is now also the String#splitWithDelimiters method, which also returns the delimiters in the result.

While browsing the JDK, I noticed a few other interesting methods that have been around for a while. But that’s another story.

Leave a Comment