Why can we not pass a char
value as an argument to any method that accepts a short
parameter, whereas we can pass a char
value to another method whose parameter is of int
type? Why does type casting not take place from char
to short
, given that the sizes are equal? I hope short can also store as much values as short
can.
Short has a minimum value of -32,768 and a maximum value of 32,767. Integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. So char can fit into integer but not into short, that's why you should assure java that you want to do typecast here.
We can convert a char to a string object in java by using the Character. toString() method.
In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically. Note: This is also known as Explicit Type Casting.
Why can we not pass a
char
value as a argument to any method that accepts ashort
parameter
Because there's no implicit conversion from char
to short
in an invocation context.
whereas we can pass a
char
value to another method whose parameter is ofint
type?
That's because there is an implicit conversion available from char
to int
in an invocation context.
Why does type casting not take place from
char
toshort
, given that the sizes are equal? I hope short can also store as much values asshort
can.
Although char
and short
are the same size, char
is unsigned whereas short
is signed. That's why there's no implicit conversion from char
to short
.
The conversion from char
toint
is a widening primitive conversion (JLS 5.1.2) whereas the conversion from char
to short
is a narrowing primitive conversion (JLS 5.1.3). In particular (emphasis mine):
A narrowing conversion of a char to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though chars represent 16-bit unsigned integer values.
Java specification says:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Char has a minimum value of 0 and a maximum value of 65,535.
Short has a minimum value of -32,768 and a maximum value of 32,767.
Integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.
So char can fit into integer but not into short, that's why you should assure java that you want to do typecast here.
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