publicclassOperators{publicstaticvoidmain(String[]args){intx=5;System.out.println("x = "+x);System.out.println();System.out.println("--- Addition ---");x=5;System.out.println("x + 2 = "+(x+2));System.out.println("x = "+x);System.out.println();System.out.println("--- Subtraction ---");x=5;System.out.println("x - 4 = "+(x-4));System.out.println("x = "+x);System.out.println();System.out.println("--- Multiplication ---");x=5;System.out.println("x * 3 = "+(x*3));System.out.println("x = "+x);System.out.println();System.out.println("--- (Integer) Division ---");x=5;System.out.println("x / 2 = "+(x/2));System.out.println("x = "+x);System.out.println();System.out.println("--- Modulo (Remainder) ---");x=5;System.out.println("x % 2 = "+(x%2));System.out.println("x = "+x);System.out.println();System.out.println("--- Preincrement by one ---");x=5;System.out.println("++x = "+(++x));System.out.println("x = "+x);System.out.println();System.out.println("--- Predecrement by one ---");x=5;System.out.println("--x = "+(--x));System.out.println("x = "+x);System.out.println();System.out.println("--- Postincrement by one ---");x=5;System.out.println("x++ = "+(x++));System.out.println("x = "+x);System.out.println();System.out.println("--- Postdecrement by one ---");x=5;System.out.println("x-- = "+(x--));System.out.println("x = "+x);System.out.println();}}
代码清单 3.10 的控制台
x = 5
--- Addition ---
x + 2 = 7
x = 5
--- Subtraction ---
x - 4 = 1
x = 5
--- Multiplication ---
x * 3 = 15
x = 5
--- (Integer) Division ---
x / 2 = 2
x = 5
--- Modulo (Remainder) ---
x % 2 = 1
x = 5
--- Preincrement by one ---
++x = 6
x = 6
--- Predecrement by one ---
--x = 4
x = 4
--- Postincrement by one ---
x++ = 5
x = 6
--- Postdecrement by one ---
x-- = 5
x = 4
除了执行数学函数之外,还有一些运算符用于将数字赋值给变量(每个示例都使用初始化为 x = 5 的变量)
代码清单 3.11:Assignments.java
publicclassAssignments{publicstaticvoidmain(String[]args){intx=5;x=3;System.out.println("Assignment (x = 3) : "+x);x=5;x+=5;System.out.println("Assign x plus another integer to itself (x += 5): "+x);x=5;x-=4;System.out.println("Assign x minus another integer to itself (x -= 4): "+x);x=5;x*=6;System.out.println("Assign x multiplied by another integer to itself (x *= 6): "+x);x=5;x/=5;System.out.println("Assign x divided by another integer to itself (x /= 5): "+x);}}
代码清单 3.11 的控制台
Assignment (x = 3) : 3
Assign x plus another integer to itself (x += 5): 10
Assign x minus another integer to itself (x -= 4): 1
Assign x multiplied by another integer to itself (x *= 6): 30
Assign x divided by another integer to itself (x /= 5): 1