简体   繁体   中英

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

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.

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.

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM