在Java中键入cast into byte [英] Type casting into byte in Java

查看:171
本文介绍了在Java中键入cast into byte的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者。我遇到了一个名为Type Casting的概念。
我有以下代码段 -

I am a beginner in Java. I came across a concept called Type Casting. I have the following snippet-

class Demo
{
    byte b;
    int a=257;
    double d= 323.142
    b=(byte)a;
      System.out.println(b);
    b=(byte)d;
      System.out.println(b);

}

代码输出为-1
67

The output for the code is- 1 67

任何人都可以向我解释输出。

Can anybody explain me the outputs.

提前致谢!

推荐答案

字节类型以8位编码,因此它的值在-128到127之间。在您的情况下,按 byte 进行转换与计算模数并舍入为 int 相同。尝试以下代码,输出相同:

The byte type is encoded on 8 bits, so it takes its values between -128 and 127. In your case, casting by byte is the same as computing a modulo and rounding to an int. Try the following code, the output is the same:

int a = 257;
double d = 323.142;
System.out.println(a % 128);
System.out.println((int) d % 128);

这篇关于在Java中键入cast into byte的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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