AP COMPUTER SCIENCE A • USING OBJECTS AND METHODS

Expressions and Output()

Master how Java evaluates expressions and displays results using System.out.print and println.

Historical Context & Motivation

Every programming language must solve two fundamental problems: how to compute values and how to present those values to the user. In the earliest days of computing, programmers communicated with machines through punched cards and toggle switches, but even then the concept of an expression—a combination of values, operators, and variables that the machine evaluates to produce a result—was central. As languages evolved from assembly to high-level abstractions, expressions became richer and output mechanisms grew more sophisticated, culminating in the strongly typed, object-oriented approach that Java adopts today.

1957
FORTRAN's WRITE Statement
IBM's FORTRAN introduced WRITE and PRINT statements, giving programmers a structured way to evaluate arithmetic expressions and send computed results to a line printer.
1972
C's printf()
The C language popularized formatted output via printf(), introducing format specifiers that let programmers control how expressions appear—concepts that strongly influenced Java's I/O design.
1995
Java's System.out.println()
James Gosling and the Sun Microsystems team released Java 1.0, featuring System.out as a PrintStream object with print() and println() methods—an object-oriented approach to console output.
2004
AP Computer Science A Adopts Java
The College Board switched the AP Computer Science A exam from C++ to Java, making System.out.print() and System.out.println() staple topics tested every year on both the multiple-choice and free-response sections.

Understanding how Java evaluates expressions—arithmetic, string concatenation, and method calls—and how it renders those results to the console is not merely academic trivia. These skills form the foundation upon which every subsequent AP Computer Science A topic is built: from control flow to object construction. The central question this lesson addresses is: How does Java transform a written expression into a displayed result, and what rules govern evaluation order, type promotion, and string concatenation along the way?

Core Principles & Definitions

Before diving into syntax, it is essential to establish the vocabulary that the AP exam expects you to know fluently. Java treats every computation as an expression—a construct that evaluates to a single value of a specific type. Expressions can be as simple as a literal integer or as complex as a chain of method calls. The result of an expression can be stored in a variable, passed as an argument, or sent directly to the console using System.out.print() or System.out.println().

1

Expression

A combination of literals, variables, operators, and/or method calls that Java evaluates to produce a single value. Examples: 3 + 4, "Hi" + name, Math.abs(-5).
2

Operator Precedence

Java evaluates operators in a defined order: parentheses first, then multiplication/division/modulus (left to right), then addition/subtraction (left to right). This mirrors standard mathematical convention.
3

String Concatenation

When the + operator has at least one String operand, Java converts the other operand to a String and joins them. Evaluation proceeds left to right, so 1 + 2 + "x" yields "3x".
4

System.out.print() vs println()

print() outputs text and keeps the cursor on the same line. println() outputs text and then advances the cursor to the beginning of the next line. Both accept any expression as an argument.
5

Integer vs Double Division

Dividing two ints performs integer (truncating) division: 7 / 2 yields 3. If either operand is a double, the result is a double: 7.0 / 2 yields 3.5.
KEY TAKEAWAY
Think of an expression like a recipe instruction that the Java runtime follows to produce one dish (a single value). System.out.println() is the serving window: it does not cook anything itself; it merely presents whatever the kitchen (the expression evaluator) has prepared. Understanding this separation—computation versus display—is the key to predicting what Java will print.

Visual Explanation: Expression Evaluation Flow

The following diagram traces how Java evaluates the expression inside System.out.println(1 + 2 + "abc" + 3 + 4) step by step, from left to right, illustrating the critical moment when arithmetic addition switches to string concatenation.

The violet boxes show arithmetic operations between two ints, the pink boxes mark the moment a String operand triggers concatenation, and the green boxes display intermediate results. Notice that once a String appears, all subsequent + operations become concatenation—this is the most commonly tested trap on the AP exam.

The critical insight from this diagram is that Java does not scan the entire expression for Strings before it begins evaluating. It processes each + operator strictly from left to right, and the decision between arithmetic addition and string concatenation is made at each individual operator based solely on the types of the two operands present at that point. This is why 1 + 2 + "abc" yields "3abc" rather than "12abc": the first + sees two ints and performs addition, and only the second + encounters a String.

How Expressions and Output Work in Java

Arithmetic Expressions and Type Rules

