Why not throwing an ArrayIndexOutOfBoundsException?
Let's take a look at the following code:
public Class Program{
public static void main(String[] args){
int i = 0;
int[] a = {1,2};
a[i] = i = 2;
System.out.println(i + " " + a[0]+ " "+a[1]);
}
}
What is the output from the above code?
The output is:
2 2 2
You may raise some questions: "When does i get a value 2?", "Why doesn't it use the same value (i=2) for a[i] (which should actually give an ArrayOutOfBoundsException Exception)?", and so on.
The reason no ArrayIndexOutOfBoundsException is thrown is because each of the operands is evaluated from left to right. Basically the array reference is evaluated first then the rest of the expression is done according to the rules in the "15.26.1 Simple Assignment Operator =" of Java Language Specification 3rd Edition. We first evaluate a[i] while i is still 0. Then the assignment takes place after the leftmost operand is evaluated. After the assignment operator takes over, it changes the value of i to 2 and then assign i variable value to a[0]. Hence, a[0] obtains a value of 2 and no an ArrayIndexOutOfBoundsException is thrown.
The assignment is performed from right to left, but operand evaluation is evaluated from left to right.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?