Unit 1.3: Expressions and Output
AP Computer Science A
Learning Objectives:
- 1.3.A: Develop code to generate output
- 1.3.B: Utilize string literals
- 1.3.C: Create arithmetic expressions
Output Methods in Java
System.out.print vs System.out.println
System.out.println - displays information and moves cursor to new line
System.out.print - displays information without moving cursor
System.out.print("Hello ");
System.out.print("World");
System.out.println("!");
System.out.println("Next line");
Hello World!
Next line
Arithmetic Operators
The Five Basic Operators
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Remainder (Modulo)
System.out.println(7 + 3); // 10
System.out.println(7 - 3); // 4
System.out.println(7 * 3); // 21
System.out.println(7 / 3); // 2 (integer division!)
System.out.println(7 % 3); // 1 (remainder)
Arithmetic Type Rules
Important Rules
- Operation with two int values produces int result
- Operation with at least one double produces double result
// int operations
System.out.println(5 + 3); // 8
System.out.println(5 / 2); // 2
// double operations
System.out.println(5.0 + 3); // 8.0
System.out.println(5.0 / 2); // 2.5
System.out.println(5 / 2.0); // 2.5
8
2
8.0
2.5
2.5
Integer Division
Important Concept!
When dividing two int values, the result is only the integer portion of the quotient (truncated, not rounded).
System.out.println(7 / 2); // 3 (not 3.5!)
System.out.println(10 / 3); // 3 (not 3.33...)
System.out.println(1 / 2); // 0 (not 0.5!)
// To get decimal result:
System.out.println(7.0 / 2); // 3.5
System.out.println(7 / 2.0); // 3.5
3
3
0
3.5
3.5
Operator Precedence
Order of Operations (PEMDAS)
- Parentheses - highest precedence
- *, /, % - multiplication, division, remainder
- +, - - addition, subtraction
- Left to right - for operators of same precedence
System.out.println(2 + 3 * 4); // 14 (not 20)
System.out.println((2 + 3) * 4); // 20
System.out.println(10 / 2 * 3); // 15 (left to right)
System.out.println(10 / (2 * 3)); // 1
14
20
15
1
Unit 1.3 Summary
Key Concepts Mastered:
- Output: System.out.print() vs println()
- Arithmetic Operators: +, -, *, /, %
- Type Rules: int operations vs double operations
- Integer Division: Truncates decimal part
- Operator Precedence: PEMDAS rules
Ready for Unit 1.4!
You now understand expressions and output in Java!
1 / ?