Assignment and compound assignment
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)The assignment operator = stores a value in a variable. Compound assignment operators like += and -= change a variable using its own old value, in a shorter way.
= stores a value
You have 75 marks, and the teacher adds 5 grace marks. = works out its right side first, then stores the answer in the variable on its left.
int marks = 75;marks = marks + 5; // 75 + 5 is 80, then 80 is storedIn maths, = means "is equal to", so marks = marks + 5 looks wrong. In Java it means "store". To ask whether two values are equal, Java uses ==, which Comparison operators (opens in a new tab) covers.
Shortcut operators: +=, -=, *=, /=, %=
A UPI app changes your balance all day, and balance = balance - 350; repeats the name each time.
- Line 1: same as: variable = variable op value;
A compound assignment operator does both jobs at once: balance -= 350; means exactly balance = balance - 350;.
Example 1 · /= and %= with boxes of pens
public class Pens { public static void main(String[] args) { int pens = 47; int boxes = pens; boxes /= 10; pens %= 10; System.out.println(boxes + " boxes, " + pens + " loose pens"); }}4 boxes, 7 loose pens
What this code does
boxesstarts as a copy of 47.boxes /= 10stores 47 / 10, which is 4 withintvalues.pens %= 10stores the remainder of 47 / 10, which is 7.
There is one for each arithmetic operator: +=, -=, *=, /= and %=. Step through the program below and watch the values change line by line.
Trace the code
Watch the UPI balance change
Variables
- balance
- 1500
Output
(nothing printed yet)Line 3balance starts at Rs 1500.
+=, not + =.+= with text, and a hidden cast
A greeting app builds a message piece by piece: first "Happy", then " Diwali".
+= joins text too. On numbers it hides a cast: it converts the answer back to the variable's type.
Example 2 · += with text and the hidden cast
public class HiddenCast { public static void main(String[] args) { String wish = "Happy"; wish += " Diwali"; System.out.println(wish); int marks = 70; marks += 2.7; System.out.println(marks); }}Happy Diwali 72
What this code does
wish += " Diwali";joins the new text to the end ofwish.marks += 2.7;works out 72.7, then converts it back toint, so 72 is stored with no error or warning. The decimal is dropped, not rounded.- The long form
marks = marks + 2.7;does not even compile, because adoublecannot go into anintwithout a cast.
This is a language rule, not a style to copy. To keep the decimals, use a double variable, as in Type conversion and casting (opens in a new tab).
Next step
Check your understanding
9 quick questions