java - Java 中从 char 到 short 的类型转换

标签 java casting

<分区>

为什么我们不能将 char 值作为参数传递给任何接受 short 参数的方法,而我们可以传递 char将值传递给另一个参数为 int 类型的方法?为什么在大小相等的情况下,不会从 charshort 进行类型转换?我希望 short 也可以像 short 一样存储尽可能多的值。

最佳答案

Why can we not pass a char value as a argument to any method that accepts a short parameter

因为在调用上下文中没有从 charshort 的隐式转换。

whereas we can pass a char value to another method whose parameter is of int type?

那是因为在调用上下文中charint 的隐式转换可用。

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.

尽管 charshort大小相同,但是 char 是无符号的,而 short 已签名。这就是为什么没有从 charshort 的隐式转换。

charint 的转换是一个加宽 原语转换(JLS 5.1.2),而从char 的转换code> 到 short 是一个narrowing 原语转换 ( JLS 5.1.3 )。特别是(强调我的):

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 - Java 中从 char 到 short 的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352541/

相关文章:

java - 为 BacKstack 调用 getChildFragmentManager() 时出现非法状态异常

java - 配置 Springboot 以使用 2 个不同的数据库

java - PropertyNotFoundException : Target Unreachable, 'null' 返回空

java - Andengine和box2d碰撞检测

java - BufferedReader.readLine() 创建线程()?

java - 无法从 int 转换为 byte

java - 如何强制转换 List<T> 以便能够调用相应对象上的特定方法?

java - 如果我包含括号,为什么输出会不同

java - 为什么 && 会返回并强制转换?

list - 如何获取 List 的第一个元素,它本身是 Map [int, Any] 类型的 Map 的成员