• Post Reply Bookmark Topic Watch Topic
  • New Topic

Addition operation on character variables  RSS feed

 
radha gogia
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when addition operation is performed on the character variables ,then it specifies actually that the ASCII values are added because the character variable stores ASCII value of the character constant ,then why after the addition the result cannot be stored inside a character variable ,why it needs to be stored in an integer variable only ,when actually the character variable stores the ASCII value then why is it an error to store the added result in an character variable.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
characters are smaller than integers. What would happen if you add one to the largest character? Should it wrap to the smallest character? Should something else happen?



Here, we get 65535 (max) and then 0.

This works because ch++ tells the compiler that you really do want to store it in a character.

When you write ch + 1, the compiler doesn't know you want it stored in a char so you have to add the cast to tell it.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can learn more from the JLS section about widening conversions for primitives. A char is an integral type so if you do arithmetic on a char, it will often get widened to an int.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
radha gogia wrote:the character variable stores ASCII value of the character constant

It's not actually the ASCII value - ASCII only defines codes 0 to 127. A char is 16 bits and contains a Unicode character, encoded using the UTF-16 character encoding. Codes 0 to 127 of UTF-16 are the same as ASCII, but a char can contain far more different characters than just ASCII characters.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say that you do not store the Unicode value nor the ASCII value of a char. If you look in the Java® Language Specification you find it is called an unsigned integer. What actually happens is that a number is stored, and when you display the value of the char, or add it to a String with the catenation operator + it is converted to its Unicode value.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!