加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中的char和int

发布时间:2020-12-14 16:36:39 所属栏目:Java 来源:网络整理
导读:看到这段代码工作,我感到很惊讶.我认为char和int是 Java中的两种不同的数据类型,我不得不将char转换为int来为此提供ascii equivelent.为什么这样做? String s = "hello";int x = s.charAt(1);System.out.println(x); 解决方法 char可以自动转换为int.见 JLS
看到这段代码工作,我感到很惊讶.我认为char和int是 Java中的两种不同的数据类型,我不得不将char转换为int来为此提供ascii equivelent.为什么这样做?
String s = "hello";
int x = s.charAt(1);
System.out.println(x);

解决方法

char可以自动转换为int.见 JLS 5.1.2:

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • char to int,long,float,or double

A widening conversion of a signed integer value to an integral type T simply sign-extends the two’s-complement representation of the integer value to fill the wider format. A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

(重点补充)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读