2

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 static void main(String[] args) {
    //int a = 23, b = 44;
    byte a = 23, b = 44;
    a = a + b;
    b = a - b;
    a = a - b;
    System.out.println("a=" + a + "b=" + b);
    }
}

I know that the data-type byte can hold data of the range -2^(8-1) to -1+2^(8-1). But I'm using 23 & 44, so it's less than 127.

Here I got error message "incompatible types: possible lossy conversion from int to byte".

Nawin Mandal
  • 21
  • 1
  • 3

3 Answers3

4

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);
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
2

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

ersks
  • 1,409
  • 2
  • 16
  • 23
  • 1
    http://stackoverflow.com/questions/14125843/basic-arithmetic-operations-on-int-java explains exactly why the widening on arithmetic occurs. – user508633 Feb 20 '16 at 04:51
  • @ersks Thank You Sir for your help! It worked for me. – Nawin Mandal Feb 20 '16 at 04:51
  • It's ok @NawinMandal! – ersks Feb 20 '16 at 04:52
  • @user508633, that link is not working for me! It's maybe helpful, but I found convoluted. – Nawin Mandal Feb 20 '16 at 04:56
  • @NawinMandal doing "alt-enter" without understanding the meaning of what you're doing is a bad habit for a developer. Pro tip: take the time to go over the link in the first comment, make sure you understand what widening means otherwise, you're doomed to run into nasty bugs in the future... – Nir Alfasi Feb 24 '16 at 18:30
2

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);
}
Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45