what does += mean in java

In this post, we will see what does += mean in java.

Java += operator

+= is compound addition assignment operator which adds value of right operand to variable and assign the result to variable. Types of two operands determine the behavior of += in java.

In the case of number, += is used for addition and concatenation is done in case of String.

a+=b is similar to a=a+b with one difference which we will discuss later in the article.

Let’s see with the help of example:

Output: // Prints 6

2

Using += in loops

You can use += in for loop when you want to increment value of variable by more than 1. In general, you might have used i++, but if you want to increment it by 2, then you can use i+=2.

Let’s understand with the help of example:
If you want to print even number from 0 to 10, then you could use += operator as below:

Output:

0 2 4 6 8 10

Difference between a+=b and a=a+b

If a and b are of different types, the behavior of a+=b and a=a+b will differ due to rule of java language.

Let’s understand with the help of example:

Here, += does implicit cast, where as + operator requires explicit cast for second operand, otherwise it won’t compile.

As per oracle docs for compound assignment expression:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So,

is equivalent to:

Using += for String concatenation

You can use += operator for String concatenation as well.

Output:

java2blog

That’s all about what does += mean in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *