java - java中(char)i或(int)i的目的和含义是什么?

标签 java

来自这个例子

FileInputStream fis=new FileInputStream("lalu.txt");
int i=0;

while(i=fis.read() !=-1){
    System.out.println((char)i);  
}

我问这个问题的目的是为什么char在这里用括号括起来?

最佳答案

why the char is wrapped in parentheses here?

哇哦,这里发生了什么神奇的事?不,它在 Java 中很常见,称为显式类型转换

强制转换表达式在运行时将一种数值类型的值转换为另一种数值类型的相似值;或者在编译时确认表达式的类型是 boolean 值;或在运行时检查引用值是否引用其类与指定引用类型兼容的对象。

括号和它们包含的类型有时被称为强制转换运算符。

CastExpression:
( PrimitiveType ) UnaryExpression
( ReferenceType ) UnaryExpressionNotPlusMinus

当您将 i 声明为 int 并将其转换为 char(在括号中您写 char ) 这意味着你正在做 narrowing primitive conversion

根据§5.1.3:

A narrowing conversion of a signed integer to an integral type T 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 sign of the resulting value to differ from the sign of the input value.

默认情况下,int 数据类型是 32 位有符号二进制补码整数,char 数据类型是单个 16 位 Unicode 字符(引用 here ), 这意味着

  • int 是 4 个字节,
  • char 是 2 个字节(Unicode 字符)。

因此,当您通过显式转换将 integer 缩小为 character 时,您只是告诉编译器丢弃整数的前两个字节并处理 i 作为一个字符!

让我们看一个例子:

int i = 0x41990041; // hex 41990041 is equivalent to decimal 1100546113
System.out.println("printing integer: " + i);
System.out.println("printing char representation of int: " +(char)i);

输出是:

printing integer: 1100546113

printing char representation of int: A

在这里,我将一个随机的 4 字节值转化为整数 i。仔细看,前两个字节 4199 在运行时执行转换时被丢弃,最后两个字节 0041 被打印为字符。见 here hex0041 的字符表示是 A

关于java - java中(char)i或(int)i的目的和含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222344/

相关文章:

java - 在@Query 注解中传递动态创建的查询(根据条件)

javax.net.ssl.SSLHandshakeException :Remote host closed connection during handshake

java - encog 神经网络 - java - 训练不起作用

java - 将 Java LinkedHashMap 转换为 C++ std::map

java - 摩托罗拉 Xoom 是否有绘图错误,或者只有我有?

java - 尝试使用此语言级别不支持的资源

java - 分割字符串时的奇怪行为

java - 使用 weka 对相互作用的粒子进行聚类

java - 子类的类加载器

java - 如何在 Wildfly 中使用自定义系统属性解析器