Why can't i cast (byte) Data Type into (short) Data Type in Java

Viewed 426

So, Actually Im still new in Java Programming Language and still learning about casting Data type So in this case, i have a trouble in casting Byte into Short. Can You guys help me??

public class Main {
    public static void main(Strings[] args) {
        int number = 2;
        long updateNumber = number + 2;
        System.out.println(updateNumber); //output : 4
    }
}

So in this case, i can cast from (int) into (long) Data type normally because (long) data size is bigger than (int). it's the same case as when i trying to cast it from (short) into (int). But why can't i use this concept to casting Data Type from (byte) into (short)?? eventhough (short) has Data size bigger than (byte)??

public class Main {
    public static void main(Strings[] args) {
        byte number = 2;
        short updateNumber = number + 2;
        System.out.println(updateNumber); //output : Error
    }
}

I guess thats it.. Sorry for the trouble and Thank youu hehe..

1 Answers

When we add two byte type variables or byte type variable with int type variable the result is automatically cast (implicit casting) to int. So the compiler will give error if we want to assign the result of addition to a short type variable.

While you can assign it to short type variable by explicit casting.

public static void main(String[] args) throws MyException {
        byte number = 2;
        //Explicit casting
        short updateNumber = (short) (number + 2);

        System.out.println(updateNumber); // output : Error
}

As the result of the addition can overflow because here number variable value can be changed at runtime. So if you declare number as final and addition of the numbers fits in range of byte then you won't need to do explicit casting because compiler would be knowing in advance weather the result of addition can be hold by byte or not.

public static void main(String[] args) throws MyException {
        final byte number = 2;
        //Explicit casting not needed as number is final
        short updateNumber = number + 2;
    
        System.out.println(updateNumber); // output : Error
 }
Related