Fiveable

💻AP Computer Science A Unit 1 Review

QR code for AP Computer Science A practice questions

1.3 Expressions and Assignment Statements

💻AP Computer Science A
Unit 1 Review

1.3 Expressions and Assignment Statements

Written by the Fiveable Content Team • Last updated September 2025
Verified for the 2026 exam
Verified for the 2026 examWritten by the Fiveable Content Team • Last updated September 2025

Expressions and output are the building blocks that bring your Java programs to life. Without output, your calculations remain hidden inside the computer. Without expressions, you can only display static text. Together, they create the interactive programs that solve real problems.

Java provides two primary output methods: System.out.print and System.out.println. The difference between them might seem small, but it fundamentally changes how your output appears. Meanwhile, expressions let you perform calculations, manipulate values, and create dynamic results. Understanding how these work together is essential for every Java programmer.

  • Major concepts: System.out.print/println differences, string literals and escape sequences, arithmetic operators and precedence, integer division quirks
  • Why this matters for AP: Every FRQ requires output formatting, MCQs love testing operator precedence, string manipulation appears in FRQ1 frequently
  • Common pitfalls: Forgetting println adds a newline, integer division truncating decimals, modulo with negative numbers
  • Key vocabulary: string literal, escape sequence, operator precedence, integer division, modulo/remainder
  • Prereqs: Basic variable types from Topic 1.2, understanding what a program does

Key Concepts

Pep mascot
more resources to help you study

Output Methods: print vs println

Java gives you two main ways to display output: System.out.print() and System.out.println(). The difference is simple but crucial. Think of print as continuing on the same line, while println hits the enter key after printing.

System.out.print("Hello");
System.out.print("World");
// Output: HelloWorld

System.out.println("Hello");
System.out.println("World");
// Output: Hello
//         World

Here's the strategic approach: use println when you want each piece of information on its own line. Use print when you're building up a single line of output piece by piece.

String Literals and Escape Sequences

A string literal is just text surrounded by double quotes. Seems simple, right? But what if you need to include a quote mark in your string? Or a new line? That's where escape sequences save the day.

The backslash \ is your escape character. It tells Java "the next character is special." The most useful ones are \" for quotes, \n for newline, and \\ for an actual backslash.

System.out.println("She said \"Hello\" to me");
// Output: She said "Hello" to me

System.out.println("Line 1\nLine 2\nLine 3");
// Output: Line 1
//         Line 2
//         Line 3

System.out.println("Path: C:\\Users\\Documents");
// Output: Path: C:\Users\Documents

Arithmetic Operators and Basic Math

Java handles math pretty much like you'd expect, with one major gotcha we'll cover next. The basic operators are + (addition), - (subtraction), * (multiplication), / (division), and % (remainder/modulo).

System.out.println(5 + 3);    // 8
System.out.println(10 - 7);   // 3

System.out.println(4 * 6);    // 24
System.out.println(15.0 / 4); // 3.75
System.out.println(17 % 5);   // 2

The remainder operator % gives you what's left over after division. Think of it like this: 17 divided by 5 is 3 with 2 left over, so 17 % 5 equals 2.

Integer Division: The Silent Truncator

Here's where students lose points on the AP exam. When you divide two integers, Java throws away the decimal part. No rounding, just chopping it off.

System.out.println(7 / 2);     // 3, not 3.5!
System.out.println(10 / 3);    // 3, not 3.333...
System.out.println(1 / 2);     // 0, ouch!

// Fix: make at least one number a double
System.out.println(7.0 / 2);   // 3.5
System.out.println(10 / 3.0);  // 3.333...

This isn't a bug, it's a feature. Sometimes you want integer division (like finding how many full groups you can make). But if you need the decimal, convert at least one number to a double.

Operator Precedence: Who Goes First?

Java follows the same order of operations you learned in math class. Multiplication and division happen before addition and subtraction. Left to right for operators at the same level.

