Simple Assignment and Compound Assignments
Using simple assignment means = operator and special variations with arithmetic operators like +=, -=, *=, /= and %= .
Learning Objectives
- Learning to use simple = (assignment) and its compounding with other arithmetic operators.
Source Code
Run Output
Code Understanding
int a,b,c,d; //four integer variables declared
a=10; b=20;
Two simple assignments with left hand side is a variable and right hand side is a value
System.out.println(“a=10, b=20 so a+b=”+ (a+b));
Printing a+b directly computing within println method argument. Assignment to a third intermediate variable is not done here.
a+=10; System.out.println(“after a+=10 a=”+ a);
This is a compound assignment which is equivalent to a=a+10; After changing a it is printed.
b-=10; System.out.println(“after b-=10 b=”+ b);
This is a compound subtraction assignment which is equivalent to b=b-10. Then it is printed.
c=d=10;
This is simultaneous assignment of two variables which are pre-declared.
System.out.println(“after c=d=10 c=”+ c);
System.out.println(“after c=d=10 d=”+ d);
Both the cases of simultaneous assignments are printed.
c*=5; d/=2;
System.out.println(“after c*=5 c=”+ c);
System.out.println(“after d/=2 d=”+ d);
These are compound multiplication and division assignments
d%=2; System.out.println(“after d%=2 d=”+ d);
This is a compound modulus assignment which is equivalent to d=d%2, which means that after operation the contents of d would be remainder of d/2 operation.
Notes
- Left hand side of an assignment should definitely be a variable and it can not be a value. For e.g. we can not do 10=a;
- For the above reason even when LHS is a variable we can not use sign along with assignment like
-a=10 for negation of left hand side.
Common Errors
- At the time of definition/declaration we can not use assignment chain like
int a=b=10; as the compiler will not be able to understand the second variable here. However one can use this type of syntax.
int x=10,y=15;
int z=x=y; //here x and y are pre-declared and with this line z,x,y all will become 15.
Suggested Filename(s): AssignmentOp.java