为什么我们允许将char赋给java中的int? [英] Why are we allowed to assign char to a int in java?

查看:93
本文介绍了为什么我们允许将char赋给java中的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java中的char和int

AsicII表: http://www.asciitable.com

代码下面打印出相应字符的Dec值,例如123 - > 49 50 51

The code below print out the Dec value of the corresponding char, for example "123" -> 49 50 51

 public void foo(String str)
        {
            for(int x = 0; x < str.length(); x++)
            {
                int temp = str.charAt(x);
                System.out.println(temp);
            }
        }

但我注意到java是一种强类型语言,意味着每个事情都必须在编译时进行转换,但是为什么代码知道如何以及何时将char转换为AsicII表中正确的Dec值?
我搞砸了任何java /编程基础吗?

But I notice java is a strong type language, which mean every thing has to be cast in compile time, but how come the code knows how and when to convert char into the correct Dec value in AsicII table? Did I mess up any of the java/programming fundamental?

推荐答案

A char 只是一个无符号的16位数,因为它基本上是 int 类型的一个子集,所以JVM可以毫不含糊地抛出它。

A char is simply an unsigned 16-bit number, so since it's basically a subset of the int type, the JVM can cast it without any ambiguity.

这篇关于为什么我们允许将char赋给java中的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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