[go: up one dir, main page]

Open In App

Java Assignment Operators with Examples

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

variable operator value;

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax: 

num1 = num2;

Example: 

a = 10;
ch = 'y';

Java




// Java code to illustrate "=" operator
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
        // Declaring variables
        int num;
        String name;
 
        // Assigning values
        num = 10;
        name = "GeeksforGeeks";
 
        // Displaying the assigned values
        System.out.println("num is assigned: " + num);
        System.out.println("name is assigned: " + name);
    }
}


Output

num is assigned: 10
name is assigned: GeeksforGeeks

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Syntax: 

num1 += num2;

Example: 

a += 10

This means,
a = a + 10

Java




// Java code to illustrate "+="
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
 
        // Declaring variables
        int num1 = 10, num2 = 20;
 
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Adding & Assigning values
        num1 += num2;
 
        // Displaying the assigned values
        System.out.println("num1 = " + num1);
    }
}


Output

num1 = 10
num2 = 20
num1 = 30

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5.

int x = 5;

If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this:

Method 1: x = x + 4.5

Method 2: x += 4.5

As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “incompatible types: possible lossy conversion from double to int“, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error.

Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int. It is equivalent to x = (int) (x + 4.5), where the result of the addition is explicitly cast to an int. The fractional part of the double value is truncated, and the resulting int value is assigned back to x.

It is advisable to use Method 2 (x += 4.5) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -=, *=, /=, and %=.

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

Syntax: 

num1 -= num2;

Example: 

a -= 10

This means,
a = a - 10

Java




// Java code to illustrate "-="
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
 
        // Declaring variables
        int num1 = 10, num2 = 20;
 
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Subtracting & Assigning values
        num1 -= num2;
 
        // Displaying the assigned values
        System.out.println("num1 = " + num1);
    }
}


Output

num1 = 10
num2 = 20
num1 = -10

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Syntax: 

num1 *= num2;

Example: 

a *= 10
This means,
a = a * 10

Java




// Java code to illustrate "*="
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
 
        // Declaring variables
        int num1 = 10, num2 = 20;
 
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Multiplying & Assigning values
        num1 *= num2;
 
        // Displaying the assigned values
        System.out.println("num1 = " + num1);
    }
}


Output

num1 = 10
num2 = 20
num1 = 200

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

Syntax: 

num1 /= num2;

Example: 

a /= 10
This means,
a = a / 10

Java




// Java code to illustrate "/="
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
 
        // Declaring variables
        int num1 = 20, num2 = 10;
 
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Dividing & Assigning values
        num1 /= num2;
 
        // Displaying the assigned values
        System.out.println("num1 = " + num1);
    }
}


Output

num1 = 20
num2 = 10
num1 = 2

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Syntax: 

num1 %= num2;

Example: 

a %= 3

This means,
a = a % 3

Java




// Java code to illustrate "%="
 
import java.io.*;
 
class Assignment {
    public static void main(String[] args)
    {
 
        // Declaring variables
        int num1 = 5, num2 = 3;
 
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Moduling & Assigning values
        num1 %= num2;
 
        // Displaying the assigned values
        System.out.println("num1 = " + num1);
    }
}


Output

num1 = 5
num2 = 3
num1 = 2


Previous Article
Next Article

Similar Reads

Compound assignment operators in Java
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a
7 min read
Array Variable Assignment in Java
An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1. Element Level Promotion Element-level promotions are not applicable at the array
3 min read
Interesting facts about Array assignment in Java
Prerequisite : Arrays in Java While working with arrays we have to do 3 tasks namely declaration, creation, initialization or Assignment. Declaration of array : int[] arr; Creation of array : // Here we create an array of size 3 int[] arr = new int[3]; Initialization of array : arr[0] = 1; arr[1] = 2; arr[3] = 3; int intArray[]; // declaring array
4 min read
Difference between Simple and Compound Assignment in Java
Many programmers believe that the statement "x += i" is simply a shorthand for "x = x + i". This isn’t quite true. Both of these statements are assignment expressions. The second statement uses the simple assignment operator (=), whereas the first uses a compound assignment operator. The compound assignment operators are +=, -=, *=, /=, %= etc. The
2 min read
Java Arithmetic Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Java Logical Operators with Examples
Logical operators are used to perform logical "AND", "OR" and "NOT" operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND
10 min read
Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
10 min read
Short Circuit Logical Operators in Java with Examples
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to effi
3 min read
Java | Operators | Question 1
Predict the output of following Java Program class Test { public static void main(String args[]) { int x = -4; System.out.println(x>>1); int y = 4; System.out.println(y>>1); } } (A) Compiler Error: Operator >> cannot be applied to negative numbers (B) -2 2 (C) 2 2 (D) 0 2 Answer: (B) Explanation: See https://www.geeksforgeeks.org/
1 min read
Java | Operators | Question 2
Predict the output of following Java program. Assume that int is stored using 32 bits. class Test { public static void main(String args[]) { int x = -1; System.out.println(x>>>29); System.out.println(x>>>30); System.out.println(x>>>31); } } (A) 7 3 1 (B) 15 7 3 (C) 0 0 0 (D) 1 1 1 Answer: (A) Explanation: Please see https
1 min read
Article Tags :
Practice Tags :