Getting Started
In programming, it is extremely common to modify a variable's value based on its current state. For example, you might add points to a player's score, subtract an item from an inventory count, or double a price. Java provides a set of convenient shorthand operators to make these common update operations more concise and readable.
What You Should Be Able to Do
Use compound assignment operators (
+=,-=,*=,/=,%=) to modify the value of a variable.Use the increment (
++) and decrement (--) operators to change a variable's value by exactly one.Evaluate Java expressions that include compound assignment, increment, and decrement operators.
Translate between standard assignment expressions (e.g.,
x = x + 5;) and their shorthand equivalents (e.g.,x += 5;).
Key Concepts & Java Implementation
The Core Idea
The fundamental concept is combining an arithmetic operation with an assignment. Instead of writing variable = variable + value;, which can feel repetitive, you can use a compound assignment operator to express the same logic in a more compact form: variable += value;. This pattern applies to all major arithmetic operations.
Similarly, the special cases of adding or subtracting exactly one are so frequent (e.g., in counters or loops) that they have their own dedicated operators: the increment operator (++) and the decrement operator (--). These operators provide the shortest possible way to express "add one" or "subtract one."
Syntax & Implementation
These operators work with any numeric primitive data type, such as int and double.
Compound Assignment Operators
An assignment operator is a symbol used to assign a value to a variable. The most basic is the equals sign (=). A compound assignment operator combines an arithmetic operator with the basic assignment operator.
| Operator | Example | Equivalent To |
|---|---|---|
+= | x += 5; | x = x + 5; |
-= | y -= 3; | y = y - 3; |
*= | z *= 2; | z = z * 2; |
/= | a /= 4; | a = a / 4; |
%= | b %= 2; | b = b % 2; |
// Annotated Example: Compound Assignment
public class GameScore {
public static void main(String[] args) {
int score = 100; // Initial score
System.out.println("Initial score: " + score);
// Player gains 50 points
score += 50; // Equivalent to: score = score + 50;
System.out.println("After gaining points: " + score); // Prints 150
// Player loses 25 points
score -= 25; // Equivalent to: score = score - 25;
System.out.println("After losing points: " + score); // Prints 125
// Score is doubled for a bonus round
score *= 2; // Equivalent to: score = score * 2;
System.out.println("After bonus double: " + score); // Prints 250
}
}
Increment and Decrement Operators
These operators are used exclusively for adding or subtracting one from a variable's value.
| Operator | Example | Equivalent To |
|---|---|---|
++ | count++; | count = count + 1; or count += 1; |
-- | lives--; | lives = lives - 1; or lives -= 1; |
Note: These operators can be placed before (prefix) or after (postfix) a variable. This course focuses on the postfix version (variable++), where the variable is used in an expression first and then incremented.
// Annotated Example: Increment and Decrement
public class Inventory {
public static void main(String[] args) {
int itemsInCart = 0; // Start with an empty cart
System.out.println("Items in cart: " + itemsInCart);
// Add an item
itemsInCart++; // Equivalent to: itemsInCart = itemsInCart + 1;
System.out.println("Added an item: " + itemsInCart); // Prints 1
// Add another item
itemsInCart++;
System.out.println("Added another item: " + itemsInCart); // Prints 2
// Remove an item
itemsInCart--; // Equivalent to: itemsInCart = itemsInCart - 1;
System.out.println("Removed an item: " + itemsInCart); // Prints 1
}
}
Tracing & Analysis
Execution Trace
Let's trace the values of variables through a sequence of operations.
Code:
int a = 10;
int b = 20;
a += 5;
b--;
a *= 2;
Trace:
int a = 10;->ais10.int b = 20;->bis20.a += 5;->abecomes10 + 5, soais now15.b--;->bbecomes20 - 1, sobis now19.a *= 2;->abecomes15 * 2, soais now30.
Final Values:a is 30, b is 19.
Analysis
These operators are primarily for programmer convenience and code clarity. In modern Java, they do not provide a significant performance benefit over their longer equivalents, but they are standard practice. Using score++; is universally understood by Java developers to mean "increment the score," making the code's intent clear and concise.
Be mindful of integer division when using /=. For example, int x = 7; x /= 2; will result in x having the value 3, as the decimal part is truncated.
Java Syntax Quick-Reference
+=(Addition assignment): Adds the right-side value to the left-side variable.-=(Subtraction assignment): Subtracts the right-side value from the left-side variable.*=(Multiplication assignment): Multiplies the left-side variable by the right-side value./=(Division assignment): Divides the left-side variable by the right-side value.%=(Modulo assignment): Replaces the left-side variable with the remainder of a division.++(Increment): Increases the value of a numeric variable by one.--(Decrement): Decreases the value of a numeric variable by one.
Core Code Examples & Terminology
Assignment Operator (
=): The operator used to store the value of the expression on its right in the variable on its left.Compound Assignment Operator: An operator that combines an arithmetic operation (like
+or*) with the assignment operator (=) to shorten code.Increment Operator (
++): A unary operator that increases the value of its operand (a variable) by one.Decrement Operator (
--): A unary operator that decreases the value of its operand (a variable) by one.Core Snippet 1 (Addition Assignment):
int total = 50; total += 10; // total is now 60This is a shortcut for
total = total + 10;.Core Snippet 2 (Integer Division Assignment):
int value = 15; value /= 2; // value is now 7This is a shortcut for
value = value / 2;, which performs integer division.Core Snippet 3 (Increment):
int counter = 0; counter++; // counter is now 1This is the most common way to increase a variable's value by one.
Core Skill Check
Code Tracing: What is the final value of
xafter this Java code runs:int x = 4; x *= 3; x--;?xwill be11. (4 * 3is12, then12 - 1is11).Debugging: Identify the logical error in this Java code intended to add 10 to
val:int val = 20; val =+ 10;.The error is using
=+instead of+=. The codeval =+ 10;is valid syntax forval = (+10);, which assigns10toval, overwriting the20. The correct operator isval += 10;.Application: Write a single line of Java code that halves the value of the
doublevariableprice.price /= 2;
Common Misconceptions & Errors
Confusing
=+with+=: A common typo is writingx =+ 5;when you meanx += 5;. The first expression is valid Java that assigns the positive value of5tox, completely replacing its old value. The second correctly adds5tox.Integer Division with
/=: Remember that if you use/=withintvariables, the result will also be anint. Any fractional part of the result is discarded. For example,int x = 10; x /= 4;results inxbeing2, not2.5.Order of Operations: The expression on the right side of a compound operator is fully evaluated before the operation is performed. For example,
x *= 5 + 2;is equivalent tox = x * (5 + 2);, notx = x * 5 + 2;.
Summary
Compound assignment operators (+=, -=, *=, /=, %=) and the increment (++) and decrement (--) operators are fundamental tools in a Java programmer's toolkit. They are not new concepts but rather essential shorthand for the common task of modifying a variable relative to its current value. Using these operators makes code more concise, easier to read, and aligns with professional programming conventions. Understanding that score += 10; is simply a shorter way to write score = score + 10; is the key to mastering their use.