aspose file tools*
The moose likes Beginning Java and the fly likes ArrayIndexOutOfBounds exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayIndexOutOfBounds exception" Watch "ArrayIndexOutOfBounds exception" New topic

ArrayIndexOutOfBounds exception

Fantine Ponter
Ranch Hand

Joined: Aug 11, 2008
Posts: 30
Code Magnets in Head First Java, page 351:
The following code (Exercise solution straight from the book) compiles, but when I run it, I get the above exception on main because of the statement " String test = args[0];"

When I comment out that statement and uncomment my own statement just below that (String test = "no";) , I get no runtime error.

Please would someone explain what the statement, String test = args[0];
means, and why I get a runtime error. thanks in advance.

[edit]Disable smilies. CR[/edit]
[ December 05, 2008: Message edited by: Campbell Ritchie ]
Paul Clapham

Joined: Oct 14, 2005
Posts: 18662

It gets the first of the parameters that you typed on the command line after the class name.

If you didn't type any parameters, then you get the error that you observe.
marc weber

Joined: Aug 31, 2004
Posts: 11343

The String array in main contains the arguments you supply at runtime. If you do not supply any arguments, then this array will have a length of zero, and trying to access its elements will result in an exception.

To supply arguments at runtime, enter them on the command line after the class name. For example...

java ShowMyArgs here are some args
[ December 05, 2008: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Fantine Ponter
Ranch Hand

Joined: Aug 11, 2008
Posts: 30
Thanks Paul and Marc.

I'll try to be more observant in future!
jQuery in Action, 2nd edition
subject: ArrayIndexOutOfBounds exception