Assignment operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =.
In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:
Syntax:
variable = expression;
Example:
int a = 6;
float b = 6.8F;
Compound Assignment Operators in Java
Operator | Meaning |
---|---|
+= | Increments then assigns |
-= | Decrements then assigns |
*= | Multiplies then assigns |
/= | Divides then assigns |
%= | Modulus then assigns |
<<= | Binary Left Shift and assigns |
>>= | Binary Right Shift and assigns |
>>>= | Shift right zero fill and assigns |
&= | Binary AND assigns |
^= | Binary exclusive OR and assigns |
|= | Binary inclusive OR and assigns |
Programs to Show How Assignment Operators Works
Example:
//Programs to Show How Assignment and Compound Assignment Operators Works
public class assignmntop {
public static void main(String[] args) {
//Simple assigns
byte bt = 24;
System.out.println("bt: " + bt);
//Increments then assigns
bt += 10;
System.out.println("bt: " + bt);
//Decrements then assigns
bt -= 2;
System.out.println("bt: " + bt);
//Multiplies then assigns
bt *= 2;
System.out.println("bt: " + bt);
//Divides then assigns
bt /= 2;
System.out.println("bt: " + bt);
//Modulus then assigns
bt %= 7;
System.out.println("bt: " + bt);
//Binary Left Shift and assigns
bt <<= 3;
System.out.println("bt: " + bt);
//Binary Right Shift and assigns
bt >>= 4;
System.out.println("bt: " + bt);
//Shift right zero fill and assigns
bt >>>= 1;
System.out.println("bt: " + bt);
//Binary AND assigns
bt &= 4;
System.out.println("bt: " + bt);
//Binary exclusive OR and assigns
bt ^= 4;
System.out.println("bt: " + bt);
//Binary inclusive OR and assigns
bt |= 4;
System.out.println("bt: " + bt);
}
}
Output:
bt: 24 bt: 34 bt: 32 bt: 64 bt: 32 bt: 4 bt: 32 bt: 2 bt: 1 bt: 0 bt: 4 bt: 4
JNNC Technologies Pvt Ltd is a comprehensive repository
for online, offline courses offering high quality state-of-the-art IT and
business related training and courses. JNNC commenced its IT Education & training
business and has trained over thousands of students. JNNC is an ISO 9001:2009
certified training institute with its presence...
0 Comments
If you have any doubts,please let me know