将整数内部转换为较小尺寸的char [英] Internal conversion of integer to char whose size is smaller

查看:46
本文介绍了将整数内部转换为较小尺寸的char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下程序中,我将一个整数数据类型分配给char数据类型.

In the following program , I am assigning a integer data type to a char data type.

    public static void main(String args[]) {
        char ch =65;
        System.out.println(ch);
    }

我知道以下事实:int占用32位,而char占用16位.有了这些知识,我期望编译器抛出一些错误消息尝试将较大的数据转换为较小的数据".

I know the fact that int occupies 32 bits and char occupies 16 bits . With that knowledge , I was expecting the compiler throw an error of some message "Attempt to convert a data of higher size to a lower size ".

为什么编译器不会抱怨并且在内部将输出转换为'A'并打印出来(我知道这是ASCII等于65的事实,我的问题仅与数据类型的大小有关)?

Why is the compiler not complaining and internally converting and printing the output as 'A' (I understand the fact that it is the ASCII equivalent of 65, my question is only related to the size of data types) ?

推荐答案

实际上,编译器确实会验证范围.之所以有用,是因为 int 65 在预期范围内.

The compiler does in fact validate the range. That is working because int 65 is within the expected range.

以下内容无法编译:

char c = (int)Character.MAX_VALUE + 1
char c = 65536

这就像您的作业一样:

char c = 65535 //Within range

但是,当值在编译时不是常量时,则需要进行强制转换:

When the value is not a constant at compile time, though, there's need for cast:

private static void charRange(int i) {
    char c = (char) i;
    System.out.println(" --> " + (int) c);
}

charRange(65);
charRange(Character.MAX_VALUE + 20);

检查不会发生(为溢出腾出空间)

And the check doesn't happen (making room for overflow)

-> 65
-> 19

--> 65
--> 19

这篇关于将整数内部转换为较小尺寸的char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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