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?
The Java Language Specification states
where the rules governing whether one value is assignable to another is defined as
and
and finally
In short, a
char
value as the expression of areturn
statement is assignable to a return type ofint
through widening primitive conversion.A
char
is not anint
. However, it is an integral type. That is to say, it's considered to be a whole number that can be converted to and from other integral types (long
,short
,byte
andint
), according to the Java Language Specification.Basically what this means is that it is assignment-compatible to
int
. Its value is between 0 and 65535, and if you assign it to anint
or cast it to anint
and print it, you'll get the UTF-16 value of the character it represents.Hope this little example solves your confusion:
If you pass
char
as anint
likegetValue('x')
, it would return the value of theint
.There is an implicit and natural conversion from
int
tochar
and vice-versa. Note that you thus have the usual arithmetic defined onchar
m which comes very handy when you want, let's say, to iterate on the alphabet :However, note that a
char
is 2 bytes long whereas anint
is 4 bytes long, so casting anint
down to achar
may result in an integer overflow.A
char
is smaller than anint
, so you can return it and it will prepend zeroes to make a longer number. That's not the right thing to return - in your case I'd probably throw an exception instead; however, the editor suggested it because it's something that you're allowed to return and you need to return something.The following code is legal:
In computing, everything is numbers! Just bits and bytes.
int
,char
,byte
,short
andlong
are just numbers. Achar
is just a number that the compiler knows is usually used for displaying the character represented by the particular number (e.g. 32 = space, 48 = zero, etc).A String is a sequence of numbers and other stuff, so a bit more complicated. We don't want to go there.
An
int
is a four byte number and achar
is a two byte number, so you can fit anychar
number in anint
.The designers of Java just decided they would let you convert from char to int without requiring any special casts or conversions.