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?
In Java, char can be converted to int value using the following methods: Implicit type casting ( getting ASCII values ) Character. getNumericValue()
Char is short for character, and should be used for strings. Int is used for whole numbers. Never use char for number.
However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.
char in java is defined to be a UTF-16 character, which means it is a 2 byte value somewhere between 0 and 65535. This can be easily interpreted as an integer (the math concept, not int ). char in c is defined to be a 1 byte character somewhere between 0 and 255.
A char
is smaller than an int
, 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:
char c = 'h';
int i = c;
The Java Language Specification states
When a return statement with an
Expression
appears in a method declaration, theExpression
must be assignable (§5.2) to the declared return type of the method, or a compile-time error occurs.
where the rules governing whether one value is assignable to another is defined as
Assignment contexts allow the use of one of the following:
- a widening primitive conversion (§5.1.2)
and
19 specific conversions on primitive types are called the widening primitive conversions:
char
toint
,long
,float
, or `double
and finally
A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly: [...]
A widening conversion of a
char
to an integral typeT
zero-extends the representation of thechar
value to fill the wider format.
In short, a char
value as the expression of a return
statement is assignable to a return type of int
through widening primitive conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With