Java Assignment Operators with Examples
Last Updated :
13 Sep, 2023
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:
- Arithmetic Operators
- Unary Operators
- Assignment Operator
- Relational Operators
- Logical Operators
- Ternary Operator
- Bitwise Operators
- 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);
}
}
Outputnum 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 += 10This 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);
}
}
Outputnum1 = 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 -= 10This 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);
}
}
Outputnum1 = 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);
}
}
Outputnum1 = 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);
}
}
Outputnum1 = 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 %= 3This 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);
}
}
Outputnum1 = 5
num2 = 3
num1 = 2
Similar Reads
Basics of Java
If you are new to the world of coding and want to start your coding journey with Java, then this learn Java a beginners guide gives you a complete overview of how to start Java programming. Java is among the most popular and widely used programming languages and platforms. A platform is an environme
10 min read
Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
9 min read
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynam
6 min read
In the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
6 min read
Java is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w
6 min read
Java is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
6 min read
Understanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is:JDK: Java Development Kit is a software develo
3 min read
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one sy
7 min read
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 2
2 min read
Variables & DataTypes in Java
In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated.Key Components of Variables in Java:A variable in Java has three components, which are listed below:Data Type: Defines the kind
9 min read
The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
7 min read
Java is statically typed and also a strongly typed language because each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be declared with the specifi
15 min read
Operators in Java
Java operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
15 min read
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
6 min read
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
7 min read
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 p
8 min read
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
10 min read
Logical operators are used to perform logical "AND", "OR", and "NOT" operations, i.e., the functions 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 consider
8 min read
Operators constitute the basic building block of any programming language. Java provides many types of operators that 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 provi
5 min read
In Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming.There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level. T
6 min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Multidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
10 min read
In Java, Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. Example:arr [][]= { {1,2}, {3,4,5,6},{7,8,9}};So, here you can check that the number of columns in row1!=row2!=row3. That
5 min read
Strings in Java
In Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi
9 min read
A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c
11 min read
In Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations.Declaration:StringBuilder sb = new
7 min read
OOPS in Java
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
11 min read
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
8 min read
In Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
7 min read
A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
6 min read
Firstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These metho
3 min read