'='赋值运算符用于为任何变量赋值。它具有从左到右的结合性,即在操作符右侧给出的值被分配给左侧的变量,因此右侧的值必须在使用前声明或者应该是常量。
赋值运算符的一般格式是,
variable = value;
在许多情况下,赋值运算符可以与其他运算符结合使用以构建称为复合语句的简短版本的语句。例如,而不是a = a + 5,我们可以写一个+ = 5。
int a = 5; a + = 5; // a = a + 5;
// Java program to illustrate
// assignment operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c, d, e = 10, f = 4, g = 9;
// simple assignment operator
c = b;
System.out.println("Value of c = " + c);
// This following statement would throw an exception
// as value of right operand must be initialised
// before assignment, and the program would not
// compile.
// c = d;
// instead of below statements,shorthand
// assignment operators can be used to
// provide same functionality.
a = a + 1;
b = b - 1;
e = e * 2;
f = f / 2;
System.out.println("a,b,e,f = " + a + ","
+ b + "," + e + "," + f);
a = a - 1;
b = b + 1;
e = e / 2;
f = f * 2;
// shorthand assignment operator
a += 1;
b -= 1;
e *= 2;
f /= 2;
System.out.println("a,b,e,f (using shorthand operators)= " +
a + "," + b + "," + e + "," + f);
}
}
输出:
Value of c =10 a,b,e,f = 21,9,20,2 a,b,e,f (using shorthand operators)= 21,9,20,2