为什么我需要显式转换字节和短的字元? [英] Why do I need to explicitly cast char primitives on byte and short?

查看:164
本文介绍了为什么我需要显式转换字节和短的字元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于原语:当我从较小类型转换为较大类型时,转换是隐式的,当我从较大类型转换为较小类型时,我需要显式转换原始数据,这是由于数据丢失所致。但有一些我不能得到的东西。当我在某些情况下(字节和短)向上或向下转换为char时,我总是需要在两个方向显式转换,尽管byte(8bit)适合char(16bit)。

Concerning primitives: When I cast from smaller to bigger types, the casts are implicit, when I cast from bigger to smaller types, I need to explicitly cast the primitives, that's clear due to loss of data. But there is something I don't get. When I up- or downcast to char in some cases (byte and short), I always need to explicitly cast in both directions although byte (8bit) fits into char (16bit)?

(另请参阅 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

查看我的示例...

public class CastingTest
{
    public static void main(String[] args)
    {
        //casting from smaller to bigger types
        short c = 13;
        int d = c;

        byte f = 34;
        short g = f;

        byte h = 20;
        long i = h;

        byte var03 = 6;
        double var04 = var03;   

        //casting from bigger to smaller types
        int j = 12;
        short k = (short)j;

        long m = 56;
        int n = (int)m;

        double o = 19;
        short p = (short)o;

        //not possible without explicit cast, but why?
        byte var01 = 3;
        char var02 = (char)var01;

        short var05 = 5;
        char var06 = (char)var05;

        char var07 = 'k';
        short var08 = (short)var07;
    }
}


推荐答案

code> char 是Java的唯一无符号类型,因此其值范围不完全包含任何其他Java类型的值范围。

char is Java's only unsigned type, therefore its value range does not fully contain any other Java type's value range.

对于目标类型的范围未完全涵盖源类型范围的任何转换,您必须使用显式转换运算符。

You must use an explicit cast operator for any conversion where the target type's range doesn't fully cover the source type's range.

这篇关于为什么我需要显式转换字节和短的字元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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