Java char is also an int?

2019-01-28 03:23发布

I was trying to get some code done for class:

public int getValue(char value) {
    if (value == 'y') return this.y;
    else if (value == 'x') return this.x;

Since I might not be able to return anything in the end, it told me to do this at the end:

return value;

This surprised me because the return type for the method was of type int. Yet, it was telling me to return a char! I'm using eclipse, and accustomed to the endless number of warnings and stuff, this was a major surprise.

So, is a char really an int? Why is this happening?

7条回答
Luminary・发光体
2楼-- · 2019-01-28 03:51

By definition (in java) a char is an 8bit unsigned integer. (0 to 256)

An int an 32bit signed integer. (−2.147.483.648 to 2.147.483.647)

char a = 65;                    //65 is the ASCII Number of 'A'
System.out.println(a);
>>> A

b = a + 1
System.out.println(b);
>>> B

java autoboxing converts char to int and vice versa

查看更多
登录 后发表回答