What does the “+=” operator do in Java?

What does the "+=" operator do in Java?

In java the default type of numbers like 2 or -2(without a fractional component) is int and unlike c# that’s not an object and we can’t do sth like 2.tostring as in c# and the default type of numbers like 2.5(with a fractional component) is double; So if you write:

short s = 2; s = s + 4;

you will get a compilation error that int cannot be cast into short also if you do sth like below:

float f = 4.6; f = f + 4.3;

you will get two compilation errors for setting double ‘4.6’ to a float variable at both lines and the error of first line is logical because float and double use different system of storing numbers and using one instead of another can cause data loss; two examples mentioned can be changed like this:

s += 4 f += 4.3

which both have an implicit cast behind code and have no compile errors; Another point worthy of consideration is numbers in the range of ‘byte’ data type are cached in java and thus numbers -128 to 127 are of type byte in java and so this code doesn’t have any compile errors:

byte b = 127

but this one has an error indeed:

byte b = 128

because 128 is an int in java; about long numbers we are recommended to use an L after the number for the matter of integer overflow like this:

long l = 2134324235234235L

in java we don’t have operator overloading like c++ but += is overloaded only for String and not for the let’s say StringBuilder or StringBuffer and we can use it instead of String ‘concat’ method but as we know String is immutable and that will make another object and will not change the same object as before :

String str = “Hello”; str += “World”;

It’s fine;


Leave a Reply