1.5 Compound Assignment Operators
Variables can store the outcome of expressions:
Variables can also use their own existing value to change the value of the variable.
In this case, counter
has an initial value of 0, but you then reassign the value in the second line. The reassignment takes the current value and adds one to it. When you print out the value on the third line, you will see a 1.
There are shortcuts available when performing arithmetic expressions. Consider the following table:
Original | Shortcut | Description |
---|---|---|
counter = counter + 1; | counter++; | Increment a variable by 1 |
counter = counter - 1; | counter–; | Subtract 1 from a variable |
x = x + y | x += y | Adding values to a variable |
x = x - y | x -= y | Subtracting values from a variable |
x = x * y; | x *= y | Multiplying values to a variable |
x = x / y; | x /= y | Dividing values from a variable |
-
Incorrect
Correct
No Answer was selected
Invalid Answer
In Java, the
==
sign in a statement means
A doctor works 12 hours, 14 minutes, and 16 seconds in one shift at a hospital. Convert the total shift time into seconds and display that information.
NOTE: You must use at least ONE compound operator (+=, -=, *=, /=, %=
) to complete this program.
Vocabulary
Term | Definition |
---|---|
Increment | Increase the value of a variable by one. variable++; |
Decrement | Decrease the value of a variable by one. variable–; |
Compound Assignment Operators | Allows programmers to shortcut variable assignments that include the variable being assigned a new value: x = x + y; shortcut: x += y; |