by BehindJava

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Home » java » Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

In this tutorial we are going to learn about whether Java’s +=, -=, *=, /= compound assignment operators require casting or not.

In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:

byte -> short -> int -> long -> float -> double

The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.

For example, when you write:

int a = 2;
long b = 3;
a = a + b;

There is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.

So to avoid it, you must write your code like this:

int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting

A good example of this casting is using *= or /=

byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or

byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or

char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or

char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'