Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Addition operation on character variables  RSS feed

 
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.
 
author & internet detective
Sheriff
Posts: 38035
605
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.
 
Sheriff
Posts: 11745
191
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.
 
Java Cowboy
Sheriff
Posts: 16082
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.
 
Marshal
Posts: 58378
178
  • 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!