Table of Contents

    Java Assignment Operators: Examples and Usage

    Java Assignment Operators: Examples and Usage

    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 );
    
       }
    }

    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 = 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 . . .
    Practice Quiz 14 MCQs Smart Learning

    Master This Topic with Smart Practice

    Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.

    Topic-wise MCQs
    Instant Results
    Improve Accuracy
    Exam Ready Practice
    Login & Start Quiz Create Free Account
    Save progress • Track results • Learn faster