1.3 Expressions and Output

22 阅读1分钟

1. Exam Points

  • Statements for output
    • System.out.println()
    • System.out.print()
  • Escape sequences(转义字符)
    • "
    • \
    • \n
  • Arithmetic Operators: +, -, *, /, %
    • int/int is int
    • int/double or double/int is double
    • a/b*c evaluates a/b first, from left to right
    • 13 % 5 is 3
    • divide an integer by zero results in ArithmeticException

2. Knowledge Points

(1) Literals (字面值)

  • A literal(字面值) is the code representation of a fixed value.
  • A string literal is a sequence of characters enclosed in double quotes.
    • "Annabelle"
    • "0532-89765432"
  • Escape sequences(转义字符) are special sequences of characters that can be included in a string.
  • They start with a \ and have a special meaning in Java.
  • Escape sequences used in this course include:
    • " : displays a "
    • \ : displays a \
    • \n : start a new line
  • Example:
    • System.out.println("I "love" sleeping");
    • It prints I "love" sleeping

(2) Arithmetic Expressions(算术表达式)

  • Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
    • Example:
      • a + b
      • a * b / c - d
  • Arithmetic operators: +, -, *, /, %
    image.png
  • Note:
    • An arithmetic operation on two int values evaluates to an int value.
      • 19/5 is 3
    • An arithmetic operation using at least one double value evaluates to a double value.
      • 13/2.0 is 6.5
      • 15.0/2 is 7.5
    • An attempt to divide an integer by zero will result in ArithmeticException, which is a run-time error.
      • 2/0 leads to error
      • can be used to concatenate(连接) two String values.
        • "ab"+"cd" is abcd
  • Operator Precedence
    • Just like in math, *, /, % first, parentheses first
    • Operators with the same precedence are evaluated from left to right.
      • 5/2*3 is 6, 5/2 is evaluated first
      • 1+2+"a" is 3a
      • "a"+1+2 is a12

3. Exercises