Sep 13, 2023 · 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 ... ... The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −. Example 1. In this example, we're creating three variables a,b and c and using assignment operators. We've performed simple assignment, addition AND assignment ... ... In the above example, the variable x is assigned the value 10. Addition Assignment Operator (+=) To add a value to a variable and subsequently assign the new value to the same variable, use the addition assignment operator (+=). ... Below, we have explained each assignment operator in Java with examples. Simple Assignment Operator (=) We’ll start with the most straightforward and simple assignment operator (=), which is used to assign a value of the variable on the right to the variable on the left. ... Java Assignment Operators Assignment operators are used to assign values to variables. In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x : ... Oct 15, 2022 · Operator is a symbol that instructs the compiler to perform a specific action. For example, a "+" operator instructs the compiler to perform addition, a ">" operator instructs the compiler to perform comparison, "=" for assignment and so on. The operators in java are classified in eight different categories. In this guide, we will mainly ... In this tutorial, we will learn about different Assignment Operators available in Java programming language and go through each of these Assignment Operations in detail, with the help of examples. Operator Symbol – Example – Description. The following table specifies symbol, example, and description for each of the Assignment Operator in Java. ... Aug 19, 2022 · Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8; ... Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types : Assignment operator or simple assignment operator; Compound assignment operators ... Sep 26, 2024 · Assignment Operators in Java Introduction Assignment operators are fundamental in Java for assigning values to variables. Beyond the basic = operator, Java provides several compound assignment operators that simplify coding tasks. This article will cover the different types of assignment operators, their syntax, and practical use cases with examples from the project file. Mastering assignment ... ">
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Java Assignment Operators with Examples

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, 

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:  

Example:  

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. 

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 “i ncompatible 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. 

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. 

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. 

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. 

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 10 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
  • Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 22. Below are the environ 6 min read
  • Java is an object-oriented programming language which 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. Let's understand the Syntax and Structure of Java Programs with a basic 5 min read
  • Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn h 5 min read
  • Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java 5 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 s 7 min read
  • An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names and every Java Variables must be identified with unique names. Example: public class Test{ public static void main(String[] args) { int a = 20; }}In the above Java code, we h 2 min read

Variables & DataTypes in Java

  • Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val 8 min read
  • Scope of a variable 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 function call stack. Java programs are organized in the form of cla 5 min read
  • Java is statically typed and also a strongly typed language because, in Java, 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 described with 11 min read

Operators in Java

  • Java operators are special symbols that perform operations on variables or values. They can be classified into several categories based on their functionality. These operators play a crucial role in performing arithmetic, logical, relational, and bitwise operations etc. Example: Here, we are using + 14 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 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 considerati 10 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 4 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 6 min read

Packages in Java

  • Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.EmployeeMaking searching/locatin 8 min read

