Random Java

by

It's always good to have the convenience of the Java libraries on your side, and I'm learning how to use them to make my code cleaner.

Here's a simple one, which I came across lately:
java.util.Math has a max function, and the java docs say:

public static int max(int a, int b)
"Returns the greater of two int values. That is, the result is the argument closer to the value of Integer.MAX_VALUE. If the arguments have the same value, the result is that same value. "

if(a>b)
a=b;

can be replaced with

a=Math.max(a,b);

which is much more readable.

And take this one:

Converting a string with a value from 0 to 9, like "5", into an integer is best done by
str.charAt(index) - '0'

And here's an obscure String function, intern()

"A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned."