APCSA 1.3 — Expressions and Output (Java)

How Java evaluates expressions, handles data, and prints output

Overview

An expression combines values, variables, operators, and method calls to produce a single value. Output displays information to the user, typically with System.out.print() or System.out.println().

1) Expressions

Expressions range from a literal like 10 to complex formulas like (a + b) * c / 2. Java follows operator precedence and type conversion rules.

Arithmetic Expressions

Use +, -, *, /, and % (remainder).

int sum = 5 + 3 * 2;   // 11
int remainder = 10 % 3; // 1

String Expressions

Use + for concatenation (joining text).

String name = "Mr. " + "Cusack"; // "Mr. Cusack"

Boolean Expressions

Produce true or false using relational and logical operators.

boolean result = (5 > 3) && (2 < 4); // true
// Relational: > < >= <= == !=
// Logical:    &&, ||, !

2) Operator Precedence

Determines evaluation order. Use parentheses for clarity.

PriorityOperators
Highest() (parentheses)
*, /, %
+, -
Relational: <, >, <=, >=
Equality: ==, !=
Logical AND: &&
LowestLogical OR: ||
int a = 5 + 3 * 2;     // 11
int b = (5 + 3) * 2;   // 16

3) Type Conversion (Casting)

Java promotes types automatically when mixing int and double. Use casting to control results.

double avg1 = (3 + 4 + 5) / 3;    // 12 / 3 = 4  (integer division → 4.0)
double avg2 = (3 + 4 + 5) / 3.0; // 12 / 3.0 = 4.0 (double)
double avg3 = (double)(3 + 4 + 5) / 3; // 12.0 / 3 = 4.0

Note: If all operands of / are int, Java performs integer division and truncates decimals.

4) Output Statements

Use System.out.print() (no newline) and System.out.println() (adds newline).

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

5) Escape Sequences

SequenceDescription
\nNew line
\tTab
\"Double quote
\\Backslash
System.out.println("Hello\nWorld!");
/* Output:
Hello
World!
*/

6) Combining Expressions and Output

int age = 17;
System.out.println("You are " + age + " years old.");
// You are 17 years old.

7) Common Pitfalls

✅ Summary

ConceptDescriptionExample
ExpressionValues + variables + operators → one valuex + y * 2
OutputDisplay with print/printlnSystem.out.println("Hi");
ArithmeticMath operatorsa + b, x % y
BooleanTrue/false logic(x > 5) && (y < 10)
PrecedenceEvaluation order3 + 4 * 2 = 11
Type CastingChange data type(double) sum / count
Escape SequencesFormatting in strings\n, \t, \"

Tip: Add small, runnable snippets in your IDE so students can see actual outputs.