gembin

OSGi, Eclipse Equinox, ECF, Virgo, Gemini, Apache Felix, Karaf, Aires, Camel, Eclipse RCP

HBase, Hadoop, ZooKeeper, Cassandra

Flex4, AS3, Swiz framework, GraniteDS, BlazeDS etc.

There is nothing that software can't fix. Unfortunately, there is also nothing that software can't completely fuck up. That gap is called talent.

About Me

 

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.

posted on 2010-07-08 14:25 gembin 阅读(410) 评论(0)  编辑  收藏 所属分类: JavaSE


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(6)

随笔分类(440)

随笔档案(378)

文章档案(6)

新闻档案(1)

相册

收藏夹(9)

Adobe

Android

AS3

Blog-Links

Build

Design Pattern

Eclipse

Favorite Links

Flickr

Game Dev

HBase

Identity Management

IT resources

JEE

Language

OpenID

OSGi

SOA

Version Control

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

free counters