Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
Ronald Lee
 
Comment and Contribute

 

 

 

 

 


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

 

 

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