When I was reading the Java SE8 Silver problem book, it said, "Char type can be implicitly cast to int type or double type." I'm ashamed to say that I've been using Java for years in my business, but I didn't know this fact at all.
So, I tried to find out the reason why char type can be cast to int type or double type, but the reason was not written in the problem collection, so I investigated it myself. I tried to summarize the results.
TypeCast.java
public class TypeCast {
public static void main(String[] args) {
char ch = '1';
//Implicitly cast to int type or double type.
int i = ch;
double d = ch;
System.out.println(ch + "Result of casting to int type: " + i);
System.out.println(ch + "Result of casting to double type: " + d);
//Pass char type as an argument to a method whose argument is double type.
foo(ch);
}
static void foo(double d) {
System.out.println("double type: " + d);
}
}
The result of casting 1 to int type: 49
The result of casting 1 to double type: 49.0
double type: 49.0
Looking at the char type wrapper class Character type API, "Unicode character representation" Is written. So if you look at "1" in the Unicode table, the value is "U + 0031". You can see that it is represented by.
The values in the Unicode table are in hexadecimal, which is actually "0x31", so if you change this to decimal, it will be "49". In other words, if the char type "1" is implicitly cast to an int type, this "49" is stored in an int type variable.
Recommended Posts