• Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive type char  RSS feed

 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not properly understand char; I know it is a primitive type. Nevertheless I do not understand for instance the following code:
Why does it work? I mean, an int is not a char and a char is not an int. Please help.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
char is really just an unsigned 16 bit integer type. When you write 'a', you're really just using the integer value 97. The difference is that when you print a char, it is first mapped to an UTF-16 code point. Other than that, it's just a number.
 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the answer. I have an other issue:
The output is:
C
68
134
CC
134

It seems that you can calculate as it were an int. What are the rules?

I am not sure if have seen that you can assign an int to a char. I would kindly ask you to explain that.
 
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
Check out Joel Spolky's article about Unicode and character sets. The integer value of a char is its Unicode code. When you add an integer value to a char value, Java's integer conversion rules kick in and the char will be widened to an int. The JLS has all the nitty-gritty details about integer type conversions but it can be difficult to read.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'C' just prints the character 'C'.
'C' + 1 performs integer addition. The result is an int with the numeric value of 'C' (which is 67) plus 1.
'C' + 'C' again performs integer addition. The result is an int with the numeric value of 'C', times two.
"C" + "C" performs string concatenation. The result is a string with the two string operands concatenated.
2 * 'C' performs integer multiplication. It yields the same result as 'C' + 'C' for the same reasons.

All arithmetic operators in Java return either an int or a long, except for the + operator. It returns a String if either of the operands is a String.

[edit]

Sorry, all arithmetic operators in Java return either an int or a long when no floating point numbers are involved. In that case, they return double.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!