将int常量分配给字节变量时是否需要强制转换? [英] Is a cast necessary when assigning an int literal to a byte variable?

查看:47
本文介绍了将int常量分配给字节变量时是否需要强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一行书:

byte rounds = 12, fighters = (byte) 2;

它说明

字节基元有一个四字节带符号整数作为有效字节文字.如果未执行显式强制转换,则整数为隐式转换为一个字节.

The byte primitive has a four-byte signed integer as its valid literal. If an explicit cast is not performed, the integer is implicitly cast to one byte.

根据Oracle文档,字节本质上不是一个字节吗?

According to Oracle doc, isn't a byte should be one byte in nature?

推荐答案

例如,Java提供了用于初始化原始数据类型的特殊文字

Java provides special literals for initializing primitive data types, for example

int a = 1234;
double b = 12.34;
float c = 56.78f;
char d = 'x';

文档说, byte 类型没有特殊的文字.相反,原始类型 byte int 共享其文字.当签名的32位 int 文字适合"单个字节时,Java将执行隐式转换;否则,Java将执行隐式转换.否则,将产生编译时错误.

The documentation says that there is no special literal for byte type. Instead, primitive type byte shares its literal with int. When a signed 32-bit int literal "fits" into a single byte, Java will perform an implicit conversion; otherwise, it will produce a compile-time error.

这篇关于将int常量分配给字节变量时是否需要强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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