Verified for the 2025 AP Computer Science A exam•Citation:
In Java programming, assignment statements are fundamental building blocks that allow us to store values in variables. This section explores how assignment works, the different types of assignment operators available in Java, and best practices for using them effectively. Understanding how to properly assign and manipulate values is essential for writing clear, efficient code.
The assignment operator (=
) stores the value of the right-side expression into the variable on the left:
int score = 95; // Assigns the value 95 to the variable score
When Java executes an assignment statement:
int a = 5; // a gets 5 int b = a * 2; // b gets 10 a = b; // a is now 10
Java provides shorthand operators that combine arithmetic and assignment:
| Operator | Example | Equivalent To | |----------|----------|----------------| | += | x += 5; | x = x + 5; | | -= | x -= 5; | x = x - 5; | | *= | x *= 5; | x = x * 5; | | /= | x /= 5; | x = x / 5; | | %= | x %= 5; | x = x % 5; |
Example:
int count = 10; count += 5; // count is now 15 count *= 2; // count is now 30 count /= 3; // count is now 10 count -= 5; // count is now 5 count %= 3; // count is now 2
The increment operator (++
) and decrement operator (--
) add 1 or subtract 1 from a variable's value:
int counter = 5; counter++; // counter is now 6 counter--; // counter is now 5
Note: In this course and on the AP Exam, you'll only use these operators as standalone statements (not in prefix form or inside other expressions).
Multiple variables can be assigned in the same statement:
int x, y, z; x = y = z = 0; // All three variables get value 0
The value being assigned must be compatible with the variable's type:
Same Type: Direct assignment
int a = 5; // int to int double d = 2.5; // double to double
Widening Conversion: Automatically done by Java
int i = 100; double d = i; // int to double (100.0)
Narrowing Conversion: Requires explicit cast
double pi = 3.14159; int approx = (int)pi; // Must use cast - loses precision (3)
Adding to a running total:
int sum = 0; sum += 10; // sum is 10 sum += 20; // sum is 30 sum += 30; // sum is 60
Keeping track of occurrences:
int count = 0; // When an event occurs: count++;
Exchanging values between two variables:
int a = 5; int b = 10; // Swapping requires a temporary variable int temp = a; a = b; b = temp; // Now a is 10 and b is 5
Remember to pay attention to the types involved in your assignments and be careful with operations that might change type. An expression's result must be compatible with the variable to which it's being assigned. Using assignment statements correctly will help you write code that's both efficient and easy to read.