APrep Open the app

AP Computer Science A · Unit 1: Using Objects & Methods

1.3 Expressions and Assignment Statements

Variables and Assignment

A variable stores a value in memory, and must be declared with a data type before use (e.g., `int x;`). The assignment operator (=) stores the value on the right into the variable on the left. Example: `x = 5;` assigns 5 to x. Reassigning a variable overwrites its previous value.

Arithmetic Expressions

Java's arithmetic operators are +, -, *, /, % (modulo, gives remainder). Operator precedence follows math rules: `*`, `/`, `%` before `+`, `-`, evaluated left to right; parentheses override order. Integer division truncates decimals (7/2 = 3), while dividing with a double gives a decimal result (7.0/2 = 3.5).

Compound Assignment & Type Rules

Compound assignment operators like `+=`, `-=`, `*=`, `/=` combine an operation with assignment (`x += 3` means `x = x + 3`). When mixing int and double in an expression, Java promotes the result to double. Assigning a double to an int without casting causes a compile error, since it risks losing data.

Key terms

Assignment operator (=)
Stores the value on the right side of the operator into the variable on the left side.
Integer division
Division between two ints truncates any decimal remainder (e.g., 7/2 = 3).
Modulo operator (%)
Returns the remainder of a division operation (e.g., 10 % 3 = 1).
Compound assignment operator
Combines an operation with assignment, like += , -=, *=, /= (e.g., x += 2 means x = x + 2).
Operator precedence
Order in which operations are evaluated: *, /, % before +, -, with parentheses overriding default order.

Try an AP-style question

What is the value of 17 % 5?

  1. 3.4
  2. 12
  3. 2
  4. 3
Show the answer

C. Remainder.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 1.3 free in APrep