Tips and Tidbits from someone Sun felt was Certifiable

Today | ???common.rss??? | ???common.rdf??? | ???common.atom??? | ???common.other???
 

Most people know of the compound assignment operators, such as +=, -=, <<=, and others. It is generally thought that these compound operators can be broken into simple operators like this:

x += y is equivalent to x = x + y
x -= y is equivalent to x = x - y etc.

However, although this is pretty close, it doesn't tell the whole story. What happens if you compile and execute this code?

byte b = 10;
b = b + 5;

What happens? You get a compiler error. Why? Well, that's because the result of using the addition operator is an int and we're trying to assign that result into a variable that is only a byte. Therefore, the compiler complains about a possible loss of precision and requires an explicit cast in order to compile. Why is it, then, that the following compiles and executes fine?

byte b = 10;
b += 5;

The reason this works is because the compound assignment operator isn't exactly equivalent to what we showed above. Instead, the compound assignment operator includes an implict cast to the type of the left-hand operand. So, if we were to break apart the compound operator, it would look like this:

b += 5 is equivalent to b = (byte)(b + 5)

Because of the implicit cast, the compiler doesn't complain about this line. With that in mind, you need to be aware that a compound assignment operator will allow you to overflow variables without giving you any sort of warning. What does the following print?

byte b = 10;
b += 130;
System.out.println(b);

The output of that code is -116. We lost some data because the compound assignment operator includes an implicit cast and the compiler never warned us that we were doing something dangerous. Keep that in mind.

You can read all about compound assignment operators in the JLS §15.26.2 Compound Assignment Operators.

Corey


what will be the output if bye b = 10; b =+5; Another question is b += 5; is same as b=+5; ? Thanks in advance
The compound operators are always in the form +=, -=, *=, etc. There is no such operator as =+. Writing this:

byte b = 5;
b =+ 5;

Is exactly the same as writing this:

b = 5;
if I have int a=1,b=2,c=3; a+=b+=c+=7; what is the equiv statment that is fully parenthesized? and what are the values for a,b,c. Thanks for any help
if I have int a=1,b=2,c=3; a+=b+=c+=7; what is the equiv statment that is fully parenthesized? and what are the values for a,b,c. Thanks for any help

To me, that looks like a homework problem and I can't say I want to answer people's homework for them. I will, however, say that the values for a, b, and c are easily determined by simply compiling and executing the code. Given that, work backwards and work out what the parenthesized equation would be.

Thank you
I was confused, now I see the light. thanks
TrackBack to http://radio.javaranch.com/corey/addTrackBack.action?entry=1082576069000