Java fill type char to short

Why can't we pass the char value as an argument to any method that takes a short parameter, while we can pass the char value to another method whose parameter is of type int ? Why doesn't casting happen from char to short , given that the sizes are equal? I hope short can also store as many short values ​​as possible.

+5
source share
2 answers

Why can't we pass the char value as an argument to any method that takes a short parameter

Because there is no implicit conversion from char to short in the call context.

then how can we pass the char value to another method with an int type parameter?

This is because there is an implicit conversion available from char to int in the context of the call.

Why does type listing not matter from char to short , given that the sizes are equal? I hope short can also store as many short values ​​as possible.

Although char and short are the same size, char is unsigned, while short signed. Therefore, there is no implicit conversion from char to short .

The conversion from char to int is an extension of the primitive conversion ( JLS 5.1.2 ), while the conversion from char to short is a narrowing primitive conversion ( JLS 5.1.3 ). In particular (focus):

Narrowing the conversion of char to an integral type T also simply discards everything except n bits of the least significant bit, where n is the number of bits used to represent type T. In addition to the possible loss of information about the value of a numerical value, this can lead to the resulting value will be a negative number, even if the characters are unsigned 16-bit values.

+13
source

The Java specification says:

Furthermore, if the expression is a constant expression (Β§15.28) such as a byte, short, char or int:

Narrowing the primitive conversion can be used if the type of the variable is byte, short, or char, and the value of the constant expression is represented in the type of the variable.

Char has a minimum value of 0 and a maximum value of 65,535.

A short value has a minimum value of -32,768 and a maximum value of 32,767.

An integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.

So char can fit into an integer, but not a short one, so you have to assure java that you want to make typecast here.

+6
source

Source: https://habr.com/ru/post/1270273/


All Articles