Java Program on Assignment Operator

In the previous article, we have discussed about Java Program on Decrement Operator

In this article we will see the use of assignment operator in Java programming language.

Java Program on Assignment Operator

Assignment Operator:

Assignment operator is used to assign any value to a variable.

Syntax: Variable = Value

Where,

  • Variable represents the name of the variable.
  • Value represents any particular type of value which is assigned to the Variable.
  • = symbol represents assignment operator means Value is assigned to Variable.

Let’s know more abut assignment operator.

Important Points about Assignment Operator:

  1. While using assignment operator then Left hand side will be variable and right hand side will be value.
  2. Value assigned to variable must be same as the type of variable.

Types of Assignment Operator:

There are 2 types of assignment operator.

  1. Simple Assignment Operator: When assignment operator is used individually.
  2. Compound Assignment Operator: When assignment operator used along with +,-,*, and / operator.

Simple Assignment Operator:

Simple assignment operator is the straight forward operator which is used to assign a value to a variable.

Example:

import java.io.*;
 
class Main 
{
    public static void main(String[] args)
    {
        //Declaring variables
        int number = 16;
        String text = "BtechGeeks";
        
        //print assigned values
        System.out.println("Number = " + number);
        System.out.println("Text = " + text);
    }
}
Output:

Number = 16
Text = BtechGeeks

Compound Assignment Operator:

+= Operator:

Syntax: a+=b;

Means a=a+b;

-= Operator:

Syntax: a-=b;

Means a=a-b;

*= Operator:

Syntax: a*=b;

Means a=a*b;

/= Operator:

Syntax: a/=b;

Means a=a/b;

%= Operator:

Syntax: a%=b;

Means a=a%b;

Let’s see the Program:

import java.io.*;
 
class Main 
{
    public static void main(String[] args)
    {
        //Declaring variables
        int a = 16;
        int b = 4;
        
        //print results
        System.out.println("By using += operator: " + (a+=b));
        System.out.println("By using -= operator: " + (a-=b));
        System.out.println("By using *= operator: " + (a*=b));
        System.out.println("By using /= operator: " + (a/=b));
        System.out.println("By using %= operator: " + (a%=b));
        
    }
}
Output:

By using += operator: 20
By using -= operator: 16
By using *= operator: 64
By using /= operator: 16
By using %= operator: 0

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: