In this post, we will see what does += mean in java.
[toc]
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:
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:
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:
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,
int x = 2; x += 3.2;
is equivalent to:
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.
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.