Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Mar 10, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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");
     } catch (NumberFormatException e) {
       // if user entered an invalid integer, exit the program.
       System.err.println("Error: Can't convert argument to integer");
     // if arraySize is valid integer,
     // declare an array with size equals arraySize
     int intArray[] = new int[arraySize];

  }// end main()
}//end class TestArray
Ronald Lee
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date