This week's book giveaway is in the General Computing forum.
We're giving away four copies of Learning Regular Expressions and have Ben Forta on-line!
See this thread for details.
Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Assignment of values  RSS feed

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
author and iconoclast
Sheriff
Posts: 24220
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Really nice explanation
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!