下面的示例显示了赋值运算符和复合赋值运算符的用法:
- = 赋值运算符
- += 加法 与 赋值运算符
- -= 减法 与 赋值运算符
- *= 乘法 与 赋值运算符
- /= 除法 与 赋值运算符
- %= 取模与赋值运算符
public class MyClass {
public static void main(String[] args) {
float a = 25f;
System.out.println("a = "+ a);
//加法AND赋值运算符
a += 5;
System.out.println("a += 5; makes a = "+ a);
//减法与赋值运算符
a -= 8;
System.out.println("a -= 8; makes a = "+ a);
//乘法与赋值运算符
a *= 4;
System.out.println("a *= 4; makes a = "+ a);
//除法与赋值运算符
a /= 2;
System.out.println("a /= 2; makes a = "+ a);
//模与赋值运算符
a %= 7;
System.out.println("a %= 7; makes a = "+ a);
}
}
上述代码的输出将是:
a = 25.0
a += 5; makes a = 30.0
a -= 8; makes a = 22.0
a *= 4; makes a = 88.0
a /= 2; makes a = 44.0
a %= 7; makes a = 2.0