Win a copy of AWS Security this week in the Cloud/Virtualization 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
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

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: 12030
257
  • 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: 69527
277
  • 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: 69527
277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Veena Pointi wrote:Thank you so much . . .

That's a pleasure
 
Run away! Run away! Here, take this tiny ad with you:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic