When delaring an array of primitive types in C and C++, you have to assign a constant for the array size. Since Java treats arrays as objects, the size of an array is treated like an attribute of an object and can be assigned at run time. This is useful when you want to create an array to store data, but you can’t determine the size of it until run time (for example, when you are receiving packets from a socket). Therefore, this code is valid:
class TestArray { public static void main(String[] args) { int arraySize; try { if (args.length == 1) arraySize = Integer.parseInt(args[0]); else { System.err.println("Error: one argument expected"); return; } } catch (NumberFormatException e) { // if user entered an invalid integer, exit the program. System.err.println("Error: Can't convert argument to integer"); return; } // if arraySize is valid integer, // declare an array with size equals arraySize int intArray[] = new int[arraySize]; }// end main()}//end class TestArray