在Java中将Chars转换为Ints [英] Converting Chars to Ints in Java

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

问题描述

系统:Windows Vista 32-bit,Java 6.0.2

System: Windows Vista 32-bit, Java 6.0.2

我有几个关于将chars转换为int的问题。
我运行下面的代码,让myInt的值为4:

I have a few questions about converting chars to ints. I run the code below, leaving myInt with a value of 4:

  char myChar = '4';
  int myInt = myChar - '0';

现在,这种转换是Java自动完成的吗?是从ascii'4'减去ascii值'0',然后在后台转换为int?这对我很困惑,因为当我尝试反向操作,我必须实际投射结果作为一个char:

Now, is this conversion something that Java does automatically? Was the ascii value of '0' subtracted from ascii '4', and then cast to an int behind the scenes? This is confusing for me because when I try to the reverse operation, I have to actually cast the result as a char:

  int anotherInt = 5;
  char newChar = anotherInt + '0'; //gives error

  char newChar = (char)(anotherInt + '0'); //works fine

这是因为Java自动转换(anotherInt +'0' int,如第一个例子?谢谢。

Is this occuring because Java is automatically casting (anotherInt + '0') to an int, as in the first example? Thank you.

推荐答案

char (2字节类型) int (一个4字节类型)在Java中是隐含的,因为这是一个加宽的转换 - 所有可能的值都可以存储在 char ,还可以存储在 int 中。反向转换不是隐式的,因为它是一个变窄的转换 - 它可以丢失信息( int 的高两个字节被丢弃)。你必须总是在这种情况下显式转换,作为一种告诉编译器是的,我知道这可能会丢失信息,但我仍然想这样做。

The conversion from char (a 2-byte type) to int (a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in a char you can also store in an int. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of the int are discarded). You must always explicitly cast in such scenarios, as a way of telling the compiler "yes, I know this may lose information, but I still want to do it."

这篇关于在Java中将Chars转换为Ints的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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