Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

java - Short hand assignment operator, +=, True Meaning?

I learnt that i+=2 is the short-hand of i=i+2. But now am doubting it. For the following code, the above knowledge holds no good:

byte b=0; b=b+2; //Error:Required byte, Found int

The above code is justifiable, as 2 is int type and the expression returns int value.

But, the following code runs fine:

byte b=0; b+=2; //b stores 2 after += operation

This is forcing me to doubt that the += short-hand operator is somewhat more than I know. Please enlighten me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When in doubt, you can always check the Java Language Specification. In this case, the relevant section is 15.26.2, Compound Assignment Operators.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So you were almost correct, except that a cast is added as well. In your case: b+=2; qualifies to b=(byte)(b+2);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...