This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Assignment of values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assignment of values" Watch "Assignment of values" New topic
Author

Assignment of values

Vrushali Gore
Ranch Hand

Joined: Oct 17, 2005
Posts: 40
line1 byte b;

line2 b += 10;
line3 b = b + 10;
line4 b = 'b' + 1;



In line2 how does compiler compiles the program without giving error while at line3 we would get in error. In case of expressions byte, short & char is promoted to int so by that rule line4 should give error but still it compiles well

How this happens?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24168
    
  30

Hi,

Welcome to JavaRanch!

The compound assignment operators effectively include a cast to the appropriate type -- i.e.,

b += 10;

is actually not equivalent to

b = b + 10;

but rather

b = (byte) (b + 10);

So this explains line 2. Line 4 compiles because " 'b' + 1" is a constant expression which can be evaluated at compile time; the compiler can see that it is less than Byte.MAX_VALUE so there is no overflow, and the result is a byte constant.

Line 3, on the other hand, is evaluated at runtime. The compiler doesn't keep track of the values of variables on previous lines of code, so as far as it knows, the expression might overflow; therefore, this is an error.


[Jess in Action][AskingGoodQuestions]
Nipun Devlekar
Greenhorn

Joined: Dec 07, 2005
Posts: 9
Really nice explanation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assignment of values
 
Similar Threads
assertion related(mock)
Overloading doubt
Type casting
casting - shift operators [scjp1.4]
how to revert ArrayList!