Implicit typecasting not working if passing integer value as argument in java

。_饼干妹妹 提交于 2019-12-12 02:15:34

问题


In the following code , implicit typecasting for an integer value 9 take place and assigned to variable of byte datatype which is of size 8 bits.

class Demo1
{
   public static void main(String args[])
    {

    byte b=9;
    System.out.println(b);

    }

}

The code happily compiled and executed .

but when i wrote the following code it gave me compilation error

class Demo2 
{
   void func1(byte b)
    {
        System.out.println(b);
    }

   public static void main(String[] args) 
    {
       Demo2 d1=new Demo2();
       d1.func1(9);
    }
}

please explain me why implicit (auto typecasting) is not taking place in the latter code?

Thank you all in anticipation.


回答1:


Because byte (8 bits) can hold less information than int (32 bits), so the compiler will not automatically cast int to byte because you can lose information in the process. For example:

    int a = 150;
    byte b = (byte) a;
    System.out.println(b); 

This will print -106 because 150 is out of byte range (-128 - 127).

Compiler needs you to manually cast int to byte to make sure this is not an error and that you understand the implications of the cast.




回答2:


You need to change your code like below so that you don't get possible loss of precision error.

This will make compiler to understand that you know you are going to lose precision.

void func1(int i)
    {
        byte b = (byte)i;
        System.out.println(b);
    }


来源:https://stackoverflow.com/questions/20442782/implicit-typecasting-not-working-if-passing-integer-value-as-argument-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!