Working with Assignment and Compound Assignment Operators in Java
Course: Core Java Training
Topic: Working with Assignment and Compound Assignment Operators
Course Link: Core Java Training Course
Demo Link: Register for a Free Course Demo
Training Provider: JustAcademy
1. Introduction to Assignment Operators
Assignment operators are fundamental operators in Java that store values in variables. They allow programmers to initialize variables, update existing values, perform calculations, and modify data efficiently. The simple assignment operator is =, while compound assignment operators combine an operation with assignment.
For example, total = 100; assigns the value 100 to the variable total. If the variable needs to be increased by 20, you can write total = total + 20; or use the shorter compound assignment expression total += 20;.
Java defines assignment behavior in its language specification, including how compound assignments perform an operation and convert the result to the type of the variable receiving it.
Learning Objectives
- Understand the purpose and syntax of assignment operators.
- Use the simple assignment operator (
=) correctly.
- Understand arithmetic compound assignment operators.
- Work with bitwise and shift compound assignment operators.
- Understand type conversion in compound assignments.
- Identify common errors and write clear, maintainable Java code.
2. What Is the Assignment Operator?
The simple assignment operator = assigns the value of an expression on the right-hand side to a variable on the left-hand side.
Syntax
variable = expression;
Here:
- Left-hand side (LHS): The variable that receives the value.
- Right-hand side (RHS): The value or expression being evaluated.
- Assignment operator: The
= symbol that stores the resulting value.
Example
public class AssignmentExample {
public static void main(String[] args) {
int age;
age = 25;
double salary = 35000.50;
String name = "Aarav";
boolean isActive = true;
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Name: " + name);
System.out.println("Active: " + isActive);
}
}
Output
Age: 25
Salary: 35000.5
Name: Aarav
Active: true
Explanation: The assignment operator stores compatible values in variables. A variable can be declared and initialized in one statement, such as int age = 25;, or declared first and assigned later, as long as Java's definite-assignment rules are satisfied.
3. Important Rules for Simple Assignment
- The left-hand side must identify a valid assignable variable, field, or array element.
- The right-hand expression must be assignment-compatible with the target variable's type.
- A local variable must be initialized before its value is read.
- A variable declared with
final cannot be reassigned after its permitted initialization.
- Assignment expressions produce the value that was assigned, which means assignments can be chained.
Example: Assigning Values to Variables
int firstNumber = 10;
int secondNumber = 20;
firstNumber = secondNumber;
System.out.println(firstNumber);
Output:
20
The value of secondNumber is copied into firstNumber. Changing one primitive variable afterward does not automatically change the other.
4. Assigning the Result of an Expression
The right-hand side can contain arithmetic operations, method calls, or other expressions, provided the resulting value is compatible with the target type.
public class ExpressionAssignment {
public static void main(String[] args) {
int price = 120;
int quantity = 3;
int total = price * quantity;
int discount = 50;
int finalAmount = total - discount;
System.out.println("Total: " + total);
System.out.println("Final amount: " + finalAmount);
}
}
Output:
Total: 360
Final amount: 310
Java evaluates the right-hand expression and stores its result in the variable on the left.
5. Chained Assignment
Java allows multiple assignments in one expression. Assignment operators associate from right to left, so a = b = c; behaves like a = (b = c);.
public class ChainedAssignment {
public static void main(String[] args) {
int a, b, c;
a = b = c = 50;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Output:
50
50
50
Explanation: The value 50 is assigned to c, the resulting value is assigned to b, and then that value is assigned to a. Although chaining is valid, separate assignments can be easier to read when variables have different meanings.
6. What Are Compound Assignment Operators?
Compound assignment operators combine an operation with an assignment. Instead of repeating the variable name on both sides of an expression, you can use a shorter operator.
For example:
int score = 10;
// Standard assignment with addition
score = score + 5;
// Equivalent compound assignment
score += 5;
The first statement changes score from 10 to 15. The second statement then changes it from 15 to 20.
General Syntax
variable operator= expression;
Compound assignments are useful for counters, running totals, calculations, bit manipulation, and other situations where a variable is updated using its existing value.
7. Complete List of Java Assignment Operators
| Operator |
Name |
Example |
Meaning |
= |
Simple assignment |
x = 10; |
Assigns 10 to x. |
+= |
Addition assignment |
x += 5; |
Adds 5 to x. |
-= |
Subtraction assignment |
x -= 3; |
Subtracts 3 from x. |
*= |
Multiplication assignment |
x *= 2; |
Multiplies x by 2. |
/= |
Division assignment |
x /= 4; |
Divides x by 4. |
%= |
Remainder assignment |
x %= 3; |
Stores the remainder after division. |
&= |
Bitwise AND assignment |
x &= mask; |
Applies bitwise AND. |
|= |
Bitwise OR assignment |
x |= mask; |
Applies bitwise OR. |
^= |
Bitwise XOR assignment |
x ^= mask; |
Applies bitwise XOR. |
<<= |
Left-shift assignment |
x <<= 1; |
Shifts bits to the left. |
>>= |
Signed right-shift assignment |
x >>= 1; |
Shifts bits right while preserving the sign bit. |
>>>= |
Unsigned right-shift assignment |
x >>>= 1; |
Shifts bits right while filling with zeros. |
Java has 12 assignment operators in this list: the simple assignment operator and 11 compound assignment operators.
8. Addition Assignment Operator (+=)
The += operator adds a value to the current value of a variable and stores the result back in that variable.
Syntax
variable += value;
Equivalent Expression
variable = variable + value;
Example
public class AdditionAssignment {
public static void main(String[] args) {
int balance = 1000;
balance += 250;
System.out.println("After deposit: " + balance);
balance += 150;
System.out.println("After second deposit: " + balance);
}
}
Output:
After deposit: 1250
After second deposit: 1400
Practical use: Adding deposits to a bank balance, accumulating marks, and calculating a running total.
Using += with Strings
Java also supports += for string concatenation. When the left-hand variable is a String, the operator combines the existing string with the right-hand value and stores the resulting string.
String message = "Hello";
message += " Java";
message += " Learners";
System.out.println(message);
Output:
Hello Java Learners
9. Subtraction Assignment Operator (-=)
The -= operator subtracts a value from the current value of a variable and stores the result.
public class SubtractionAssignment {
public static void main(String[] args) {
int inventory = 100;
inventory -= 15;
System.out.println("Remaining: " + inventory);
inventory -= 20;
System.out.println("Remaining: " + inventory);
}
}
Output:
Remaining: 85
Remaining: 65
Practical use: Reducing product inventory, deducting expenses, or decreasing the number of available seats.
10. Multiplication Assignment Operator (*=)
The *= operator multiplies the current variable value by another value and stores the result.
public class MultiplicationAssignment {
public static void main(String[] args) {
int number = 5;
number *= 2;
System.out.println(number);
number *= 3;
System.out.println(number);
}
}
Output:
10
30
Practical use: Applying scale factors, multiplying quantities, and calculating repeated growth. Be aware that integer overflow can occur if the result exceeds the range of the integer type.
11. Division Assignment Operator (/=)
The /= operator divides the current variable value by another value and stores the quotient.
public class DivisionAssignment {
public static void main(String[] args) {
int amount = 100;
amount /= 4;
System.out.println(amount);
double price = 99.0;
price /= 2;
System.out.println(price);
}
}
Output:
25
49.5
Important: When both operands are integral types, Java performs integer division. For example, 7 /= 2 is not a valid statement by itself, but if an integer variable contains 7, applying value /= 2; stores 3. A divisor of zero causes ArithmeticException when the division is integral. Floating-point division follows different rules.
12. Remainder Assignment Operator (%=)
The %= operator calculates the remainder after division and stores it back in the variable.
public class RemainderAssignment {
public static void main(String[] args) {
int number = 17;
number %= 5;
System.out.println("Remainder: " + number);
int count = 28;
count %= 10;
System.out.println("Last digit: " + count);
}
}
Output:
Remainder: 2
Last digit: 8
Practical use: Checking divisibility, cycling through indexes, and extracting the last digit of a non-negative integer.
13. Bitwise Compound Assignment Operators
Bitwise compound assignment operators perform logical operations on the individual bits of integral values, such as byte, short, int, and long. They are useful for flags, masks, low-level programming, and compact data representations.
13.1 Bitwise AND Assignment (&=)
The &= operator keeps a bit set to 1 only when the corresponding bits of both operands are 1.
int value = 12; // Binary: 1100
value &= 10; // Binary: 1010
System.out.println(value);
Output:
8
The operation is 1100 & 1010 = 1000, which equals 8 in decimal.
13.2 Bitwise OR Assignment (|=)
The |= operator sets a bit to 1 if either corresponding bit is 1.
int value = 12; // Binary: 1100
value |= 10; // Binary: 1010
System.out.println(value);
Output:
14
The operation is 1100 | 1010 = 1110, which equals 14 in decimal.
13.3 Bitwise XOR Assignment (^=)
The ^= operator sets a bit to 1 when the corresponding bits differ.
int value = 12; // Binary: 1100
value ^= 10; // Binary: 1010
System.out.println(value);
Output:
6
The operation is 1100 ^ 1010 = 0110, which equals 6 in decimal.
14. Shift Compound Assignment Operators
Shift assignment operators move the bits of an integral value left or right. They are used in bit manipulation, encoding, and certain performance-sensitive calculations. Their behavior depends on the signedness and width of the left operand.
14.1 Left-Shift Assignment (<<=)
The <<= operator shifts bits left and fills the vacated low-order bits with zeros. For positive values, shifting left by one often corresponds to multiplying by two when the result remains within the type's range.
int value = 5; // Binary: 0101
value <<= 1;
System.out.println(value);
Output:
10
14.2 Signed Right-Shift Assignment (>>=)
The >>= operator shifts bits right while extending the sign bit. This helps preserve the sign of signed integer values.
int value = 20;
value >>= 2;
System.out.println(value);
Output:
5
14.3 Unsigned Right-Shift Assignment (>>>=)
The >>>= operator shifts bits right and fills the high-order positions with zeros. Unlike >>=, it does not extend the sign bit. The distinction is particularly noticeable for negative integers.
int value = -8;
value >>>= 1;
System.out.println(value);
Output:
2147483644
Note: Java's int type uses 32 bits. When a negative int is shifted using >>>, the leading zeros can produce a large positive result.
15. Compound Assignment and Type Conversion
One important difference between simple assignment and compound assignment is how Java handles the result type. A compound assignment implicitly converts the operation's result back to the type of the left-hand variable. This can allow code that would otherwise require an explicit cast.
Example with a short Variable
public class CompoundTypeConversion {
public static void main(String[] args) {
short number = 10;
number += 5.8;
System.out.println(number);
}
}
Output:
15
Explanation: The addition is evaluated using numeric promotion, producing a floating-point result of 15.8. The compound assignment converts that result back to short, discarding the fractional part and storing 15.
By contrast, this statement does not compile:
short number = 10;
number = number + 5;
The expression number + 5 has type int because arithmetic with a short promotes it to int. A narrowing conversion is needed before assigning the result to short.
short number = 10;
number = (short) (number + 5);
This version compiles because the cast explicitly converts the result to short.
Type Conversion Comparison
| Code |
Valid? |
Reason |
int x = 10; x += 2.5; |
Yes |
The compound assignment converts the result to int, storing 12. |
int x = 10; x = x + 2.5; |
No |
The expression produces a double, which cannot be assigned to int without a cast. |
long x = 100L; x *= 2; |
Yes |
The result is stored in the long variable. |
short x = 3; x += 4.6; |
Yes |
The result is converted back to short, storing 7. |
Implicit conversion in compound assignments can be convenient, but it can also cause precision loss or overflow. Use explicit casts and clear calculations when the conversion might surprise another developer.
16. Difference Between Simple and Compound Assignment
| Feature |
Simple Assignment |
Compound Assignment |
| Operator |
= |
+=, -=, *=, and others |
| Purpose |
Stores a value. |
Performs an operation and stores the result. |
| Existing value |
Not necessarily used. |
Usually used in the operation. |
| Type conversion |
Must satisfy assignment compatibility; narrowing may need a cast. |
Result is converted to the type of the left-hand variable. |
| Example |
count = count + 1; |
count += 1; |
| Readability |
Can make the full operation explicit. |
Can make repeated updates more concise. |
17. Evaluation Order and Single Evaluation
Java evaluates the left-hand operand of an assignment before the right-hand operand according to the language's evaluation rules. For compound assignments, the left-hand side is evaluated only once. This matters when the left-hand side contains an array access or another expression with side effects.
Example: Updating an Array Element
int[] numbers = {10, 20, 30};
int index = 1;
numbers[index] += 5;
System.out.println(numbers[index]);
Output:
25
The value at index 1 is read, increased by 5, and stored back into that array element.
For complex expressions, avoid combining multiple side effects in a single statement. Clear, separate statements are generally easier to understand and debug.
18. Assignment Expressions as Values
An assignment expression produces the value that was assigned. This behavior allows chaining and can also be used in other expressions. However, placing assignments inside larger expressions can make code harder to read.
int a;
int b;
System.out.println(a = 10);
System.out.println(b = a + 5);
Output:
10
15
The first print statement assigns 10 to a and prints the resulting value. The second assigns 15 to b and prints it. For everyday application code, assigning on a separate line is often clearer.
19. Practical Example: Updating a Shopping Cart
This example demonstrates several assignment operators in a realistic calculation involving a product price, quantity, discount, and final amount.
public class ShoppingCart {
public static void main(String[] args) {
double price = 250.0;
int quantity = 2;
double discount = 0.0;
double total = price * quantity;
discount += 50.0;
total -= discount;
System.out.println("Price per item: " + price);
System.out.println("Quantity: " + quantity);
System.out.println("Discount: " + discount);
System.out.println("Final total: " + total);
}
}
Output
Price per item: 250.0
Quantity: 2
Discount: 50.0
Final total: 450.0
Explanation
double total = price * quantity; calculates the original total.
discount += 50.0; adds a discount to the current discount.
total -= discount; subtracts the discount from the total.
In a real shopping application, currency calculations should be designed carefully to avoid floating-point rounding issues. For many financial applications, using integer minor units or BigDecimal is more appropriate than using double.
20. Common Mistakes and Troubleshooting
| Mistake |
Problem |
Correction |
Using == instead of = |
== compares values or references; it does not assign a value. |
Use = when assigning. |
| Using an uninitialized local variable |
Java reports that the variable might not have been initialized. |
Assign a value before reading it. |
| Assigning an incompatible type |
A compile-time type error occurs. |
Use a compatible value or a deliberate conversion. |
| Expecting integer division to preserve decimals |
Fractional parts are discarded in integer division. |
Use floating-point operands if a fractional result is required. |
| Ignoring narrowing in compound assignments |
Decimal fractions may be discarded, or values may overflow. |
Check ranges and conversions before storing the result. |
| Dividing an integer by zero |
Java throws ArithmeticException. |
Validate the divisor before division. |
| Updating a final variable |
Reassignment is rejected by the compiler. |
Use a non-final variable if the value must change. |
| Overusing chained assignments |
Complex statements can be difficult to maintain. |
Prefer separate statements when clarity improves. |
21. Best Practices
- Choose meaningful variable names such as
totalPrice, remainingStock, and studentScore.
- Use compound assignment when it makes a simple update easier to read.
- Use parentheses or separate statements when an expression could be confusing.
- Be careful with integer overflow, especially when multiplying or shifting values.
- Understand how numeric promotion and narrowing conversions affect the result.
- Validate divisors before performing division or remainder operations.
- Use bitwise operators only when bit-level operations are appropriate.
- Avoid mixing assignments with multiple side effects in a single complex expression.
- Compile and run small examples to verify your understanding of operator behavior.
22. Practice Exercises
Exercise 1: Basic Assignment
Declare two integer variables, assign values to them, and copy the value of the first variable into the second. Print both variables.
Exercise 2: Compound Arithmetic
Create a variable named score initialized to 100. Apply +=, -=, *=, and /= in separate steps. Print the result after every operation.
Exercise 3: Remainder
Initialize an integer variable with 47. Use %= with 10 and explain why the result is 7.
Exercise 4: Type Conversion
Declare a short variable initialized to 5. Add 3.7 using compound assignment. Predict the result and explain the conversion.
Exercise 5: Bitwise Operators
Use &=, |=, and ^= with the values 12 and 10. Write the binary representation of each result.
Exercise 6: Shopping Cart
Create a program that calculates a total price, adds a delivery charge using +=, and subtracts a discount using -=. Print the final amount.
23. Interview Questions and Answers
Q1. What is an assignment operator in Java?
An assignment operator stores a value in a variable. The simplest assignment operator is =.
Q2. What is a compound assignment operator?
A compound assignment operator performs an operation on a variable's existing value and stores the result back in the same variable. Examples include +=, -=, and *=.
Q3. What is the difference between = and ==?
= assigns a value, while == compares primitive values or checks reference equality for objects.
Q4. What does x += 5; mean?
It adds 5 to the current value of x and stores the result back in x. For an ordinary variable, this is broadly equivalent to x = x + 5;, with compound-assignment conversion and evaluation rules applying.
Q5. Why can shortValue += 5; compile when shortValue = shortValue + 5; does not?
Arithmetic involving a short and an int normally produces an int. Compound assignment implicitly converts the result back to the left-hand variable's type, while the simple assignment requires the conversion to be explicit.
Q6. What does the %= operator do?
It calculates the remainder after division and stores the remainder in the variable.
Q7. Can += be used with Strings?
Yes. When the left-hand variable is a String, += performs string concatenation and assigns the combined result back to the variable.
Q8. What happens when an integer variable is divided by zero using /=?
Java throws ArithmeticException for integer division by zero, and the assignment does not complete.
Q9. What is the purpose of &= and |=?
&= performs bitwise AND and stores the result; |= performs bitwise OR and stores the result.
Q10. What does >>>= do?
It performs an unsigned right shift, filling the high-order bits with zeros, and stores the result back in the variable.
Q11. Can a final variable be updated with a compound assignment operator?
No. A variable declared final cannot be reassigned after it has been initialized, so a compound assignment to an already initialized final variable is a compile-time error.
Q12. Why should compound assignments be used carefully?
They can implicitly narrow the result to the target type, potentially losing precision or causing overflow. Developers should check the variable type and expected range.
24. Quick Revision Checklist
- Understand that
= assigns a value to a variable.
- Remember that assignment expressions associate from right to left.
- Know the arithmetic compound operators:
+=, -=, *=, /=, and %=.
- Recognize bitwise operators:
&=, |=, and ^=.
- Recognize shift operators:
<<=, >>=, and >>>=.
- Understand that compound assignments convert the result to the target variable's type.
- Check for division by zero, narrowing, and overflow.
- Use simple and readable expressions in production code.
25. Official Learning Resources
26. Conclusion
Assignment and compound assignment operators are essential tools for storing values and updating data in Java. The simple assignment operator = stores a value, while compound operators combine arithmetic, bitwise, or shift operations with assignment. Understanding their syntax, evaluation order, and type-conversion rules helps prevent common programming errors and makes Java code more readable and reliable.
To strengthen your understanding, practise writing small programs that update counters, calculate totals, manipulate bits, and convert numeric values. For more structured learning, explore the Core Java Training Course, visit the JustAcademy website, or register for a course demo.