栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么将short转换为char是一个狭窄的转换?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么将short转换为char是一个狭窄的转换?

这是因为a

short
可以保持负值,而
char
您可能从中看不到
Character.MIN_VALUE
。让我举几个例子。

  short s = -124;  char c = 124; // OK, no compile time error  char d = -124; // NOT OK, compile time error since char cannot hold -ve values  char e = s; // NOT OK, compile time error since a short might have -ve values which char won't be able to hold  char f = (char)s; // OK, type casting. The negative number -124 gets converted to 65412 so that char can hold it  System.out.println((short)f); // -124, gets converted back to a number short can hold because short won't be able to hold 65412  System.out.println((int)f); // 65412, gets converted to 65412 because int can easily hold it.

A(负)号

-n
转换为时
char
,变得
2^16-n
。因此,
-124
成为
2^16-124 = 65412

我希望这有帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453895.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号