devxlogo

Assigning the Size of an Array at Run Time

Assigning the Size of an Array at Run Time

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
See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist