Showing posts with label Java Compound Assignment Operator. Show all posts
Showing posts with label Java Compound Assignment Operator. Show all posts

Monday, 16 February 2015

Java Program to Demonstrate the Compound Assignment Operators

Compound Assignment Operator Example Program in Java

A Program to show the use of Compound Assignment Operator


               The program shows a few compound assignment operators and how it can be used in programs to write program intelligently. This helps to reduce a few lines while writing a program. It is also efficient than normal coding.

Program:


// Demonstrate compound assignment operators.

public class CompoundAssignemntOperators {
    
    public static void main(String[] args) {
        
        int x = 1;
        int y = 3;
        int z = 5;
        
        x += 2;                    //Equals to x=x+2; Now x=3;
        y *= 4;                    //Equals to y=y*4; Now y=12;
        z += x * y;              // z= z+(x*y); Now z=41 i.e z=5+(3*12)
        z %= 6;                  // z= z%6; Now z=5; i.e z=41%6
        
        System.out.println("x = " + x);
        System.out.println("y = " + y);
        System.out.println("z = " + z);
    }
    
}

Output:


x = 3
y = 12
z = 5

Compound Assignment Operators Example Program

Monday, 26 January 2015

Arithmetic Compound Assignment Operators

Java Arithmetic Compound Operator

Compound Assignment Operators in Java

       
               Java gives special operators to combine an arithmetic operator with an assignment and which is known as Compound Assignment Operator. This session describes how it works and its benefits.

Consider the following addition and subtraction statements,

                         a = a + 5;
                         b = b - 5;

These statements can be rewritten as follows with the help of Compound Assignment Operator.

                         a += 5;
                         b -= 5;

Compound Assignment operators are available for all arithmetic and binary operators.

Syntax:


General Form:

                        var = var op expression;

Compound assignment Operator Form:

                         var op= expression;

Examples:


 General Form  Compound Assignment Operator Form
 a = a - 5;  a -= 5;
 a = a + 5;  a += 5
 a = a % 5;  a %= 5
 a = a / 5  a /= 5
 a = a * 5  a *= 5

Advantages of Compound Assignment Operators

       
          The Compound Assignment Operators are used by Java Professionals to attain two major benefits.

          1. Compound Assignment Operators are shorthand and saves a few letters every time when you type Java Code.

          2. It is efficient than its equivalent long form in some cases.