1.3

Expressions & Assignment

AP Computer Science A

Arithmetic operators

Integer division — THIS IS CRITICAL

java
int result = 7 / 2;    // result = 3 (not 3.5!)
int result2 = 1 / 3;   // result2 = 0 (not 0.333...)
int result3 = -7 / 2;  // result3 = -3 (truncates toward zero)
java
double result = 7.0 / 2;    // result = 3.5
double result2 = 7 / 2.0;   // result2 = 3.5
double result3 = (double) 7 / 2;  // result3 = 3.5 (casting)

The modulo operator (%)

java
10 % 3   // → 1   (10 ÷ 3 = 3 remainder 1)
15 % 5   // → 0   (15 ÷ 5 = 3 remainder 0)
7 % 10   // → 7   (7 ÷ 10 = 0 remainder 7)

Common uses of %

Operator precedence

java
int result = 2 + 3 * 4;      // 2 + 12 = 14 (NOT 20)
int result2 = (2 + 3) * 4;   // 5 * 4 = 20 (parentheses change order)
int result3 = 10 - 4 / 2;    // 10 - 2 = 8
int result4 = 10 % 3 + 2;    // 1 + 2 = 3

The assignment operator (=)

java
int x = 5;   // x is now 5
x = x + 1;   // x is now 6 (take old x, add 1, store back in x)

String concatenation with +

java
String first = "Hello";
String last = "World";
System.out.println(first + " " + last);  // "Hello World"

Mixing Strings and numbers

java
System.out.println("Score: " + 95);           // "Score: 95"
System.out.println("2 + 3 = " + 2 + 3);       // "2 + 3 = 23" (!)
System.out.println("2 + 3 = " + (2 + 3));     // "2 + 3 = 5"
java
int age = 17;
System.out.println("I am " + age + " years old.");  // "I am 17 years old."

Tracing code step by step

java
int a = 10;
int b = 3;
int c = a / b;         // c = 3 (integer division)
int d = a % b;         // d = 1 (remainder)
double e = a / b;      // e = 3.0 (int division happens FIRST, then stored as double)
double f = (double) a / b;  // f = 3.333... (cast forces real division)

AP Exam Tips

Common Mistakes

Key Vocabulary