Win a copy of Event Streams in Action this week in the Java in General 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:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Question on character increment

 
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
char c=’a’;  c=c+1; gives compile error.Where as c++ compiles fine and prints b !

Trying to understand what is the difference .Is pre increment operator doing automatic casting from int to char like compound assignment operator +=?

Thanks,
Veena
 
Saloon Keeper
Posts: 10420
223
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. += and ++ perform implicit casting, while + returns an int (in this case).
 
Marshal
Posts: 65062
247
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look in the JLS (=Java® Language Specification):

The type of the postfix increment expression is the type of the variable.

Whereas the + operator performs promotion on its operands, in this case, as Stephan says, to ints. (Well one operand already is an int, so only c needs to be promoted.)
 
Veena Pointi
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for clarification.
 
Campbell Ritchie
Marshal
Posts: 65062
247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Veena Pointi wrote:Thank you so much . . .

That's a pleasure
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!