Java中的char和int [英] char and int in Java

查看:250
本文介绍了Java中的char和int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地看到这段代码有效。我认为char和int是Java中的两种不同的数据类型,我不得不将char转换为int来为此提供ascii equivelent。为什么这样做?

I was surprised to see this code work. I thought that char and int were two distinct data types in Java and that I would have had to cast the char to an int for this to give the ascii equivelent. Why does this work?

String s = "hello";
int x = s.charAt(1);
System.out.println(x);


推荐答案

A char 可以自动转换为 int 。请参阅 JLS 5.1.2

A char can be automatically converted to an int. See JLS 5.1.2:


以下19种基本类型的特定转换称为扩展基元转换:

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

...


  • char to int,long,float或double

...

将有符号整数值扩展为整数类型T只需对符号扩展二进制补码表示整数值填充更宽的格式。 将字符的扩展转换为整数类型T零扩展字符值的表示以填充更宽的格式。

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.

(强调补充)

这篇关于Java中的char和int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