> 赋值,算术和一元运算符
简单赋值运算符
您将遇到的最常见的运算符之一是简单的赋值运算符“ =
”。您在 Bicycle 类中看到了该运算符;它将右边的值赋给左边的操作数:
int cadence = 0;
int speed = 0;
int gear = 1;
如Creating Objects所述,该运算符还可用于对象以分配对象引用。
算术运算符
Java 编程语言提供了执行加,减,乘和除运算符。您很有可能会在基本 math 中被同行认可。对您来说似乎唯一的新符号是“ %
”,该符号将一个操作数除以另一个,然后返回余数作为结果。
Operator | Description |
---|---|
+ | 加法运算符(也用于字符串 连接) |
- | Subtraction operator |
* | Multiplication operator |
/ | Division operator |
% | Remainder operator |
以下程序ArithmeticDemo测试算术运算符。
class ArithmeticDemo {
public static void main (String[] args) {
int result = 1 + 2;
// result is now 3
System.out.println("1 + 2 = " + result);
int original_result = result;
result = result - 1;
// result is now 2
System.out.println(original_result + " - 1 = " + result);
original_result = result;
result = result * 2;
// result is now 4
System.out.println(original_result + " * 2 = " + result);
original_result = result;
result = result / 2;
// result is now 2
System.out.println(original_result + " / 2 = " + result);
original_result = result;
result = result + 8;
// result is now 10
System.out.println(original_result + " + 8 = " + result);
original_result = result;
result = result % 7;
// result is now 3
System.out.println(original_result + " % 7 = " + result);
}
}
该程序打印以下内容:
1 + 2 = 3
3 - 1 = 2
2 * 2 = 4
4 / 2 = 2
2 + 8 = 10
10 % 7 = 3
您还可以将算术运算符与简单的赋值运算符结合在一起以创建复合赋值。例如,x+=1;
和x=x+1;
都将x
的值加 1.
+
运算符还可以用于将两个字符串 连接(连接)在一起,如以下ConcatDemo程序所示:
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
在该程序结束时,变量thirdString
包含“这是一个 String 联的字符串。”,该变量将被打印到标准输出中。
一元运算符
一元运算符只需要一个操作数;它们执行各种操作,例如将值增加/减少 1,否定表达式或将布尔值取反。
Operator | Description |
---|---|
+ | 一元加号运算符;表示正值(但是没有这个,数字为正) |
- | 一元减运算符;否定表达式 |
++ | 增量运算符;将值增加 1 |
-- | 递减运算符;将值减 1 |
! | 逻辑补运算符;反转布尔值 |
以下程序UnaryDemo测试一元运算符:
class UnaryDemo {
public static void main(String[] args) {
int result = +1;
// result is now 1
System.out.println(result);
result--;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);
boolean success = false;
// false
System.out.println(success);
// true
System.out.println(!success);
}
}
可以在操作数(前缀)之前或之后(后缀)应用增量/减量运算符。代码result++;
和++result;
都将以result
递增 1.唯一的区别是前缀版本(++result
)评估为增量值,而后缀版本(result++
)评估为原始值。如果您只是执行简单的增量/减量,则选择哪个版本都没有关系。但是,如果在较大表达式的一部分中使用此运算符,则选择的运算符可能会产生很大的不同。
以下程序PrePostDemo演示了前缀/后缀一元增量运算符:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}