Java Assignment Operators: Examples and Usage
☰Fullscreen
Table of Content:
This is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in AssignmentOperator.java file. Compile and run this program
Example of Assignment Operator
public class AssignmentOperator { public static void main(String args[]) { int a = 5; int b = 10; int c = 0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c += a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a ; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c /= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c &= a ; System.out.println("c &= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a ; System.out.println("c |= a = " + c ); c <<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); } }
Output
c = a + b = 15 c += a = 20 c -= a = 15 c *= a = 75 c /= a = 1 c %= a = 5 c &= a = 0 c ^= a = 10 c |= a = 10 c <<= 2 = 40 c >>= 2 = 10 c >>= 2 = 2 Press any key to continue . . .
Problem in addition of two short datatype
class OperatorAddShortExample{ public static void main(String args[]){ short a=10; short b=10; //a+=b;//a=a+b internally so fine a=a+b;//Compile time error because 10+10=20 now int System.out.println(a); } }
Output
OperatorAddShortExample.java:6: error: incompatible types: possible lossy conversion from int to short a=a+b;//Compile time error because 10+10=20 now int ^ 1 error
solution of the above problem using type conversion
class OperatorAddShortExample{ public static void main(String args[]){ short a=10; short b=10; a=(short)(a+b);//20 which is int now converted to short System.out.println(a); } }
Output
20 Press any key to continue . . .