Unit 1 · 25 min
1.3 Expressions and Output
Java evaluates expressions by fixed rules: the types decide the result, and precedence decides the order.
Summary, objectives and course and exam description (CED) codes
System.out.print displays information and System.out.println displays it and then moves to a new line. A string literal is text in double quotes and can hold escape sequences such as \n. Arithmetic expressions follow fixed rules: two int values give an int, at least one double gives a double, and operator precedence decides the grouping.
By the end of this session you can
- 1.3.A Develop code to generate output and determine the result that would be displayed.
- 1.3.B Develop code to utilize string literals and determine the result of using string literals.
- 1.3.C Develop code for arithmetic expressions and determine the result of these expressions.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Output: print and println
System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed; System.out.print does not 1.3.A.1. System.out.println(); with nothing inside just ends the line.
System.out.print("Total: ");
System.out.println(7 + 3); // 10, after "Total: "
System.out.println("7" + 3); // 73 (text joined, not added)
System.out.print("A");
System.out.print("B");
System.out.println(); // just ends the line
System.out.println("C");
Output:
Total: 10
73
AB
C
Watch out: print does not add a space. If you want one, put it inside the quotes, as in "Total: ".
2. Literals and string literals
A literal is the code representation of a fixed value, such as 42, 3.5 or true 1.3.B.1. A string literal is a sequence of characters enclosed in double quotes, such as "Game over" 1.3.B.2.
A literal’s form sets its type: 7 is an int, 7.0 is a double, "7" is a String and true is a boolean. So 7 / 2 uses int division but 7.0 / 2 does not 1.3.B, 1.3.C.
System.out.println(7 / 2);
System.out.println(7.0 / 2);
System.out.println("7 / 2");
Output:
3
3.5
7 / 2
The last line prints the characters exactly as written, because they are inside a string literal. Java does not calculate anything inside quotes.
3. Escape sequences
Escape sequences are special sequences of characters inside a string. They start with a backslash \ and have a special meaning in Java. The 3 escape sequences in this course are \" (double quote), \\ (backslash) and \n (newline) 1.3.B.3.
Each escape sequence stands for one character in the String, so "a\nb".length() is 3 (length() is in topic 1.15).
System.out.println("She said \"go\"\nC:\\temp");
System.out.println("a\nb".length());
Output:
She said "go"
C:\temp
3
Watch out: a single \ inside a string always starts an escape sequence. In "C:\temp", Java reads \t as a tab (outside the course), so the backslash is never printed; with most other letters, such as "C:\data", the code does not compile. To print one backslash, write two: \\.
4. Arithmetic expressions
An arithmetic expression is made of numeric values, variables and operators, and it can have type int or double 1.3.C.1. The 5 arithmetic operators are +, -, *, / and % (remainder) 1.3.C.2.
- An operation with two
intvalues evaluates to anint. An operation with at least onedoublevalue evaluates to adouble1.3.C.2. - Dividing two
intvalues gives only the integer portion of the quotient. Dividing when at least one value is adoublegives the full quotient 1.3.C.3. - The remainder operator
%computes the remainder when one numberais divided by another numberb1.3.C.4. - int division drops the decimal part, so the result moves toward zero:
-7 / 2is-3, not-4.
| Expression | Value | Why |
|---|---|---|
17 / 5 |
3 |
int / int keeps only the integer part |
17 % 5 |
2 |
remainder of 17 divided by 5 |
17 / 5.0 and 17.0 / 5 |
3.4 |
at least one double, so the result is a double |
2 + 3 * 4 |
14 |
*, /, % before +, - |
(2 + 3) * 4 |
20 |
parentheses change the grouping |
10 - 4 - 3 |
3 |
same precedence: left to right |
8 % 3 * 2 |
4 |
same precedence: 8 % 3 is 2, then * 2 |
System.out.println(17 / 5);
System.out.println(17 % 5);
System.out.println(17 / 5.0);
System.out.println(17.0 / 5);
System.out.println(-7 / 2);
System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
System.out.println(10 - 4 - 3);
System.out.println(8 % 3 * 2);
Output:
3
2
3.4
3.4
-3
14
20
3
4
Outside the course: % with a negative first value or with a divisor of 0 or less, double division by zero, and results such as infinity or NaN (not a number).
5. Operator precedence
Operator precedence is the order in which Java groups operators. At compile time, values are associated with operators by precedence. Parentheses change the grouping. Multiplication, division and remainder have precedence over addition and subtraction, and operators with the same precedence are evaluated from left to right 1.3.C.5.
Higher rows group first (they hold their operands more tightly). Within rows 3 and 4, Java works left to right. The course framework states rows 1, 3 and 4; rows 2 and 5 are how Java works, and they explain the casting and assignment rules in topics 1.4 to 1.6.
| Order | Operators | Example | Value |
|---|---|---|---|
| 1 | ( ) parentheses |
(2 + 3) * 4 |
20 |
| 2 | one-operand operators: -x (negation), casts (int) and (double) |
(int) 3.9 * 2 |
6 (the cast applies to 3.9 only) |
| 3 | * / % |
10 - 4 * 2 |
2 |
| 4 | + - (two operands) |
10 - -3 |
13 (subtract negative 3) |
| 5 | = += -= *= /= %= |
x *= 2 + 3 |
the whole right side first (topic 1.6) |
System.out.println((int) 3.9 * 2);
System.out.println((int) (3.9 * 2));
System.out.println(10 - -3);
System.out.println(7 + 9 / 4 * 2);
Output:
6
7
13
11
In the last line, 9 / 4 is 2 (int division), 2 * 2 is 4, and 7 + 4 is 11.
Background (not tested): unary and binary operators. The values an operator works on are its operands. A unary operator has one operand:
-x,(int) x,x++(see topic 1.6). A binary operator has two:a - b,a * b. The same symbol can do different jobs.-is negation in-xbut subtraction ina - b.+adds when both operands are numbers but joins text when either operand is aString(concatenation, see topic 1.15), and because Java works left to right,1 + 2 + "!"is"3!"while"!" + 1 + 2is"!12". The words unary, binary and operand are not official course wording, but they help you read any expression.
System.out.println(1 + 2 + "!");
System.out.println("!" + 1 + 2);
Output:
3!
!12
6. Dividing by zero
An attempt to divide an integer by the integer zero results in an ArithmeticException 1.3.C.6. The code compiles, but the program stops when the division runs.
int players = 0;
System.out.println("Splitting 20 points");
System.out.println(20 / players);
Output:
Splitting 20 points
Exception in thread "main" java.lang.ArithmeticException: / by zero
Outside the course: dividing by zero when one of the values is a double.
7. Using / and % together
/ and % together split a number into parts 1.3.C:
n % 2is 0 for even numbers and 1 for odd ones (fornof 0 or more).n % 10gives the last digit andn / 10removes it, so347 % 10is 7 and347 / 10is 34.minutes / 60andminutes % 60split 135 minutes into 2 hours and 15 minutes.
int minutes = 135;
System.out.println(minutes / 60 + " h " + minutes % 60 + " min");
int code = 347;
System.out.println(code % 10);
System.out.println(code / 10);
System.out.println(code % 2);
Output:
2 h 15 min
7
34
1
These moves return in Unit 2 and in free-response questions.
Lock it in: memory hooks
- print vs printlnprintln = print + line: it ends the line after the text.
- Integer divisionint / int chops, it never rounds: 7 / 2 is 3.
- PrecedenceTimes, divide and remainder go first; plus and minus wait their turn.
- Last digit% 10 takes the last digit, / 10 removes it.
Common misconceptions
"7 / 2 is 3.5 in Java."
Not quite. Both values are int, so Java keeps only the integer part of the quotient: 7 / 2 is 3. Write 7.0 / 2 or 7 / 2.0 to get 3.5.
"Integer division rounds to the nearest whole number."
Not quite. It drops the decimal part, so the result moves toward zero: 9 / 5 is 1 (not 2) and -7 / 2 is -3 (not -4).
"println prints a new line before the text."
Not quite. println displays the text first, then moves the cursor to a new line. The next output starts on the next line.
"Java does all operations from left to right."
Not quite. Only operators with the same precedence go left to right. *, / and % group before + and -, and parentheses change the grouping.
Exam traps
- Integer division: 7 / 2 is 3, not 3.5. Check the types of BOTH values before you divide.
- A cast applies only to the value right after it. (int) 3.9 * 2 is 6, but (int) (3.9 * 2) is 7. Put parentheses around everything you want cast.
- "7" + 3 is "73": when either operand is a String, + joins text instead of adding.
- Each escape sequence is one character: "a\nb".length() is 3, not 4.
2PracticeRecall it, then check yourself
In 30 seconds
- System.out.print leaves the cursor on the line; System.out.println moves to a new line after the output.
- A literal is a fixed value in code; a string literal is characters inside double quotes.
- The 3 escape sequences in this course are \" (double quote), \\ (backslash) and \n (newline).
- int op int gives an int; at least one double gives a double. int division keeps only the integer part.
- *, / and % have precedence over + and -; same-precedence operators go left to right; parentheses change grouping.
- Dividing an integer by the integer zero throws an ArithmeticException.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 6 questions
Checkpoint: Expressions and Output
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Escape sequences in this course three escape sequences CED 1.3.B.3
- \"double quote
- \\backslash
- \nnewline
- Arithmetic operators five operators CED 1.3.C.2
- +addition
- -subtraction
- *multiplication
- /division
- %remainder
- Operator precedence, highest first five levels CED 1.3.C.5
- ( ) parentheses
- one-operand operators-x and casts
- * / %
- + -two operands
- = += -= *= /= %=
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Literaltap to flip
The code representation of a fixed value, such as 42, 3.5, true or "hi".
Example and CED codes -
String literaltap to flip
A sequence of characters enclosed in double quotes, such as "Game over".
Example and CED codes -
Escape sequencetap to flip
A special sequence of characters in a string that starts with a backslash: \" (double quote), \\ (backslash) or \n (newline).
Example and CED codes -
Expressiontap to flip
Code that is evaluated to a single value with a type. An arithmetic expression combines numeric values, variables and operators.
Example and CED codes -
Arithmetic operatorstap to flip
The five operators for arithmetic: + (addition), - (subtraction), * (multiplication), / (division) and % (remainder).
Example and CED codes -
Integer divisiontap to flip
Dividing two int values: the result is only the integer part of the quotient, so 7 / 2 is 3.
Example and CED codes -
Remainder operator (%)tap to flip
The % operator: a % b gives the remainder when a is divided by b.
Example and CED codes -
Operator precedencetap to flip
The rules that decide how operators are grouped: *, / and % before + and -, same level left to right, parentheses first.
Example and CED codes -
ArithmeticExceptiontap to flip
The exception thrown when a program tries to divide an integer by the integer zero.
Example and CED codes -
String concatenationtap to flip
Joining strings with + or +=, which creates a new String. Primitives are converted to text and objects call toString.
Example and CED codes
Questions students ask
What is the difference between print and println in Java?
System.out.print displays its information and leaves the cursor at the end of it. System.out.println displays its information and then moves the cursor to a new line, so the next output starts on the next line.
Why does 7 / 2 equal 3 in Java?
Both 7 and 2 are int values, so the division is int division: Java keeps only the integer part of the quotient. If at least one value is a double, as in 7.0 / 2, the result is the double 3.5.
What does the % operator do in Java?
% is the remainder operator. a % b gives the remainder when a is divided by b, so 17 % 5 is 2. n % 2 is 0 for even numbers and n % 10 gives the last digit.
How do I print a double quote or a backslash in Java?
Use an escape sequence inside the string literal: \" prints a double quote, \\ prints a backslash and \n starts a new line.
What happens if you divide by zero in Java?
Dividing an integer by the integer zero throws an ArithmeticException at run time, and the program stops. Dividing a double by zero is outside the AP® course.