• 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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

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: 10308
217
  • 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: 64654
225
  • 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: 64654
225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Veena Pointi wrote:Thank you so much . . .

That's a pleasure
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!