Java's arithmetic operators—+, -, *, /, and %—follow the same precedence hierarchy as standard mathematics. Multiplication, division, and modulus are evaluated before addition and subtraction, and parentheses override the default order. Within the same precedence level, operators associate left to right. The type promotion rule states that if either operand of a binary arithmetic operator is a double, the other operand is automatically promoted to double before the operation is performed.

INTEGER DIVISION
7 / 2 → 3 (truncation toward zero, not rounding)
When both operands are int, Java discards the fractional part. To get a double result, cast at least one operand: (double) 7 / 2 → 3.5.
MODULUS OPERATOR
7 % 2 → 1 (remainder after integer division)
The modulus operator % returns the remainder. It is frequently tested in AP problems involving even/odd checks (n % 2 == 0) and digit extraction (n % 10).

String Concatenation Rules

The + operator in Java is overloaded: it performs arithmetic addition when both operands are numeric, but it performs string concatenation when at least one operand is a String. In the concatenation case, the non-String operand is implicitly converted to its String representation (e.g., the int 42 becomes "42") before the two strings are joined. Because + is left-associative, the types of the operands at each step determine whether addition or concatenation occurs, which is why identical expressions can produce dramatically different outputs depending on where a String literal appears.

CONCATENATION RULE
String + any → String any + String → String
Once a String is produced at any point in a left-to-right chain of + operations, every subsequent + in that chain becomes concatenation. Use parentheses to force arithmetic first: "sum: " + (3 + 4) produces "sum: 7".

print() vs. println()

Both System.out.print() and System.out.println() first evaluate their argument expression to a single value, then convert that value to a String, and finally write the characters to the console. The only behavioral difference is that println() appends a newline character (\n) after the output, advancing the cursor to the next line, whereas print() leaves the cursor immediately after the last character. Calling System.out.println() with no argument simply outputs a blank line.

Detailed Breakdown: Output Behavior & Escape Sequences

The left panel shows how consecutive print() calls produce output on a single line, while the right panel shows how println() forces each output onto its own line. The blinking amber cursor indicates where the next character would appear. The bottom section catalogs the four escape sequences most likely to appear on the AP exam.
Common expression and output patterns tested on the AP exam
ExpressionOutputExplanation
System.out.println(5 + 3);8Both operands are ints → arithmetic addition.
System.out.println("5" + 3);53Left operand is a String → concatenation.
System.out.println(5 + 3 + "x");8xFirst + is int + int = 8, then 8 + "x" concatenates.
System.out.println("x" + 5 + 3);x53"x" + 5 → "x5", then "x5" + 3 → "x53".
System.out.println("x" + (5 + 3));x8Parentheses force arithmetic first: 5 + 3 = 8, then "x" + 8 → "x8".
System.out.println(10 / 3);3Integer division truncates the decimal portion.
System.out.println(10.0 / 3);3.3333333333333335One double operand promotes the result to double.
📝 AP Exam Tip
Multiple-choice questions frequently test the difference between "x" + 5 + 3 and 5 + 3 + "x". Always trace the expression from left to right, checking the types at each + operator. If you are ever unsure, draw a mini evaluation tree like the one in Section 3.

Worked Example: Tracing a Complex Output Statement

Consider the following Java code segment, which is representative of what you might encounter in an AP free-response question asking you to determine what is printed:

int a = 10; int b = 3; double c = 2.0; System.out.print(a + b); System.out.print(" and "); System.out.println(a / b + " R " + a % b); System.out.println(a * c);
Trace the Output
1
Step 1 — Evaluate print(a + b)Both a and b are ints, so a + b is arithmetic addition: 10 + 3 = 13. Because this is print() (not println), the cursor stays on the same line.
Console so far: 13
2
Step 2 — Evaluate print(" and ")The argument is already a String literal. It is printed immediately after the previous output, still on the same line.
Console so far: 13 and
3
Step 3 — Evaluate println(a / b + " R " + a % b)Evaluate left to right. First: a / b → 10 / 3 = 3 (integer division). Next: 3 + " R " → string concatenation produces "3 R ". Next: a % b → 10 % 3 = 1. Finally: "3 R " + 1"3 R 1". Because this is println(), a newline is appended after the output.
Console so far: 13 and 3 R 1\n
4
Step 4 — Evaluate println(a * c)a is int (10) and c is double (2.0). Type promotion converts a to 10.0 before multiplication: 10.0 × 2.0 = 20.0. This is printed on a new line (because the previous println already moved the cursor), followed by another newline.
Console so far: 13 and 3 R 1\n20.0\n
5
Step 5 — Final OutputCombining all steps, the complete console output is shown below.
Complete output: 13 and 3 R 1 20.0

