Java tricks

This is a bag of Java Tricks!

Integer.parseInt
Integer.parseInt (and Long.parseLong) is the basic function to convert from String to numbers. String str = "8888"; int number = Integer.parseInt( str ); // number is 8888

BigInteger
BigInteger (and BigDecimal) is the built-in library for precise really really big numbers. BigInteger has all the basic functions of arthmetic, as well as "isProbablePrime" and "GCD", which are useful in some cases. BigInteger a = new BigInteger( "1" );

// This will not produce any overflows. for ( int i = 0; i < 200; i++ ) a = a.multiply( new BigInteger( i ) );

Multi-Dimensional Array Caching
When using multi-dimensional arrays, you can cache the outer arrays to improve performance hit. This is because it would be checked for out of bounds conditions otherwise. // Before int[][] arr = new int[100][100];

for ( int i = 0; i < arr.length; i++ ) for ( int j = 0; j < arr[i].length; j++ ) // do something with arr[i][j]

// Better for ( int i = 0; i < arr.length; i++ ) { final int[] k = arr[i]; for ( int j = 0; j < k.length; j++ ) // do something with with k[j] }