Please enable JavaScript to use CodeHS

Chapter 1

Primitive Types

1.5 Compound Assignment Operators

Evaluating What is Stored in a Variable

Variables can store the outcome of expressions:

int mysteryNum = (4 + 6 * (2 * 3) - 2);
Java

Variables can also use their own existing value to change the value of the variable.

int counter = 0;
counter = counter + 1;
System.out.println(counter);
Java

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.

Arithmetic Shortcuts

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

All Functions Calculator

Increase/Decrease by 1

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    In Java, the ==sign in a statement means

Exercise: Work Shift

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;