Java Reference
In-Depth Information
The compound assignment operator += can also be applied to String variables. In such cases, the operand1 must
be of type String and the operand2 may be of any type including boolean . For example,
String str1 = "Hello";
str1 = str1 + 100; // Assigns "Hello100" to str1
can be rewritten as
str1 += 100; // Assigns "Hello100" to str1
Tip
Of the compound operators, only the += operator can be used with a String left-hand operand.
The following are examples of using the compound assignment operators. In the examples, each use of a
compound assignment operator is independent of the effects of its previous uses. In all cases, it has been assumed
that the values of the variables remain the same, as the values assigned to them at the time of their declarations.
int i = 110;
float f = 120.2F;
byte b = 5;
String str = "Hello";
boolean b1 = true;
i += 10; // Assigns 120 to i
// A compile-time error. boolean type cannot be used with +=
// unless left-hand operand (here i) is a String variable
i += b1;
i -= 15; // Assigns 95 to i. Assuming i was 110
i *= 2; // Assigns 220 to i. Assuming i was 110
i /= 2; // Assigns 55 to i. Assuming i was 110
i /= 0; // A runtime error . Division by zero error
f /= 0.0; // Assigns Float.POSITIVE_INFINITY to f
i %= 3; // Assigns 2 to i. Assuming i is 110
str += " How are you?"; // Assigns "Hello How are you?" to str
str += f; // Assigns "Hello120.2" to str. Assuming str was "Hello"
b += f; // Assigns 125 to b. Assuming b was 5, f was 120.2
str += b1; // Assigns "Hellotrue" to str. Assuming str was "Hello"
Increment (++) and Decrement (--) Operators
The increment operator (++) is used with a variable of numeric data type to increment its value by 1 , whereas the
decrement operator (--) is used to decrement the value by 1 . In this section, I will discuss only the increment operator.
The same discussion applies to the decrement operator with the only difference being it will decrement the value by 1
instead of increment it by 1 .
 
 
Search WWH ::




Custom Search