In Java, assignment operators are used in Java to assign values to variables.
Operator | Example |
= | c = d; |
+= | c += d; |
-= | c -= d; |
*= | c *= d; |
/= | c /= d; |
%= | c %= d; |
1. (=) Operator
This operator is used to assign the value on the right to the variable on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
System.out.println("a: " + a);
double b, c, d, e;
b = c = d = e = 4.5;
System.out.println("b: " + b);
System.out.println("c: " + c);
System.out.println("d: " + d);
System.out.println("e: " + e);
double f = b + c;
System.out.println("f: " + f);
}
}
Output:
a: 10
b: 4.5
c: 4.5
d: 4.5
e: 4.5
f: 9.0
2. (+=) Operator
This operator is a compound of “+” and “=” operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
a += 5;
System.out.println("a: " + a);
}
}
Output:
a: 15
Best Keyboards for Programming
3. (-=) Operator
This operator is a compound of “-” and “=” operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
a -= 5;
System.out.println("a: " + a);
}
}
Output:
a: 5
4. (*=) Operator
This operator is a compound of “*” and “=” operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
a *= 5;
System.out.println("a: " + a);
}
}
Output:
a: 50
5. (/=) Operator
This operator is a compound of “/” and “=” operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
a /= 5;
System.out.println("a: " + a);
}
}
Output:
a: 2
6. (%=) Operator
This operator is a compound of “%” and “=” operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
int a = 10;
a %= 5;
System.out.println("a: " + a);
}
}
Output:
a: 0