Converting Chars to Ints in Java

2019-01-18 00:58发布

System: Windows Vista 32-bit, Java 6.0.2

I have a few questions about converting chars to ints. I run the code below, leaving myInt with a value of 4:

  char myChar = '4';
  int myInt = myChar - '0';

Now, is this conversion something that Java does automatically? Was the ascii value of '0' subtracted from ascii '4', and then cast to an int behind the scenes? This is confusing for me because when I try to the reverse operation, I have to actually cast the result as a char:

  int anotherInt = 5;
  char newChar = anotherInt + '0'; //gives error

  char newChar = (char)(anotherInt + '0'); //works fine

Is this occuring because Java is automatically casting (anotherInt + '0') to an int, as in the first example? Thank you.

2条回答
孤傲高冷的网名
2楼-- · 2019-01-18 01:27

The conversion from char (a 2-byte type) to int (a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in a char you can also store in an int. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of the int are discarded). You must always explicitly cast in such scenarios, as a way of telling the compiler "yes, I know this may lose information, but I still want to do it."

查看更多
疯言疯语
3楼-- · 2019-01-18 01:47

If C rules are anything to go by, your char can be automatically coerced into an int without a cast in your first example, as the conversion does not involve a loss of information.

However, an explicit cast is required in your second case, where there is potential to lose information since a char is smaller than an int.

查看更多
登录 后发表回答