Expressions and Output
Big idea: Arithmetic in Java mostly works like math class, with two big surprises: dividing two ints throws away the remainder, and + switches to joining text as soon as a String is involved.
- Develop code to generate output and determine the result that would be displayed.
- Develop code to utilize string literals and determine the result of using string literals.
- Develop code for arithmetic expressions and determine the result of these expressions.
print vs. println
System.out.print displays its value and keeps the cursor on the same line. System.out.println displays its value and then moves to a new line.
System.out.print("A");
System.out.print("B");
System.out.println("C");
System.out.println("D");OutputABC D
String literals and escape sequences
A string literal is text in double quotes. To put a special character inside, use an escape sequence: \" for a double quote, \\ for a backslash, and \n for a new line.
System.out.println("She said \"hi\"");
System.out.println("C:\\temp");
System.out.println("line 1\nline 2");OutputShe said "hi" C:\temp line 1 line 2
Integer division and remainder
When both operands are int, the result is an int: / keeps only the whole-number part (it truncates). If at least one operand is a double, the result is a double.
% (mod) gives the remainder. It is handy for even/odd tests (n % 2 == 0), for "every kth" patterns, and for pulling digits off a number (n % 10 is the last digit, n / 10 drops it).
System.out.println(17 / 5);
System.out.println(17 % 5);
System.out.println(17 / 5.0);
System.out.println(4 % 7);
System.out.println(1234 % 10 + " " + 1234 / 10);Output3 2 3.4 4 4 123
Precedence and left-to-right +
*, /, and % happen before + and -. Operators with the same precedence go left to right, and parentheses override everything.
+ adds numbers, but once the left side is a String, it concatenates. Work left to right one operator at a time.
System.out.println(2 + 3 * 4);
System.out.println(10 - 4 - 3);
System.out.println(20 / 4 * 2);
System.out.println(1 + 2 + "3" + 4 + 5);
System.out.println("Sum: " + (4 + 5));Output14 3 10 3345 Sum: 9
printlnends the line;printdoesn't.- Escape sequences:
\",\\,\n. int / inttruncates:7 / 2is3. Anydoubleoperand gives adouble:7 / 2.0is3.5.%gives the remainder:17 % 5is2, and4 % 7is4.* / %before+ -; ties go left to right.- Dividing an
intby integer zero throws anArithmeticException.
- String concatenation is left to right:
1 + 2 + "3"is"33", but"3" + 1 + 2is"312". %has the same precedence as*and/, not lower.- When the left number is smaller,
a % bis justa:3 % 8is3.
- Trace mixed expressions one operator at a time and write the type of each intermediate result (int, double, or String).
System.out.println(7 / 2 * 2.0);Show answer
System.out.println("" + 4 + 4 + (4 + 4));Show answer
- Expressions that produce Infinity or NaN.
- Using % with a negative left operand or a right operand ≤ 0.
- Dividing by zero when one value is a double.