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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Out of bounds Exception" Watch "Out of bounds Exception" New topic
Author

Out of bounds Exception

Greedy thomas
Ranch Hand

Joined: May 15, 2003
Posts: 37
Hi
I'm starting to learn Java and have encountered my first problem. I wrote the following small program to print out the command line arguments if any exist.
When I run the program it runs as expected but at the end it prints the following message which I don't understand :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at First.main(First.java:8)

The program code is as follows :
class First {
public static void main(String[] args) {
System.out.println("Check number of arguments") ;
if (args.length == 0)
System.out.println("No arguments passed") ;
else {
for (int i = 0; i <= args.length; i++)
System.out.println(args[i]) ;
}
}
}

I ran the program as follows :
java First A B C
The output was as follows :
Check number of arguments
A
B
C
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at First.main(First.java:8)

Thanks in advance for your help.
Rajesh
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Change this line:
for (int i = 0; i <= args.length; i++)
to this:
for (int i = 0; i < args.length; i++)
The problem is that if there are two entries in the args array, you are going after 3 entries (0, 1, and 2).


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Greedy thomas
Ranch Hand

Joined: May 15, 2003
Posts: 37
Thanks Paul
It now works.
But I have a further question relating to this.
>> The problem is that if there are two entries in the args array, you are going after 3 entries (0, 1, and 2).
If there are only two entries, why does it go after three. Shouldn't it be just args[0] and args[1]. Does the count of args start from 0 or 1. If it starts from 1 then I understand why you would go to 2.
So that means we read the args array from 0 but we count the number of elements in it from 1. Why did Java not start reading the array from 1 - it would seem to be easier - or would it...
Please confirm this.
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
hi R Mera
Welcome
All the array index start from zero
In this case
for (int i = 0; i < args.length; i++)
Assume if there are two entries,the loop will loop two times if the i start from 0
Firstly i=0,secondly i=1, thirdly when i=2
Does the condition is true?
2<2 ?
false
So the loop run two times
And your case
for (int i = 0; i <= args.length; i++)
Firstly i=0,secondly i=1, thirdly when i=2
Does the condition is true?
2<=2 ?
true
So the loop run three times
But there are two entries in the array size, required three entries in the array size,so compiler error occured.
Hope this help



Francis Siu
SCJP, MCDBA
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

Originally posted by R Mera Naam:
Thanks Paul
It now works.
But I have a further question relating to this.
>> The problem is that if there are two entries in the args array, you are going after 3 entries (0, 1, and 2).
If there are only two entries, why does it go after three. Shouldn't it be just args[0] and args[1]. Does the count of args start from 0 or 1. If it starts from 1 then I understand why you would go to 2.
So that means we read the args array from 0 but we count the number of elements in it from 1. Why did Java not start reading the array from 1 - it would seem to be easier - or would it...
Please confirm this.

Arrays are zero-indexed, meaning that you should think of the index as the offset (Even though arrays in Java are implemented differently from arrays in C/C++, the concept is taken from C/C++, where arrays were memory locations and the index was the offset from that memory location)
Think of an a array like a ruler. (We'll use the American 12-inch ruler here; translate to centimeters or whatevers as needed...) There are 12 inches on the ruler. The first inch starts at the zero marking, the second inch starts at the 1 marking (which marks the end of the first inch and the beginning of the second), etc.
So, when you get ruler.length, you get 12, since there are 12 inches in the ruler. When you iterate, you say:
for(int index = 0; index < ruler.length; index++){
Inch anInch = ruler[index];
}
index will start at 0 and go to 11; once index is 12 the loop will stop. If you said:
for(int index = 0; index <= ruler.length; index++){
Inch anInch = ruler[index];
}
index would start at zero and go to 11 fine. When index becomes 12, the code checks that 12 <= 12 (which is true) and runs the loop again. Then you try to get the inch from the ruler that starts at the 12 marking. There isn't one, so it throws an IndexOutOfBoundsException.

Hope this makes everything clear,


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Nicely described!
Going a bit off topic, but does anybody else believe zero based indices (along with case sensitive source code) show a bias toward helping the computer and compiler author instead of helping the humans who write and read the code? I think that's the wrong direction for a modern language!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

Originally posted by Stan James:
Nicely described!

Thanks

Going a bit off topic, but does anybody else believe zero based indices (along with case sensitive source code) show a bias toward helping the computer and compiler author instead of helping the humans who write and read the code? I think that's the wrong direction for a modern language!

I'll agree that zero-based arrays are something a little bit akward when learning the language, but in Java, at least, they are not there for the compiler as so much as they are there for luring C/C++ programmers to Java (See how easy it is!? It's just like C++! :roll: )
I've never considered a case-insensitive language before; I use case to make my code readable (Class names are UllllUllll, methods are llllUllll, etc.) I don't think that, as a human reader, I would enjoy reading that type of code. It would be easier to write, but more difficult to read/maintain. IMHO, Case insensitivity would be OK in a scripting language, but not in a large programming language.
Greedy thomas
Ranch Hand

Joined: May 15, 2003
Posts: 37
Going a bit off topic, but does anybody else believe zero based indices (along with case sensitive source code) show a bias toward helping the computer and compiler author instead of helping the humans who write and read the code? I think that's the wrong direction for a modern language!

I suppose it's a debatable issue.
When it comes to the zero based indices, one argument is that if an array has 3 items then it should start counting from 1 to 3 - 1,2,3 and not 0,1,2. We have learnt through the ages to start counting from 1 e.g. if you have a basket of 5 apples, you would start counting it from 1 i.e. the first apple you pick up would be 1 and so on. In that respect, I'm not so much in favour of zero based indices for arrays.
With regards to case sensitivity, I much prefer case insensitive. Case sensitivity will lead to more compile errors as the user gets used to the language because if you had two methods named getArray and GetArray, these would be regarded as two different methods and if you're writing numerous methods, it can be a little frustrating trying to keep the case correct.
Anyway, that's just my two cents worth. I suppose at the end of the day, it's a personal preference (and also what the language dictates - hey maybe it does make it easier for the compiler to make you look like a bad programmer by displaying so many errors )
R.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
<rant> Copying ANYTHING from C or C++ is PROOF that the language designer went overboard to please the compiler! </rant> Mike Cowlishaw, inventer of REXX (the most sensible language ever) said many parts of the language design made his job as the interpreter author very difficult. But he only had to do his job once. The rest of us got to use it for as long as we liked. What an attitude, eh? I try to show it in everything I build.
 
Don't get me started about those stupid light bulbs.
 
subject: Out of bounds Exception