Assignment operator
Function: Assign the value of a constant, variable or expression to a variable.
species:
Operator | Calculation | example | result |
= | Assignment | a=3;b=2; | a=3; b=2; |
+= | Plus equals | a=3;b=2; a+=b; | a=a+b=5; b=2; |
-= | Minus equal | a=3;b=2; a-=b; | a=a-b=1; b=2; |
*= | Multiply equals | a=3;b=2; a*=b; | a=a*b=6; b=2; |
/= | Divide equal | a=3;b=2; a/=b; | a=a/b=1; b=2; |
%= | Modulo equal | a=3;b=2; a%=b; | a=a%b=1; b=2; |
table of Contents
-
Assignment (=)
In the assignment process, the order of operations is from right to left , and the result of the expression on the right is assigned to the variable on the left.
Exercise:
public class TestOpe07{ public static void main(String[] args){ //任意给出两个数,交换两个数并输出 //给出两个数 int a=5; int b=10; //输出交换前的两个数 System.out.println("交换前:"+a+"\t"+b); //交换 int t; //引入一个中间变量 t=a; a=b; b=t; //输出交换后的两个数 System.out.println("交换后:"+a+"\t"+b); } }
operation result:
-
Extended assignment operator
When assigning values to variables, when the two data types are incompatible with each other, or the value range of the target data type is smaller than the source type, a forced data type conversion is required. However, when the +=, -=, *=, /=, %= operators are used for assignment, the forced type conversion will be automatically completed , and the program does not need to make any explicit declarations . E.g:
public class TestOpe08{ public static void main(String[] args){ short s=3; int i=5; s+=i; //相当于s=(short)(s+i) System.out.println("s="+s); } }
operation result:
Note 1: The difference between a+=b and a=a+b:
a+=b Slightly poor readability High
compilation efficiency Low -level automatic type conversion a=a+b Good readability Low compilation efficiency Manual type conversion
-
Interview questions
(1) Is a+=b equivalent to a=a+b, then is it also equivalent to a=b+a?
For basic data type is the same . E.g:
a=10;b=20;
a=a+b=30
a=b+a=30
For String type is not the same . E.g:
a='x';b='u';
a=a+b="xu"
a=b+a="ux"
(2) Which sentence of the following code is wrong:
byte a = 10;
int b = 20;
a + = b;
a = a + b ; // rectification a = (byte) (a + b);
-
Error-prone:
In Java, multiple variables can be assigned through a single assignment statement. Specific examples are as follows:
int x,y,z;
x=y=z=5;
It is important to note that the following writing method is not possible in Java.
int x=y=z=5; //This is wrong