class StringMemoryDemo { /** * Method that tries to create the largest array * of String that will fit into the VM. * Can optionally call this routine with the specific * String to continually try to create. */ public static void main( String [] args ) { String oneString = "Average Title (1995)"; if( args.length == 1 ) oneString = args[ 0 ]; int low = 10000; int high = 100000000; while ( low <= high ) { int mid = (low + high) / 2; try { test( oneString, mid ); low = mid + 1; } catch( OutOfMemoryError e ) { high = mid - 1; } } Runtime rt = Runtime.getRuntime( ); int vmsize = (int) rt.totalMemory( ); System.out.println( "Virtual machine size: " + vmsize ); System.out.println( "Each string length is: " + oneString.length( ) ); System.out.println( "Able to create " + high + " strings" ); System.out.println( "Avg cost per String (including 4 byte ref to it): " + vmsize / high + " bytes" ); } public static void test( String theString, int numStrings ) { String [] a = new String[ numStrings ]; for( int i = 0; i < a.length; i++ ) a[ i ] = new String( theString ); a = null; } }