System.out.println(2 + 3 * 4);      // 14, not 20
System.out.println(10 - 6 / 2);     // 7, not 2

System.out.println(8 / 4 * 2);      // 4 (left to right)
System.out.println(15 % 4 + 2);     // 5 (% same level as * and /)

When in doubt, use parentheses. They make your code clearer and guarantee the order you want.

Code Examples

Building Complex Output

Let's combine variables, literals, and expressions to create meaningful output. Notice how we strategically use print vs println.

int score = 95;
int bonus = 10;
System.out.print("Your score: ");
System.out.println(score);
System.out.print("With bonus: ");
System.out.println(score + bonus);
// Output: Your score: 95
//         With bonus: 105

Calculating and Displaying Results

Here's a real problem-solving approach. Break down the calculation, then format the output nicely.

// Calculate average of three test scores
int test1 = 85;
int test2 = 92;
int test3 = 88;

// Step 1: Calculate sum
int sum = test1 + test2 + test3;

// Step 2: Calculate average (watch that integer division!)
double average = sum / 3.0;  // Use 3.0 to force double division

// Step 3: Display results
System.out.println("Test scores: " + test1 + ", " + test2 + ", " + test3);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);

Working with Remainders

The modulo operator is super useful for checking divisibility and extracting digits.

// Check if a number is even
int num = 17;
System.out.print(num + " is ");
if (num % 2 == 0) {
    System.out.println("even");
} else {
    System.out.println("odd");
}

// Extract digits from a number
int value = 256;
int ones = value % 10;        // 6
int tens = (value / 10) % 10; // 5
int hundreds = value / 100;    // 2
System.out.println("Digits: " + hundreds + " " + tens + " " + ones);

Common Errors and Debugging

Missing Quotes in String Literals

This error happens when you forget to close a string. Java gets confused about where the string ends.

