• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

+ on a char ...

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone please explain the following ...
char a = 1;
a += 2; // compile and run ok
a = a + 2; // compile fail - possible loss
// of precision
thanks !
 
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
a = a + 2; // compile fail - possible loss
- This would fail to compile because the result is promoted to int, and assigning an int to a char would fail without an implied cast.
a += 2; // compile and run ok
- This is a compound assignment operation, and in this kind of operation, an implicit cast is made to the result(see JLS 15.26.2). So this operation is equivalent to:
a=(char)(a+2);
 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just one of those little tricky things you could never know until you've seen it once .
 
reply
    Bookmark Topic Watch Topic
  • New Topic