Java: Arithmetic operation on byte

后端 未结 3 556
误落风尘
误落风尘 2020-12-21 14:37

What happened to my code? The following code worked for integer type of data, but couldn\'t work for byte type of data.

public class Exchange {
    public st         


        
相关标签:
3条回答
  • 2020-12-21 15:29

    Corrected code is here

     public static void main(String[] args) {
        //int a = 23, b = 44;
        byte a = 23, b = 44;
        a = (byte) (a + b);
        b = (byte) (a - b);
        a = (byte) (a - b);
        System.out.println("a=" + a + "b=" + b);
    }
    
    0 讨论(0)
  • 2020-12-21 15:32

    If you want to perform an arithmetic operation on byte and assign it back to a byte variable you should explicitly let the compiler know that "you know what you're doing" otherwise you'll get the the error that you're losing information by converting int (the outcome of the arithmetic operation) to byte (on the left side).

    To fix this, cast the outcome of the arithmetic operation back to byte:

        byte a = 23, b = 44;
        a = (byte) (a + b);
        b = (byte) (a - b);
        a = (byte) (a - b);
    
    0 讨论(0)
  • 2020-12-21 15:40

    Simply, Cast the result of your arithmetic operation to byte as follows:

    public class Exchange {
        public static void main(String[] args) {
        //int a = 23, b = 44;
        byte a = 23, b = 44;
        a = (byte) a + b;
        b = (byte) a - b;
        a = (byte) a - b;
        System.out.println("a=" + a + "b=" + b);
        }
    }
    

    Tip:- Use Alt+Enter for hints

    0 讨论(0)
提交回复
热议问题