Converting Chars to Ints in Java

前端 未结 2 1388
一整个雨季
一整个雨季 2020-12-09 14:22

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:



        
相关标签:
2条回答
  • 2020-12-09 15:01

    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."

    0 讨论(0)
  • 2020-12-09 15:09

    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.

    0 讨论(0)
提交回复
热议问题