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.

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

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?

SECTION 2

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.

SECTION 3

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.

Expression Evaluation: Left-to-Right with String ConcatenationSystem.out.println(1 + 2 + "abc" + 3 + 4);1 + 2int + int33 + "abc"int + String → concat!"3abc""3abc" + 3String + int → concat"3abc3""3abc3" + 4String + int → concat"3abc34"Console output: 3abc34
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.

SECTION 4

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(truncationtowardzero,notrounding)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

77 % 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→Stringany+String→StringString + 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.

SECTION 5

Detailed Breakdown: Output Behavior & Escape Sequences

print() vs. println(): Console Cursor BehaviorUsing print()Code:System.out.print("Hello");System.out.print(" World");Console:Hello World↑ Cursor stays on same lineUsing println()Code:System.out.println("Hello");System.out.println("World");Console:HelloWorld↑ Cursor moves to next line after each callCommon Escape Sequences in Strings\nNewline\tTab\\Backslash literal\"Double-quote literalEscape sequences are processed inside String literals before output.
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.
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.

Common expression and output patterns tested on the AP exam

💡

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.

SECTION 6

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. 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. 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. 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. 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. 5

    Step 5 — Final Output

    Combining all steps, the complete console output is shown below.
    Complete output: 13 and 3 R 1 20.0

SECTION 7

Comparing Output Methods & Common Pitfalls

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

Behavioral comparison of the two console output methods

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.

SECTION 8

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.

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)

How foundational output concepts connect to advanced topics

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().

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

What is printed by the following statement? System.out.println("Result: " + 3 + 7);
  • A. Result: 10
  • B. Result: 37
  • C. Result: 3 7
  • D. A compile-time error occurs.
Show answer (B)
The correct answer is B. Java evaluates the + operators left to right. The first + has a String ("Result: ") on the left and int 3 on the right, so it concatenates to produce "Result: 3". The second + has a String ("Result: 3") on the left and int 7 on the right, so it again concatenates to produce "Result: 37". Choice A is wrong because it incorrectly assumes 3 + 7 is computed arithmetically before concatenation—that would only happen with parentheses: "Result: " + (3 + 7). Choice C is wrong because concatenation does not insert spaces between the operands. Choice D is wrong because the code is syntactically valid.

Question 2: BASIC CALCULATION

What is the output of the following code segment? int x = 17; int y = 5; System.out.println(x / y + " remainder " + x % y);
  • A. 3.4 remainder 2
  • B. 3 remainder 2
  • C. 3 remainder2
  • D. 3.0 remainder 2.0
Show answer (B)
The correct answer is B. First, x / y performs integer division: 17 / 5 = 3 (truncated). Then 3 + " remainder " concatenates to "3 remainder ". Next, x % y computes the remainder: 17 % 5 = 2. Finally, "3 remainder " + 2 concatenates to "3 remainder 2". Choice A is wrong because both operands of / are ints, so the result is an int (3), not 3.4. Choice C is wrong because the String literal " remainder " includes spaces on both sides. Choice D is wrong because no double values are involved in this computation.

Question 3: INTERMEDIATE

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);
  • A. 7 and 43 7
  • B. 7 and 7 7
  • C. 43 and 43 7
  • D. 7 and 43 7
Show answer (A)
The correct answer is A. The first print outputs 7 (int + int arithmetic) with no newline. The second print outputs " and " on the same line. The third call is println(4 + "3"): since "3" is a String, 4 + "3" concatenates to "43", which is printed followed by a newline. The fourth call, println(4 + 3), adds two ints to get 7, prints it, and appends a newline. The total output is "7 and 43" on line one and "7" on line two. Choice B is wrong because 4 + "3" is concatenation, not addition. Choice C is wrong because the first print(4 + 3) evaluates two ints, yielding 7. Choice D is wrong because print() does not emit newlines, so the first three outputs appear on one line.

Question 4: APPLIED

4 pts
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).
Show answer
Sample solution: int totalMinutes = 197; int rate = 60; System.out.println(totalMinutes / rate + " hours and " + totalMinutes % rate + " minutes"); Rubric (4 points): Point 1 — Variable Declaration: Correctly declares totalMinutes as 197 and rate as 60 with appropriate int types. Point 2 — Integer Division Expression: Uses totalMinutes / rate to compute the number of hours (3). The division must be between two ints so that truncation produces the correct integer result. Point 3 — Modulus Expression: Uses totalMinutes % rate to compute the remaining minutes (17). Point 4 — Correct Concatenation and Output: Produces the exact output "3 hours and 17 minutes" using a single println statement (or equivalent) with correct spacing in the string literals. The computed values must not be hard-coded.

Question 5: CRITICAL THINKING

3 pts
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.
Show answer
Rubric (3 points): Point 1 — Correct output for line 1: The first println outputs "752". Evaluation: 5 + 2 = 7 (int addition), then 7 + "" = "7" (concatenation with empty string), then "7" + 5 = "75" (concatenation), then "75" + 2 = "752" (concatenation). Point 2 — Correct output for line 2: The second println outputs "77". Evaluation: 5 + 2 = 7 (int addition), then 7 + "" = "7" (concatenation with empty string), then (a + b) is evaluated inside parentheses as 5 + 2 = 7 (int addition forced by parentheses), then "7" + 7 = "77" (concatenation). Point 3 — Explanation of the role of "" and (): The empty string serves as a type-conversion trigger, switching all subsequent + operations from arithmetic to concatenation. Without parentheses (line 1), the remaining + operators concatenate a and b individually as "5" and "2". With parentheses (line 2), the subexpression (a + b) is evaluated as arithmetic first (producing 7), and only then is the result concatenated. This demonstrates that parentheses override left-to-right associativity by forcing inner expressions to be evaluated before they participate in the outer concatenation chain.

SUMMARY

Lesson Summary

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()