Compound Assignment Operators
Введено
15:00
Использование объектов и методов
Вот две программы Java. В первой отсутствует точка с запятой. Вторая делит семь на два и сохраняет ответ в целочисленной переменной. Компилятор останавливает…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| compound assignment operator/ˈkɒmpaʊnd əˈsaɪnmənt ˈɒpəreɪtə/ | оператор сложного присваивания |
Shorthand for updating
- Updating a variable from itself is so common it has shorthand.
- A compound assignment operator 复合赋值运算符 combines an operation with
=. x += 3;means exactlyx = x + 3;.- The family:
+=,-=,*=,/=,%=.
The five operators
x += 5→ add5tox.x -= 5→ subtract5.x *= 2→ doublex.x /= 2→ halvex(int rules apply).x %= 3→ replacexwithx % 3(the remainder).- Each reads the current value, applies the op, and stores the result back.

Compound assignment operators traced on one variable
Increment and decrement
x++adds1tox(same asx += 1orx = x + 1).x--subtracts1fromx.- These are extremely common in loops to step a counter.
- They change the variable in place — no
=needed.
Same type rules apply
- Compound assignment implicitly converts the result back to the type of the left-hand variable; the ordinary assignment may require an explicit cast.
int x = 7; x /= 2;gives3(int division still truncates).x += 2.5;on anintwould need care — the type ofxdoesn't change.- The shorthand is only shorter; the arithmetic is identical.
Compound assignment converts the result back to the type of the left-hand variable. For int x = 7; x /= 2;, integer division gives 3, not 3.5. With int x = 1;, x += 2.5; compiles and stores 3, while x = x + 2.5; needs an explicit cast. As a statement, x++ adds one to x.
Tracing a counter:
int x = 10;x += 5;→xis15.x *= 2;→xis30.x--;→xis29.x %= 5;→xis4(29 % 5).
Compound assignment operators (+=, -=, *=, /=, %=) update a variable and implicitly convert the result to its type. x++ and x-- add or subtract 1. Integer division in x /= 2 still truncates.
Stepping a counter
Each compound operator updates x in place.
x += 3 is exactly the same as...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Compound assignment is shorthand for x = x + 3.
int x = 10; x += 5; x *= 2; What is x?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
10 → 15 → 30.
int x = 7; x /= 2; What is x?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
int division truncates: 7/2 = 3.
x++ has the same effect as...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
x++ adds 1, same as x += 1.
For an int variable x, x /= 2 uses integer division and truncates the result toward zero.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Both operands are int, so integer division truncates toward zero.
Что пошло не так? Это увидит только команда сайта.