Compound Assignment Operators

Part of: Primitive Types

Updating a Variable Programs constantly update variables based on their current value, adding to a running total, decreasing a counter, scaling a number. The long form is: This reads the old score, adds 5, and stores the result back. Because this pattern is so common, Java offers compound assignment operators that do the same thing more concisely. The Compound Operators Each combines an arithmetic operator with =: - += add and assign - -= subtract and assign - = multiply and assign - /= divide and assign - %= mod and assign x += 5 is exactly equivalent to x = x + 5. The same type rules apply: x /= 5 uses integer division when x is an int. Increment and Decrement For adding or subtracting exactly 1, Java provides shortcuts: - x++ increment by 1 (same as x += 1) - x-- decrement by 1 (same as x -= 1) These appear constantly in loops to advance a counter. Compound Operators with Doubles Compound operators work on doubles too, following double arithmetic: Why They Matter Compound assignment makes accumulation code shorter and clearer, and ++/-- are the standard way to step counters. They are heavily used in loops and array processing later in the course. Just remember they inherit the s

Challenge: Running Total