1.

What is the difference between a=a+b and a+=b

Answer»

The a=a+b statement has an assignment operator = and a arithmetic operator + while a+=b has a arithmetic assignment operator +=. Apart from this there is only a slight difference between the two.

For similar integer or byte or float data TYPES both the expressions would compile.

But if one value(a) is byte and the other(b) is int, a=a+b will not compile as byte+int is not byte

On the other HAND, a+=b will compile as the arithmetic assignment operator will do an implicit type casting.

Take for example,

public class Example {    public static void main(String []args)    {        byte a=2;        int b=3;        a=a+b; // generates an error as byte+int=int        System.out.println(a);    } }

The above program generates an error

$javac Example.java Example.java:7: error: INCOMPATIBLE types: possible LOSSY conversion from int to byte        a=a+b;           ^ 1 error

But if we take a+=b

public class Example {    public static void main(String []args)    {        byte a=2;        int b=3;        a+=b; // compiles        System.out.println(a);    } }

This code is error free and will generate the following output:

$javac Example.java $java Example 5


Discussion

No Comment Found