转换数据类型在java中分配

时间:2014-11-10 09:42:52

标签: java type-conversion

我不明白为什么我应该使用{b =(byte)i}或{i =(int)d}来转换。请亲切地告诉我为什么它会在转换中发生。我的示例代码如下。

public class Conversion {

    public static void main(String[] args) {
        byte b;
        int i = 257;
        double d = 323.142;
        System.out.println("\n Conversion int to byt");
        b = (byte) i;
        System.out.println("i and b "+i+ " after "+b);

        System.out.println("\n Conversion int to byt");
        i = (int) d;
        System.out.println("d and i "+d+ " after "+i);

    }

}

2 个答案:

答案 0 :(得分:0)

你正在做"扩大原始转换"和"缩小原始转换"。

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3

答案 1 :(得分:0)

byte的范围为-128 to 127,如果超出限制,则必须明确将其转换为int 同样的方式int具有范围,如果它超出其范围,则必须明确地转换它

如果byte的值介于-128 to 127之间,则无需明确将其转换为int

如需更多帮助,我可以按照链接指导您

  1. Oracle description about primitive data type

  2. Why is the range of bytes -128 to 127 in Java?

  3. Chapter 5. Conversions and Promotions