In this post, we will see what does += mean in java.
Table of Contents
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:
1 2 3 4 5 |
int i = 4; i += 2; System.out.println(i) |
Output: // Prints 6
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class PrintEvenNumberMain { public static void main(String[] args) { for (int i=0;i<=10;i+=2) { System.out.print(i+" "); } } } |
Output:
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:
1 2 3 4 5 |
int x = 2; x += 3.2; // compile fine; will cast 3.2 to 3 internally x = x + 3.2; // won't compile! 'cannot convert from double to int' |
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,
1 2 3 4 |
int x = 2; x += 3.2; |
is equivalent to:
1 2 3 4 5 |
int x = 2; x = (int)(x + 3.2); System.out.println(x) // prints 5 |
Using += for String concatenation
You can use +=
operator for String concatenation as well.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class StringConcatenationWithAddition { public static void main(String[] args) { String blogName = "java"; blogName += "2blog"; System.out.println(blogName); } } |
Output:
That’s all about what does += mean in java.