This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hello, Sorry if this has been asked and answered before. I searched in this forum and didn't come up with any hits so here goes: I'm fuzzy on how exactly one specifies how many arguments main will accept before getting an ArrayOutOfBoundsException. In the Kathy Sierra and Bert Bates book (not the Head First one, the Osborne Certification one) it looks like the code within main performs an action based on whether the proper number of arguments were entered at the command line when executing the class containing main but where is it specified how many there should be? Thanks in advance for your time. Barbara
Hi Barbara I think you mean to say ArrayIndexOutOfBoundsException, and not ArrayOutOfBoundsException. ArrayIndexOutOfBoundsException is not thrown depending upon how many arguments you specify at the command line, but how you access those arguments in your program. Remember that arrays are indexed from 0 to (length - 1). So, if you try to access any element in the array at index equal to or greater than 'length', an ArrayIndexOutOfBoundsException would be thrown. Here's a simple example:
If you compile and run the above program as:
The program would print: 3 javaranch is cool Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at ArrayIndexTest.main(ArrayIndexTest.java:8) It will throw an ArrayIndexOutOfBoundsException because of line marked 4. The 'length' of the array 'args' is 3 and it can be indexed only from 0 to 2. Index 3 is out of the bounds (range) of this array and hence the exception. Hope this helps. Cheers Harwinder [ November 15, 2003: Message edited by: Harwinder Bhatia ]
Joined: Sep 30, 2003
Thanks very much for your detailed and informative reply. Yes, I did make a type and leave out the "Index" I'm afraid I didn't ask my original question clearly: what I still don't understand is how the JVM knows what the "length" of the String array args is? Does one declare it? I'm completely new to Java and was unaware of what the (String  args) in main was for until I read about it in the KS & BB book and the Programmer's Guide to Java Certification. I'm just missing the point of where one changes or specifies the number of cells that the args, or "freddie" as mentioned in KS & BB, array has. Sorry if this is a lame question. Thanks. Barbara