Monday, 27 May 2019

Java: Why byte = byte + 1 is not compiling?


App.java
public class App {

 public static void main(String args[]) {
  byte b = 10;
  b = b + 1;

 }

}


Try to compile App.java, you will end up in below compilation error.

$javac App.java
App.java:5: error: incompatible types: possible lossy conversion from int to byte
  b = b + 1;
        ^
1 error

Reason behind compilation error
When you do b = b + 1, type of the expression b + 1 is promoted to int and you can assign the int to a byte variable. To solve this problem, explicitly convert the result of (b + 1) to a byte.
b = (byte) (b + 1);


App.java
public class App {

 public static void main(String args[]) {
  byte b = 10;
  b = (byte) (b + 1);

 }

}

Note
a. Compound assignment operators perform type conversion implicitly.
b += 1 is an equivalent to b = (byte)(b + 1)


You may like

No comments:

Post a Comment