Flow Control in Java

  • Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program base 7 min read
  • The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not. Example: [GFGTABS] Java // Java program to ill 5 min read
  • The if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples. Example: [GF 4 min read
  • The Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback. Example: The 3 min read

Loops in Java

  • Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax an 7 min read
  • Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections. Example: [GFGTABS] Java class Geeks { pu 4 min read
  • Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGT 3 min read
  • Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // 4 min read
  • The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required. Example: Below is a basic e 6 min read

Jump Statements in Java

  • In Java, continue statement is used inside the loops such as for, while and do-while to skip the curren iteration and move directly to the next iteration of the loop. Example: [GFGTABS] Java // Java Program to illustrate the use of continue statement public class GFG { public static void main(String 4 min read
  • The Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example: [GFGTABS] 3 min read
  • In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:  Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrat 6 min read

Arrays in Java

  • Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with e 15+ min read
  • A multidimensional array can be defined as an array of arrays. Data in multidimensional arrays are stored in tabular form (row-major order).  Example: [GFGTABS] Java // Java Program to Demonstrate // Multi Dimensional Array import java.io.*; public class Main { public static void main(String[] args) 9 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. Tha 5 min read

Strings in Java

  • In Java, String is the type of objects that can store the 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, allowing 9 min read
  • 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 will learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import java.io.*; 7 min read
  • StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time. Features of StringBuffer ClassHere are some important features and met 12 min read
  • StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much s 6 min read

OOPS in Java

  • As the name suggests, Object-Oriented Programming or Java OOPs concept refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks you assign. Object-oriented programmin 12 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. For example, the animal type Dog is a class while a particular dog named 11 min read
  • The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every metho 10 min read
  • In Java, Access modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc. to the user depending upon the access modifier used with the element. In this article, let us learn about Java Access Modifiers, their types, and 6 min read
  • A Wrapper class in Java is a class whose object wraps or contains primitive data types. When we create an object to 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 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

Constructors in Java

  • Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attrib 8 min read
  • Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own. A prerequisite prior to learning copy constructors is to learn about constructors in java to deeper roots. Below is an example Java program that shows a simpl 4 min read
  • Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. Prerequ 5 min read
  • Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various 2 min read

Inheritance & Polymorphism in Java

  • Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from ano 13 min read
  • Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which c 6 min read
  • The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit fr 4 min read
  • The word 'polymorphism' means 'having many forms'. In simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type. Real-life Illustration of Polymorphism in Java: A person can have d 6 min read
  • Prerequisite: Overriding in java, Inheritance Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. When an overridden method is called thro 5 min read

Method overloading & Overiding

  • In Java, Method Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static Polym 9 min read
  • If a class has multiple methods having same name but parameters of the method should be different is known as Method Overloading.If we have to perform only one operation, having same name of the methods increases the readability of the program.Suppose you have to perform addition of the given number 7 min read
  • In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or 13 min read
  • The differences between Method Overloading and Method Overriding in Java are as follows: Method Overloading Method Overriding Method overloading is a compile-time polymorphism.Method overriding is a run-time polymorphism.Method overloading helps to increase the readability of the program.Method over 4 min read

Abstraction & Encapsulation

  • Abstraction in Java is the process in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. In this article, we will learn about abstraction and what abstraction means. Simple Example to understand Abstraction:Televisi 11 min read
  • In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-abstract methods(methods with bodies). An abstract is a Java modifier applicable for classes and methods in Java but not for Variables. In this article, we will learn the use of abstract classes in Java. 10 min read
  • In object-oriented programming (OOP), both abstract classes and interfaces serve as fundamental constructs for defining contracts. They establish a blueprint for other classes, ensuring consistent implementation of methods and behaviors. However, they each come with distinct characteristics and use 10 min read
  • Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. Java Encapsulation is a way of hiding the implementation details of a class from outsid 8 min read

Interfaces in Java

  • An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to ac 11 min read
  • We can declare interfaces as members of a class or another interface. Such an interface is called a member interface or nested interface. Interfaces declared outside any class can have only public and default (package-private) access specifiers. In Java, nested interfaces (interfaces declared inside 5 min read
  • It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. public interface Serializable { // nothing here } Examples of Marker Interface which are used in real-time applications : Cloneabl 3 min read
  • Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simp 10 min read
  • A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):Suppose we have an Array/ArrayList of our own class 6 min read

Keywords in Java

  • In Java, Keywords are the Reserved words in a programming language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Example : [GFGTABS] Java // Java Program to demonstrate Keywords class GFG { pub 5 min read
  • The super keyword in Java is a reference variable that is used to refer to parent class when we're working with objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.  The Keyword "super" came into the picture with the concept of Inheritance. In thi 8 min read
  • The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java. The following are different contexts where the final is used: VariableMethodClass The final keyword is used to define constants or prevent inheritance 12 min read
  • In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Ab 7 min read
  • The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than an i 9 min read
  • In Java, 'this' is a reference variable that refers to the current object, or can be said "this" in Java is a keyword that refers to the current object instance. It can be used to call current class methods and fields, to pass an instance of the current class as a parameter, and to differentiate bet 6 min read
  • In Java,Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. What is Enumeration or Enum in Java?A Ja 11 min read

Exception Handling in Java

  • Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. What are Ja 10 min read
  • Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situati 8 min read
  • In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked exceptionsUnchecked exceptions Understanding the difference betwee 5 min read
  • In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, 4 min read
  • In this article, we'll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. Control flow in try-catch clause OR try-catch-finally clause Case 1: Exception occurs in try block and handle 6 min read
  • In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as NullPointerException, ArrayIndexOutOfBoundsException, etc. In this article, we will 4 min read
  • An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which ar 3 min read

Collection Framework

  • Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac 15+ min read
  • Collections class in Java is one of the utility classes in Java Collections Framework. The java.util package contains the Collections class in Java. Java Collections class is used with the static methods that operate on the collections or return the collection. All the methods of this class throw th 13 min read
  • The List Interface in Java extends the Collection Interface and is a part of java.util package. It is used to store the ordered collections of elements. So in a Java List, you can organize and manage the data sequentially. Maintained the order of elements in which they are added.Allows the duplicate 15+ min read
  • Java ArrayList is a part of collections framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in array is required. The main advantage of ArrayList is, unli 10 min read
  • The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface. Thread-Safe: All methods are synchronized, making it suitable for multi-threaded environments. 13 min read
  • Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of LIFO(last-in-first-out). In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The Stack cl 11 min read
  • Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr 13 min read
  • The Queue Interface is present in java.util package and extends the Collection interface. It stores and processes the data in FIFO(First In First Out) order. It is an ordered list of objects limited to inserting elements at the end of the list and deleting elements from the start of the list. No Nul 13 min read
  • The PriorityQueue class in Java is part of the java.util package. It is known that a Queue follows the FIFO(First-In-First-Out) Algorithm, but the elements of the Queue are needed to be processed according to the priority, that's when the PriorityQueue comes into play. The PriorityQueue is based on 11 min read
  • Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/ 10 min read
  • The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. T 13 min read
  • The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of the dupl 14 min read
  • HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon 12 min read
  • LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el 8 min read
  • The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this 8 min read
  • NavigableSet represents a navigable set in Java Collection Framework. The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet. For example, the Na 9 min read
  • TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ 13 min read
  • In Java, Map Interface is present in java.util package represents a mapping between a key and a value. Java Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. No Duplicates in Keys: Ensures that keys are unique. H 12 min read
  • In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding 15+ min read
  • The Hashtable class, introduced as part of the original Java Collections framework, implements a hash table that maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashC 13 min read
  • LinkedHashMap in Java implements the Map interface of the Collections Framework. It stores key-value pairs while maintaining the insertion order of the entries. It maintains the order in which elements are added. Stores unique key-value pairs.Maintains insertion order.Allows one null key and multipl 7 min read
  • SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap. The SortedMap interface is a subinterface of the jav 11 min read
  • Let us start with a simple Java code snippet that demonstrates how to create and use a TreeMap in Java. [GFGTABS] Java import java.util.Map; import java.util.TreeMap; public class TreeMapCreation { public static void main(String args[]) { // Create a TreeMap of Strings (keys) and Integers (values) T 15+ min read

Multi-threading in Java

  • Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : Extending the Th 3 min read
  • A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any inst 6 min read
  • Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i 4 min read
  • As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be give 5 min read
  • Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service 9 min read
  • Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. Why use Java Synchronization?Java Synchronization is used to make sure by some synchronization method that only one thread can access th 5 min read
  • Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent the 7 min read
  • Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes 10 min read
  • As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already wor 5 min read
  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

  • Java Developer's AI Tools
  • Java - AI Assistant
  • Java - AI Code Generator
  • Java - AI Code Converter
  • Java - AI Code Debugger
  • Java - AI Code Reviewer
  • Java - AI Code Explainer
  • Java - AI Code Refactoring
  • Java - AI Code Documentation
  • Java - AI Based Interview Preparation

Java Tutorial

  • Java - Home
  • Java - Overview
  • Java - History
  • Java - Features
  • Java Vs. C++
  • JVM - Java Virtual Machine
  • Java - JDK vs JRE vs JVM
  • Java - Hello World Program
  • Java - Environment Setup
  • Java - Basic Syntax
  • Java - Variable Types
  • Java - Data Types
  • Java - Type Casting
  • Java - Unicode System
  • Java - Basic Operators
  • Java - Comments
  • Java - User Input
  • Java - Date & Time

Java Control Statements

  • Java - Loop Control
  • Java - Decision Making
  • Java - If-else
  • Java - Switch
  • Java - For Loops
  • Java - For-Each Loops
  • Java - While Loops
  • Java - do-while Loops
  • Java - Break
  • Java - Continue

Object Oriented Programming

  • Java - OOPs Concepts
  • Java - Object & Classes
  • Java - Class Attributes
  • Java - Class Methods
  • Java - Methods
  • Java - Variables Scope
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Aggregation
  • Java - Polymorphism
  • Java - Overriding
  • Java - Method Overloading
  • Java - Dynamic Binding
  • Java - Static Binding
  • Java - Instance Initializer Block
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner Classes
  • Java - Static Class
  • Java - Anonymous Class
  • Java - Singleton Class
  • Java - Wrapper Classes
  • Java - Enums
  • Java - Enum Constructor
  • Java - Enum Strings
  • Java - Reflection

Java Built-in Classes

  • Java - Number
  • Java - Boolean
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Math Class

Java File Handling

  • Java - Files
  • Java - Create a File
  • Java - Write to File
  • Java - Read Files
  • Java - Delete Files
  • Java - Directories
  • Java - I/O Streams

Java Error & Exceptions

  • Java - Exceptions
  • Java - try-catch Block
  • Java - try-with-resources
  • Java - Multi-catch Block
  • Java - Nested try Block
  • Java - Finally Block
  • Java - throw Exception
  • Java - Exception Propagation
  • Java - Built-in Exceptions
  • Java - Custom Exception
  • Java - Annotations
  • Java - Logging
  • Java - Assertions

Java Multithreading

  • Java - Multithreading
  • Java - Thread Life Cycle
  • Java - Creating a Thread
  • Java - Starting a Thread
  • Java - Joining Threads
  • Java - Naming Thread
  • Java - Thread Scheduler
  • Java - Thread Pools
  • Java - Main Thread
  • Java - Thread Priority
  • Java - Daemon Threads
  • Java - Thread Group
  • Java - Shutdown Hook

Java Synchronization

  • Java - Synchronization
  • Java - Block Synchronization
  • Java - Static Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Interrupting a Thread
  • Java - Thread Control
  • Java - Reentrant Monitor

Java Networking

  • Java - Networking
  • Java - Socket Programming
  • Java - URL Processing
  • Java - URL Class
  • Java - URLConnection Class
  • Java - HttpURLConnection Class
  • Java - Socket Class
  • Java - ServerSocket Class
  • Java - InetAddress Class
  • Java - Generics

Java Collections

  • Java - Collections
  • Java - Collection Interface

Java Interfaces

  • Java - List Interface
  • Java - Queue Interface
  • Java - Map Interface
  • Java - SortedMap Interface
  • Java - Set Interface
  • Java - SortedSet Interface

Java Data Structures

  • Java - Data Structures
  • Java - Enumeration

Java Collections Algorithms

  • Java - Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Comparable Interface in Java

Advanced Java

  • Java - Command-Line Arguments
  • Java - Lambda Expressions
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Javadoc Comments
  • Java - Autoboxing and Unboxing
  • Java - File Mismatch Method
  • Java - REPL (JShell)
  • Java - Multi-Release Jar Files
  • Java - Private Interface Methods
  • Java - Inner Class Diamond Operator
  • Java - Multiresolution Image API
  • Java - Collection Factory Methods
  • Java - Module System
  • Java - Nashorn JavaScript
  • Java - Optional Class
  • Java - Method References
  • Java - Functional Interfaces
  • Java - Default Methods
  • Java - Base64 Encode Decode
  • Java - Switch Expressions
  • Java - Teeing Collectors
  • Java - Microbenchmark
  • Java - Text Blocks
  • Java - Dynamic CDS archive
  • Java - Z Garbage Collector (ZGC)
  • Java - Null Pointer Exception
  • Java - Packaging Tools
  • Java - NUMA Aware G1
  • Java - Sealed Classes
  • Java - Record Classes
  • Java - Hidden Classes
  • Java - Pattern Matching
  • Java - Compact Number Formatting
  • Java - Programming Examples
  • Java - Garbage Collection
  • Java - JIT Compiler

Java Miscellaneous

  • Java - Recursion
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Process API Improvements
  • Java - Stream API Improvements
  • Java - Enhanced @Deprecated Annotation
  • Java - CompletableFuture API Improvements
  • Java - Maths Methods
  • Java - Streams
  • Java - Datetime Api
  • Java 8 - New Features
  • Java 9 - New Features
  • Java 10 - New Features
  • Java 11 - New Features
  • Java 12 - New Features
  • Java 13 - New Features
  • Java 14 - New Features
  • Java 15 - New Features
  • Java 16 - New Features
  • Java - Keywords Reference

Java APIs & Frameworks

  • JDBC Tutorial
  • SWING Tutorial
  • AWT Tutorial
  • Servlets Tutorial
  • JSP Tutorial

Java Class References

  • Java - Scanner
  • Java - Date
  • Java - ArrayList
  • Java - Vector
  • Java - Stack
  • Java - PriorityQueue
  • Java - Deque Interface
  • Java - LinkedList
  • Java - ArrayDeque
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - TreeMap
  • Java - IdentityHashMap
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - TreeSet
  • Java - BitSet
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java - Collection
  • Java - Array

Java Useful Resources

  • Java Cheatsheet
  • Java Compiler
  • Java - Questions and Answers
  • Java 8 - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Java - Assignment Operators with Examples

Java assignment operators.

Following are the assignment operators supported by Java language −

The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −

In this example, we're creating three variables a,b and c and using assignment operators . We've performed simple assignment, addition AND assignment, subtraction AND assignment and multiplication AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Divide AND assignment, Multiply AND assignment, Modulus AND assignment, bitwise exclusive OR AND assignment, OR AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Left shift AND assignment, Right shift AND assignment, operations and printed the results.

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Advertisement

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100

Video: Java Operators

Java Tutorial on YouTube

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

TutorialKart

  • Java Basics
  • Java Tutorial
  • Java HelloWorld Program
  • Java Program Structure
  • Java Datatypes
  • Java Variable Types
  • Java Access Modifiers
  • Java Operators
  • Java Decision Making
  • Print array
  • Initialize array
  • Array of integers
  • Array of strings
  • Array of objects
  • Array of arrays
  • Iterate over array
  • Array For loop
  • Array while loop
  • Append element to array
  • Check if array is empty
  • Array average
  • Check if array contains
  • Array ForEach
  • Array - Find Index of Item
  • Concatenate arrays
  • Find smallest number in array
  • Find largest number in array
  • Array reverse
  • Classes and Objects
  • Inheritance
  • Polymorphism
  • Method Overloading
  • Method Overriding/
  • Abstraction
  • Abstract methods and classes
  • Encapsulation
  • Print string
  • Read string from console
  • Create string from Char array
  • Create string from Byte array
  • Concatenate two strings
  • Get index of the first Occurrence of substring
  • Get index of nth occurrence of substring
  • Check if two strings are equal
  • Check if string ends with specific suffix
  • Check if string starts with specific prefix
  • Check if string is blank
  • Check if string is empty
  • Check if string contains search substring
  • Validate if string is a Phone Number
  • Character Level
  • Get character at specific index in string
  • Get first character in string
  • Get last character from string
  • Transformations
  • Replace first occurrence of string
  • Replace all occurrences of a string
  • Join strings
  • Join strings in string array
  • Join strings in ArrayList
  • Reverse a string
  • Trim string
  • Split string
  • Remove whitespaces in string
  • Replace multiple spaces with single space
  • Comparisons
  • Compare strings lexicographically
  • Compare String and CharSequence
  • Compare String and StringBuffer
  • Java Exception Handling StringIndexOutOfBoundsException
  • Convert string to int
  • Convert string to float
  • Convert string to double
  • Convert string to long
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Convert int to double
  • Convert int to long
  • Convert int to char
  • Convert float to string
  • Convert float to int
  • Convert long to string
  • Convert double to string
  • Convert boolean to string
  • Create a file
  • Read file as string
  • Write string to file
  • Delete File
  • Rename File
  • Download File from URL
  • Replace a String in File
  • Filter list of files or directories
  • Check if file is readable
  • Check if file is writable
  • Check if file is executable
  • Read contents of a file line by line using BufferedReader
  • Read contents of a File line by line using Stream
  • Check if n is positive or negative
  • Read integer from console
  • Add two integers
  • Count digits in number
  • Largest of three numbers
  • Smallest of three numbers
  • Even numbers
  • Odd numbers
  • Reverse a number
  • Prime Number
  • Print All Prime Numbers
  • Factors of a Number
  • Check Palindrome number
  • Check Palindrome string
  • Swap two numbers
  • Even or Odd number
  • Java Classes
  • ArrayList add()
  • ArrayList addAll()
  • ArrayList clear()
  • ArrayList clone()
  • ArrayList contains()
  • ArrayList ensureCapacity()
  • ArrayList forEach()
  • ArrayList get()
  • ArrayList indexOf()
  • ArrayList isEmpty()
  • ArrayList iterator()
  • ArrayList lastIndexOf()
  • ArrayList listIterator()
  • ArrayList remove()
  • ArrayList removeAll()
  • ArrayList removeIf()
  • ArrayList removeRange()
  • ArrayList retainAll()
  • ArrayList set()
  • ArrayList size()
  • ArrayList spliterator()
  • ArrayList subList()
  • ArrayList toArray()
  • ArrayList trimToSize()
  • HashMap clear()
  • HashMap clone()
  • HashMap compute()
  • HashMap computeIfAbsent()
  • HashMap computeIfPresent()
  • HashMap containsKey()
  • HashMap containsValue()
  • HashMap entrySet()
  • HashMap get()
  • HashMap isEmpty()
  • HashMap keySet()
  • HashMap merge()
  • HashMap put()
  • HashMap putAll()
  • HashMap remove()
  • HashMap size()
  • HashMap values()
  • HashSet add()
  • HashSet clear()
  • HashSet clone()
  • HashSet contains()
  • HashSet isEmpty()
  • HashSet iterator()
  • HashSet remove()
  • HashSet size()
  • HashSet spliterator()
  • Integer bitCount()
  • Integer byteValue()
  • Integer compare()
  • Integer compareTo()
  • Integer doubleValue()
  • Integer equals()
  • Integer floatValue()
  • Integer getInteger()
  • Integer intValue()
  • Integer longValue()
  • Integer max()
  • Integer min()
  • Integer reverse()
  • Integer reverseBytes()
  • Integer rotateLeft()
  • Integer rotateRight()
  • Integer shortValue()
  • Integer signum()
  • Integer sum()
  • Integer toBinaryString()
  • Integer toHexString()
  • Integer toOctalString()
  • Integer toString()
  • StringBuilder append()
  • StringBuilder appendCodePoint()
  • StringBuilder capacity()
  • StringBuilder charAt()
  • StringBuilder chars()
  • StringBuilder codePointAt()
  • StringBuilder codePointBefore()
  • StringBuilder codePointCount()
  • StringBuilder codePoints()
  • StringBuilder delete()
  • StringBuilder deleteCharAt()
  • StringBuilder ensureCapacity()
  • StringBuilder getChars()
  • StringBuilder indexOf()
  • StringBuilder insert()
  • StringBuilder lastIndexOf()
  • StringBuilder length()
  • StringBuilder offsetByCodePoints()
  • StringBuilder replace()
  • StringBuilder reverse()
  • StringBuilder setCharAt()
  • StringBuilder setLength()
  • StringBuilder subSequence()
  • StringBuilder substring()
  • StringBuilder toString()
  • StringBuilder trimToSize()
  • Arrays.asList()
  • Arrays.copyOf()
  • Arrays.sort()
  • Random doubles()
  • Random ints()
  • Random longs()
  • Random next()
  • Random nextBoolean()
  • Random nextBytes()
  • Random nextDouble()
  • Random nextFloat()
  • Random nextGaussian()
  • Random nextInt()
  • Random nextLong()
  • Random setSeed()
  • Math random
  • Math signum
  • Math toDegrees
  • Math toRadians
  • Java Date & Time

Java Assignment Operators

Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand).

The syntax of any Assignment Operator with operands is

In this tutorial, we will learn about different Assignment Operators available in Java programming language and go through each of these Assignment Operations in detail, with the help of examples.

Operator Symbol – Example – Description

The following table specifies symbol, example, and description for each of the Assignment Operator in Java.

Simple Assignment

In the following example, we assign a value of 2 to x using Simple Assignment Operator.

Addition Assignment

In the following example, we add 3 to x and assign the result to x using Addition Assignment Operator.

Subtraction Assignment

In the following example, we subtract 3 from x and assign the result to x using Subtraction Assignment Operator.

Multiplication Assignment

In the following example, we multiply 3 to x and assign the result to x using Multiplication Assignment Operator.

Division Assignment

In the following example, we divide x by 3 and assign the quotient to x using Division Assignment Operator.

Remainder Assignment

In the following example, we divide x by 3 and assign the remainder to x using Remainder Assignment Operator.

Bitwise AND Assignment

In the following example, we do bitwise AND operation between x and 3 and assign the result to x using Bitwise AND Assignment Operator.

Bitwise OR Assignment

In the following example, we do bitwise OR operation between x and 3 and assign the result to x using Bitwise OR Assignment Operator.

Bitwise XOR Assignment

In the following example, we do bitwise XOR operation between x and 3 and assign the result to x using Bitwise XOR Assignment Operator.

Left-shift Assignment

In the following example, we left-shift x by 3 places and assign the result to x using Left-shift Assignment Operator.

Right-shift Assignment

In the following example, we right-shift x by 3 places and assign the result to x using Right-shift Assignment Operator.

In this Java Tutorial , we learned what Assignment Operators are, and how to use them in Java programs, with the help of examples.

Popular Courses

  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica

SAP Resources

  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Android Compose
  • Kotlin Android
  • Bash Script

Web & Server

  • Selenium Java
  • Definitions
  • General Knowledge

refresh java logo

  • Basics of Java
  • ➤ Java Introduction
  • ➤ History of Java
  • ➤ Getting started with Java
  • ➤ What is Path and Classpath
  • ➤ Checking Java installation and Version
  • ➤ Syntax in Java
  • ➤ My First Java Program
  • ➤ Basic terms in Java Program
  • ➤ Runtime and Compile time
  • ➤ What is Bytecode
  • ➤ Features of Java
  • ➤ What is JDK JRE and JVM
  • ➤ Basic Program Examples
  • Variables and Data Types
  • ➤ What is Variable
  • ➤ Types of Java Variables
  • ➤ Naming conventions for Identifiers
  • ➤ Data Type in Java
  • ➤ Mathematical operators in Java
  • ➤ Assignment operator in Java
  • ➤ Arithmetic operators in Java
  • ➤ Unary operators in Java
  • ➤ Conditional and Relational Operators
  • ➤ Bitwise and Bit Shift Operators
  • ➤ Operator Precedence
  • ➤ Overflow Underflow Widening Narrowing
  • ➤ Variable and Data Type Programs
  • Control flow Statements
  • ➤ Java if and if else Statement
  • ➤ else if and nested if else Statement
  • ➤ Java for Loop
  • ➤ Java while and do-while Loop
  • ➤ Nested loops
  • ➤ Java break Statement
  • ➤ Java continue and return Statement
  • ➤ Java switch Statement
  • ➤ Control Flow Program Examples
  • Array and String in Java
  • ➤ Array in Java
  • ➤ Multi-Dimensional Arrays
  • ➤ for-each loop in java
  • ➤ Java String
  • ➤ Useful Methods of String Class
  • ➤ StringBuffer and StringBuilder
  • ➤ Array and String Program Examples
  • Classes and Objects
  • ➤ Classes in Java
  • ➤ Objects in Java
  • ➤ Methods in Java
  • ➤ Constructors in Java
  • ➤ static keyword in Java
  • ➤ Call By Value
  • ➤ Inner/nested classes in Java
  • ➤ Wrapper Classes
  • ➤ Enum in Java
  • ➤ Initializer blocks
  • ➤ Method Chaining and Recursion
  • Packages and Interfaces
  • ➤ What is package
  • ➤ Sub packages in java
  • ➤ built-in packages in java
  • ➤ Import packages
  • ➤ Access modifiers
  • ➤ Interfaces in Java
  • ➤ Key points about Interfaces
  • ➤ New features in Interfaces
  • ➤ Nested Interfaces
  • ➤ Structure of Java Program
  • OOPS Concepts
  • ➤ What is OOPS
  • ➤ Inheritance in Java
  • ➤ Inheritance types in Java
  • ➤ Abstraction in Java
  • ➤ Encapsulation in Java
  • ➤ Polymorphism in Java
  • ➤ Runtime and Compile-time Polymorphism
  • ➤ Method Overloading
  • ➤ Method Overriding
  • ➤ Overloading and Overriding Differences
  • ➤ Overriding using Covariant Return Type
  • ➤ this keyword in Java
  • ➤ super keyword in Java
  • ➤ final keyword in Java

Assignment Operator in Java with Example

Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types :

  • Assignment operator or simple assignment operator
  • Compound assignment operators

What is assignment operator in java

The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand(variable) on its left side. For example :

The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be in the form of a constant value, a variable name, an expression, a method call returning a compatible value or a combination of these.

The value at right side of assignment operator must be compatible with the data type of left side variable, otherwise compiler will throw compilation error. Following are incorrect assignment :

Another important thing about assignment operator is that, it is evaluated from right to left . If there is an expression at right side of assignment operator, it is evaluated first then the resulted value is assigned in left side variable.

Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted value( 60 ) is assigned into x . Similarly in statement a = b = c , first the value of c which is 30 is assigned into b and then the value of b which is now 30 is assigned into a .

The variable at left side of an assignment operator can also be a non-primitive variable. For example if we have a class MyFirstProgram , we can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.

Is == an assignment operator ?

No , it's not an assignment operator, it's a relational operator used to compare two values.

Is assignment operator a binary operator

Yes , as it requires two operands.

Assignment operator program in Java

a = 2 b = 2 c = 4 d = 4 e = false

Java compound assignment operators

The assignment operator can be mixed or compound with other operators like addition, subtraction, multiplication etc. We call such assignment operators as compound assignment operator. For example :

Here the statement a += 10; is the short version of a = a + 10; the operator += is basically addition compound assignment operator. Similarly b *= 5; is short version of b = b * 5; the operator *= is multiplication compound assignment operator. The compound assignment can be in more complex form as well, like below :

List of all assignment operators in Java

The table below shows the list of all possible assignment(simple and compound) operators in java. Consider a is an integer variable for this table.

How many assignment operators are there in Java ?

Including simple and compound assignment we have total 12 assignment operators in java as given in above table.

What is shorthand operator in Java ?

Shorthand operators are nothing new they are just a shorter way to write something that is already available in java language. For example the code a += 5 is shorter way to write a = a + 5 , so += is a shorthand operator. In java all the compound assignment operator(given above) and the increment/decrement operators are basically shorthand operators.

Compound assignment operator program in Java

a = 20 b = 80 c = 30 s = 64 s2 = 110 b2 = 15

What is the difference between += and =+ in Java?

An expression a += 1 will result as a = a + 1 while the expression a =+ 1 will result as a = +1 . The correct compound statement is += , not =+ , so do not use the later one.

facebook page

Studyeasy

S02L08 – Assignment operators

Team StudyEasy

  • September 26, 2024
  • Course Articles , Java Articles

Assignment Operators in Java

Introduction.

Assignment operators are fundamental in Java for assigning values to variables. Beyond the basic = operator, Java provides several compound assignment operators that simplify coding tasks. This article will cover the different types of assignment operators, their syntax, and practical use cases with examples from the project file. Mastering assignment operators is essential for writing clean, concise, and efficient code.

What Are Assignment Operators?

Assignment operators in Java are used to assign values to variables. The most common assignment operator is the simple assignment = operator, which assigns the value on its right side to the variable on its left. Java also supports several compound assignment operators, which perform an operation and an assignment in one step.

Types of Assignment Operators

  • += (Addition assignment)
  • -= (Subtraction assignment)
  • *= (Multiplication assignment)
  • /= (Division assignment)
  • %= (Modulus assignment)
  • &= (Bitwise AND assignment)
  • |= (Bitwise OR assignment)
  • ^= (Bitwise XOR assignment)
  • <<= (Left shift assignment)
  • >>= (Right shift assignment)
  • >>>= (Unsigned right shift assignment)

Example: Using Assignment Operators

Let’s take a closer look at the usage of various assignment operators in Java through an example from the provided project file.

Code Example: Sample.java

Code explanation.

  • a = b; assigns the value of b (which is 20) to a .
  • Output: Value of a after simple assignment: 20
  • a += 5; adds 5 to a (20 + 5).
  • Output: Value of a after addition assignment: 25
  • a -= 2; subtracts 2 from a (25 – 2).
  • Output: Value of a after subtraction assignment: 23
  • a *= 3; multiplies a by 3 (23 * 3).
  • Output: Value of a after multiplication assignment: 69
  • a /= 4; divides a by 4 (69 / 4).
  • Output: Value of a after division assignment: 17
  • a %= 3; calculates a modulo 3 (17 % 3).
  • Output: Value of a after modulus assignment: 2
  • a &= 2; performs bitwise AND operation on a (2 & 2).
  • Output: Value of a after bitwise AND assignment: 2
  • a |= 1; performs bitwise OR operation on a (2 | 1).
  • Output: Value of a after bitwise OR assignment: 3
  • a ^= 2; performs bitwise XOR operation on a (3 ^ 2).
  • Output: Value of a after bitwise XOR assignment: 1
  • a <<= 1; shifts the bits of a to the left by 1 position (1 << 1).
  • Output: Value of a after left shift assignment: 2
  • a >>= 1; shifts the bits of a to the right by 1 position (2 >> 1).
  • Output: Value of a after right shift assignment: 1
  • a >>>= 1; shifts the bits of a to the right by 1 position without considering the sign (1 >>> 1).
  • Output: Value of a after unsigned right shift assignment: 0

Output of the Code

Key concepts to remember.

  • Simple Assignment ( = ): Used to assign values directly.
  • Compound Assignment Operators: Perform an operation and assignment in a single step.
  • Understanding and using these operators effectively can significantly simplify your code, especially in loops and complex expressions.

Assignment operators in Java are essential for efficient programming. They not only simplify code but also improve readability and performance. Knowing how and when to use these operators is crucial for any Java developer.

Related Posts

S02l09 – string methods in javascript continues.

  • December 20, 2024

S02L08 – String methods in JavaScript

IMAGES

  1. Assignment Operators in Java with Examples

    java assignment operators example

  2. The Assignment Operator in Java

    java assignment operators example

  3. Java Assignment Operators

    java assignment operators example

  4. Java Operators Example

    java assignment operators example

  5. A Detailed Guide on Operators in Java

    java assignment operators example

  6. PPT

    java assignment operators example

COMMENTS

  1. Java Assignment Operators with Examples - GeeksforGeeks

    Sep 13, 2023 · 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 ...

  2. Java - Assignment Operators with Examples

    The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −. Example 1. In this example, we're creating three variables a,b and c and using assignment operators. We've performed simple assignment, addition AND assignment ...

  3. Types of Assignment Operators in Java - Javatpoint

    In the above example, the variable x is assigned the value 10. Addition Assignment Operator (+=) To add a value to a variable and subsequently assign the new value to the same variable, use the addition assignment operator (+=).

  4. All Java Assignment Operators (Explained With Examples)

    Below, we have explained each assignment operator in Java with examples. Simple Assignment Operator (=) We’ll start with the most straightforward and simple assignment operator (=), which is used to assign a value of the variable on the right to the variable on the left.

  5. Java Operators - W3Schools

    Java Assignment Operators Assignment operators are used to assign values to variables. In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

  6. Assignment Operators in Java with Examples - BeginnersBook

    Oct 15, 2022 · Operator is a symbol that instructs the compiler to perform a specific action. For example, a "+" operator instructs the compiler to perform addition, a ">" operator instructs the compiler to perform comparison, "=" for assignment and so on. The operators in java are classified in eight different categories. In this guide, we will mainly

  7. Java Assignment Operators - Tutorial Kart

    In this tutorial, we will learn about different Assignment Operators available in Java programming language and go through each of these Assignment Operations in detail, with the help of examples. Operator Symbol – Example – Description. The following table specifies symbol, example, and description for each of the Assignment Operator in Java.

  8. Java Assignment Operators - w3resource

    Aug 19, 2022 · Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8;

  9. Assignment Operator in Java with Example - RefreshJava

    Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types : Assignment operator or simple assignment operator; Compound assignment operators

  10. S02L08 - Assignment operators - Studyeasy

    Sep 26, 2024 · Assignment Operators in Java Introduction Assignment operators are fundamental in Java for assigning values to variables. Beyond the basic = operator, Java provides several compound assignment operators that simplify coding tasks. This article will cover the different types of assignment operators, their syntax, and practical use cases with examples from the project file. Mastering assignment