zuai-logo

Expressions and Assignment Statements

Emily Wilson

Emily Wilson

8 min read

Study Guide Overview

This study guide covers numeric types in Java, including int and double, and basic math operations. It explains the assignment operator, incrementing/decrementing, the modulo operator, and division. It emphasizes the order of operations (PEMDAS) and includes practice problems on basic math, modulo, and AP-style questions. The guide also highlights common mistakes and provides exam tips focusing on integer division and data types.

AP Computer Science A: Expressions and Assignment Statements - The Night Before 🚀

Hey! Let's make sure you're totally ready for tomorrow. This guide will help you nail those tricky questions on expressions and assignment statements. Let's dive in!

1. Numeric Types and Basic Math in Java

Basic Math Operations

Java handles addition, subtraction, and multiplication just like your calculator. Remember to use variables to store results.

java
int a = 1 + 2; // a is 3
double b = 1.0 + 3.5; // b is 4.5
int c = 3 - 5; // c is -2
double d = 24 * 1.0; // d is 24.0
  • Assignment Operator (=): Evaluates the expression on the right and stores the result in the variable on the left.
  • Integer vs. Double:
    • int operations with int result in an int.
    • Operations with at least one double result in a double.

Incrementing and Decrementing

There are multiple ways to add or subtract 1 from a variable:

  • Adding 1:
    • score = score + 1;
    • score += 1;
    • score++;
  • Subtracting 1:
    • score = score - 1;
    • score -= 1;
    • score--;

Modulo Operator (%)

The modulo operator % gives you the remainder of a division. Only works with integers where the divisor (b) is positive.

java
int a = 4 % 2; // a is 0 (4 = 2 * 2 + 0)
int b = 10 % 3; // b is 1 (10 = 3 * 3 + 1)
int c = 3 % 5; // c is 3 (3 = 0 * 5 + 3)
Quick Fact

A smaller number % a larger number always returns the smaller number.

Division

Division can be tricky! Pay close attention to data types.

java
int a = 5 / 2; // a is 2 (integer division)
double b = 5 / 2.0; // b is 2.5 (double division)
  • Integer Division: Returns only the whole number quotient (truncates the decimal).
  • Double Division: Returns the actual quotient as a decimal.

2. Order of Operations

Java follows the standard order of operations (PEMDAS/BODMAS), with modulo included with multiplication and division.

Order of Operations

Memory Aid

PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to...

Question 1 of 10

What is the value of x after the following code executes?

java
int x = 5;
x++;

4

5

6

7