// ERROR: unclosed string literal
System.out.println("Hello World);  // Missing closing quote

// CORRECT:
System.out.println("Hello World");

Integer Division Surprises

This sneaky error produces wrong results without any error message. Always check if you're dividing integers when you want a decimal result.

// Problem: calculating percentage
int correct = 17;
int total = 20;
double percent = correct / total * 100;  // Oops! 0 * 100 = 0

// Solution: force double division
double percent = (double)correct / total * 100;  // 85.0

Escape Sequence Errors

Forgetting to escape special characters leads to compile errors or wrong output.

// ERROR: illegal escape character
System.out.println("C:\new\folder");  // \n becomes newline!

// CORRECT: escape the backslashes
System.out.println("C:\\new\\folder");

Concatenation vs Addition

When mixing strings and numbers with +, order matters. Java evaluates left to right.

System.out.println("Sum: " + 3 + 4);     // "Sum: 34" (concatenation)
System.out.println(3 + 4 + " is sum");   // "7 is sum" (addition first)
System.out.println("Sum: " + (3 + 4));   // "Sum: 7" (parentheses force addition)

Practice Problems

Problem 1: Temperature Converter

Write code that converts 86 degrees Fahrenheit to Celsius and displays both values. Formula: C = (F - 32) × 5/9

// Solution:
int fahrenheit = 86;
double celsius = (fahrenheit - 32) * 5.0 / 9.0;  // Use 5.0 and 9.0!

System.out.println(fahrenheit + "°F = " + celsius + "°C");
// Output: 86°F = 30.0°C

Key insight: We use 5.0 / 9.0 to avoid integer division. If we used 5 / 9, we'd get 0!

Problem 2: Time Display

Given total seconds, display it as hours:minutes:seconds format.

int totalSeconds = 7265;

// Solution approach: divide and use remainder
int hours = totalSeconds / 3600;
int minutes = (totalSeconds % 3600) / 60;
int seconds = totalSeconds % 60;

System.out.print("Time: ");
System.out.print(hours + ":");
System.out.print(minutes + ":");
System.out.println(seconds);
// Output: Time: 2:1:5

This demonstrates strategic use of division and modulo. First extract hours, then work with what's left.

Problem 3: Receipt Calculator

Calculate and display a receipt with subtotal, tax, and total.

double item1 = 12.99;
double item2 = 24.50;
double item3 = 8.75;
double taxRate = 0.08;

double subtotal = item1 + item2 + item3;
double tax = subtotal * taxRate;
double total = subtotal + tax;

System.out.println("Receipt");
System.out.println("-------");
System.out.println("Item 1: $" + item1);
System.out.println("Item 2: $" + item2);
System.out.println("Item 3: $" + item3);
System.out.println("Subtotal: $" + subtotal);
System.out.println("Tax: $" + tax);
System.out.println("Total: $" + total);

AP Exam Connections

Multiple Choice Patterns

The MCQ section loves testing operator precedence and integer division. They'll show you an expression and ask for the output. The trick is to work through it step by step, just like we did above.

Common MCQ trap: mixing integer and double division in the same expression. They might give you something like 25 / 4 * 1.0 and ask for the result. Work left to right: 25 / 4 = 6 (integer division!), then 6 * 1.0 = 6.0.

Another favorite: escape sequences in strings. They'll show "Line1\nLine2" and ask how many lines print. Remember each \n creates a new line.

FRQ Applications

FRQ 1 (Methods and Control): You'll definitely need to output results. They often ask you to print formatted output like "The average is: 85.5" or display results of calculations. Master combining literals with expression results.

FRQ 2 (Class Design): Less direct output here, but you might need toString methods that build strings using concatenation. Understanding how to combine different data types into a single string is crucial.

String concatenation with mixed types shows up frequently. Remember that when you concatenate anything with a string, it becomes a string. This is actually useful for displaying numeric results with labels.

Quick Test Tips

For expression questions, write out each step. Don't try to do complex expressions in your head. The AP readers (and multiple choice) care about the exact result, including integer division truncation.

When you see division, immediately check if both operands are integers. This catches most division-related errors. If you need a decimal result, make sure at least one operand is a double.

For output questions, trace through the code line by line. Count newlines carefully. Remember println adds one at the end, print doesn't.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

TermDefinition
additionThe arithmetic operator (+) that combines two numeric values to produce their sum.
arithmetic expressionMathematical expressions consisting of numeric values, variables, and operators that perform calculations.
ArithmeticExceptionAn exception that occurs when attempting to divide an integer by zero.
compound expressionExpressions that use multiple operators to combine numeric values.
divisionThe arithmetic operator (/) that divides one numeric value by another.
doubleA primitive data type used to store real numbers (numbers with decimal points).
escape sequenceA special sequence of characters starting with a backslash that has a special meaning in Java, such as \" for double quote, \\ for backslash, and \n for newline.
intA primitive data type used to store integer values (whole numbers).
integer divisionDivision of two int values that results in only the integer portion of the quotient, discarding any fractional part.
literalThe code representation of a fixed value.
multiplicationThe arithmetic operator (*) that produces the product of two numeric values.
numeric valueNumbers used in expressions, which can be of type int or double.
operatorSymbols that perform operations on numeric values in expressions.
operator precedenceThe rules that determine the order in which operators are evaluated in an expression, with multiplication, division, and remainder evaluated before addition and subtraction.
parenthesesSymbols used to modify operator precedence and control the order of operations in an expression.
remainder operatorThe operator (%) that computes the remainder when one number is divided by another.
string literalA sequence of characters enclosed in double quotes used to create a String object directly in code.
subtractionThe arithmetic operator (-) that finds the difference between two numeric values.
System.out.printA Java method that displays information on the computer display without moving the cursor to a new line after the output.
System.out.printlnA Java method that displays information on the computer display and moves the cursor to a new line after the output.
variableA named storage location in a program that holds a value of a specific data type; the value can change while the program is running.