Comparing Output Methods & Common Pitfalls

Behavioral comparison of the two console output methods
FeatureSystem.out.print()System.out.println()
Appends newline?NoYes
Can be called with no argument?No (compiler error)Yes (prints blank line)
Typical use caseBuilding a line incrementally inside a loopOutputting a complete line of text
Evaluates expression first?YesYes
Return typevoidvoid

Common Pitfalls

  • Forgetting left-to-right evaluation: Students often assume all arithmetic is computed before concatenation. Remember: Java processes each + in sequence.
  • Integer division surprise: Writing System.out.println(1/3) prints 0, not 0.333.... Both operands are ints, so the result is truncated.
  • Confusing print() with println(): Missing the newline distinction can cause entire output lines to merge, leading to wrong answers on trace questions.
  • Treating print/println as expressions: These methods return void. You cannot assign the result: String s = System.out.println("hi"); is a compile-time error.
KEY TAKEAWAY
Think of print() as a typewriter that keeps typing on the same line, and println() as a typewriter that hits the carriage return lever after each phrase. In both cases, the expression in the parentheses is fully evaluated before a single character reaches the paper.

Connecting to Advanced Topics

The expression-evaluation and output concepts covered in this lesson extend naturally into more advanced areas of the AP Computer Science A curriculum and beyond. Understanding how Java handles types, operator precedence, and string conversion at the basic level prepares you for the nuanced behaviors encountered with objects, polymorphism, and formatted output.

How foundational output concepts connect to advanced topics
This LessonAdvanced Extension
Concatenation with + and primitive typesCalling toString() on objects for custom String representations; overriding toString() in your own classes
Integer vs. double divisionExplicit casting with (int) and (double); understanding narrowing and widening conversions
print() / println()System.out.printf() for formatted output with format specifiers (not on AP exam, but widely used in college courses)
Left-to-right evaluation of + chainsCompound Boolean expressions and short-circuit evaluation with && and ||
Printing inside loops with print()Building complex output patterns in nested for/while loops; using StringBuilder for efficiency (college-level)

One particularly important connection involves the toString() method. When you write System.out.println(myObject), Java implicitly calls myObject.toString() to obtain the String that gets printed. Every class in Java inherits a default toString() from the Object class, but well-designed classes override it to return something meaningful. This mechanism is the object-oriented generalization of the primitive-to-String conversion you have already mastered in this lesson—and it is tested on the AP exam in free-response questions that involve writing or calling toString().

Practice Problems

1
What is printed by the following statement? System.out.println("Result: " + 3 + 7);
2
What is the output of the following code segment? int x = 17; int y = 5; System.out.println(x / y + " remainder " + x % y);
3
What is printed by the following code segment? System.out.print(4 + 3); System.out.print(" and "); System.out.println(4 + "3"); System.out.println(4 + 3);
PROBLEM 4APPLIED
Write a Java code segment that declares two int variables, totalMinutes set to 197 and rate set to 60, then uses System.out.println() to produce the following exact output: 3 hours and 17 minutes Your solution must compute the values 3 and 17 using expressions involving totalMinutes and rate (not hard-coded).
PROBLEM 5CRITICAL THINKING
Consider the following code segment: int a = 5; int b = 2; System.out.println(a + b + "" + a + b); System.out.println(a + b + "" + (a + b)); Explain what each println statement outputs and why the outputs differ. In your explanation, describe the role of the empty string literal and parentheses in altering the evaluation.

Lesson Summary

In Java, an expression is any combination of literals, variables, operators, and method calls that evaluates to a single value. Arithmetic expressions follow standard operator precedence (parentheses, then *, /, %, then +, −) and associate left to right. When both operands of / or % are ints, Java performs integer division (truncation toward zero) or returns the remainder; if either operand is a double, type promotion produces a double result.

The + operator is overloaded: it performs arithmetic addition between numeric types and string concatenation when at least one operand is a String, converting the non-String operand automatically. System.out.print() writes the evaluated expression to the console without a trailing newline, while System.out.println() appends a newline. Mastering left-to-right evaluation, the use of parentheses to force evaluation order, and the distinction between print and println is essential for both the multiple-choice and free-response sections of the AP Computer Science A exam.

Varsity Tutors • AP Computer Science A • Expressions and Output()