简体   繁体   中英

Why java do not give error on returning an integer while the return type is long or double?

public double delhi(Integer a)
    {
        return (int)a;
    }

In case you do not get it, look at the return type of the method

Because, an int can fit into a double. its called Widening Primitive Conversion .

The return type declared on a method is used to allocate a memory on the stack to store the return value. Here, by declaring return type as double compiler will allocate more space (64-bit) than required by the actual return value, an int (32-bit). Therefore, there is no loss of data expected on this (up)conversion . Therfore, both compiler and runtime, does not complain and it works. Try the opposite, set return type as int and return a long or double . You will get compiler error because there will be potential of data corruption.

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