• 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

Why Does the following code throws ArrayIndexOut OfBoundsException

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following code:

public class Test
{
static int i;
static public void main(String[] args)
{
do
{
System.out.println(args[++i]); //line1
} while (i < args.length);//lin2
}
}

Why does the above code throws ArrayIndexOutOfBoundsException?

Further i need explanation for the commentted lines marked with line1,line2


Thx
Venkat
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You want to print args[0] through args[args.length-1]

You are actually printing args[1] through args[args.length]

There are two problems:

1. A do loop takes you through the first time before testing your condition. If array args[] is empty and args.length == 0, you will get an ArrayIndexOutOfBoundsException because there is no args[0] to print.

2. By incrementing your index after testing it but before using it to print, you will print the wrong element. You will never print args[0]. When the index reaches args.length, you will get an ArrayIndexOutOfBoundsException because there is no args[args.length].

You need to change to a while or for loop and increment the index after printing the array element, not before.
 
reply
    Bookmark Topic Watch Topic
  • New Topic