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 Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(14923)
- What is runtime polymorphism in Java?(9389)
- What is String literal pool?(8735)
- Can the run() method be called directly to start a thread?(8193)
- How to add BASIC Authentication into HttpURLConnection?(7445)
- Can transient variables be declared as 'final' or 'static'?(6271)
- Can static methods be overridden?(4927)
Most Recent java Faqs
- What is the difference between an enum type and java.lang.Enum?
- Which replace function works with regex?
- Why does TreeSet.add throw ClassCastException?
- What is variable hiding and shadowing?
- Can private method be overridden?
- How to enable JDBC tracing?
- How to Retrieve Automatically Generated Keys in JDBC?