• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

args[] problem?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What will happen when you compile and run the following program using the command line:
java TestClass 1 2

Answer : It will throw ArrayIndexOutOfBoundsException
Since at the command line java TestClass 1 2 is passed.
and the args[1]; which means 2 elements i.e 0 and 1
When" java TestClass 1 2 "is passed , here "1 2" are like other objects or strings or...etc
so when in the main args[i] is called i.e args[1] is called ,i.e second index, "2" should be printed

Am I right?
Please explain.
Sonir
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you are printing args[i]. not i !
first line you get the i as 2 like you said, no prioblem.
second line look at it carefully: it says:
system.out.prinltn(args[i]); !
not i but args[i]! it tries to do args[2] and thats out of bounds!
tricky one!
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

if you run this program with
java TestClass 1 2
then there are 2 arguments passed to the program, and args has 2 elements
args[0] = 1
args[1] = 2
Now, the first line creates an int value by parsing the string in args[1] (remember that each element in args is a String)
When it parses the string, it takes the String value "2" and returns an int value = 2.This 2 gets assigned to the variable named 'i'.
Then this int value is used as an index into the args array....
System.out.println(args[i]);
becomes
System.out.println(args[2]);
But args only has 2 elements, so args[2] is not in the array, it is outside the range of elements it contains, and this access throws an ArrayIndexOutOfBoundsException.
Rob
[ January 13, 2002: Message edited by: Rob Ross ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic