• 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 Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples

Java Assignment Operators with Examples

  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

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. 

Please Login to comment...

Similar reads.

  • Java-Operators

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

Java methods, java classes, java file handling, java how to, 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

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

Get Certified

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.

  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable 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. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

Java assignment operators are classified into two types: simple and compound .

The Simple assignment operator is the equals ( = ) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left.

Compound operators are comprised of both an arithmetic, bitwise, or shift operator in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * 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. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com

  • Fundamentals
  • Objects & Classes
  • OO Concepts
  • API Contents
  • Input & Output
  • Collections
  • Concurrency
  • Swing & RMI
  • Certification

Assignment Operators J8 Home   «   Assignment Operators

  • <<    Relational & Logical Operators
  • Bitwise Logical Operators     >>

Symbols used for mathematical and logical manipulation that are recognized by the compiler are commonly known as operators in Java. In the third of five lessons on operators we look at the assignment operators available in Java.

Assignment Operators Overview  Top

The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression .

Shorthand Assignment Operators

The shorthand assignment operators allow us to write compact code that is implemented more efficiently.

Automatic Type Conversion, Assignment Rules  Top

The following table shows which types can be assigned to which other types, of course we can assign to the same type so these boxes are greyed out.

When using the table use a row for the left assignment and a column for the right assignment. So in the highlighted permutations byte = int won't convert and int = byte will convert.

Casting Incompatible Types  Top

The above table isn't the end of the story though as Java allows us to cast incompatible types. A cast instructs the compiler to convert one type to another enforcing an explicit type conversion.

A cast takes the form     target = (target-type) expression .

There are a couple of things to consider when casting incompatible types:

  • With narrowing conversions such as an int to a short there may be a loss of precision if the range of the int exceeds the range of a short as the high order bits will be removed.
  • When casting a floating-point type to an integer type the fractional component is lost through truncation.
  • The target-type can be the same type as the target or a narrowing conversion type.
  • The boolean type is not only incompatible but also inconvertible with other types.

Lets look at some code to see how casting works and the affect it has on values:

Running the Casting class produces the following output:

run casting

The first thing to note is we got a clean compile because of the casts, all the type conversions would fail otherwise. You might be suprised by some of the results shown in the screenshot above, for instance some of the values have become negative. Because we are truncating everything to a byte we are losing not only any fractional components and bits outside the range of a byte , but in some cases the signed bit as well. Casting can be very useful but just be aware of the implications to values when you enforce explicit type conversion.

Related Quiz

Fundamentals Quiz 8 - Assignment Operators Quiz

Lesson 9 Complete

In this lesson we looked at the assignment operators used in Java.

What's Next?

In the next lesson we look at the bitwise logical operators used in Java.

Getting Started

Code structure & syntax, java variables, primitives - boolean & char data types, primitives - numeric data types, method scope, arithmetic operators, relational & logical operators, assignment operators, assignment operators overview, automatic type conversion, casting incompatible types, bitwise logical operators, bitwise shift operators, if construct, switch construct, for construct, while construct.

Java 8 Tutorials

Live Training, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Java Interview Questions and Answers
  • Java Developer Salary Guide in India – For Freshers & Experienced

02 Beginner

  • Hierarchical Inheritance in Java
  • Arithmetic operators in Java
  • Unary operator in Java
  • Relational operators in Java

Assignment operator in Java

  • Logical operators in Java
  • Primitive Data Types in Java
  • Multiple Inheritance in Java
  • Parameterized Constructor in Java
  • Constructor Chaining in Java
  • What is a Bitwise Operator in Java? Type, Example and More
  • Constructor Overloading in Java
  • For Loop in Java: Its Types and Examples
  • Best Java Developer Roadmap 2024
  • While Loop in Java
  • What are Copy Constructors In Java? Explore Types,Examples & Use
  • Do-While Loop in Java
  • Hybrid Inheritance in Java
  • Single Inheritance in Java
  • Top 50 Java Full Stack Developer Interview Questions and Answers
  • Ternary Operator in Java - (With Example)
  • Java Full Stack Developer Salary
  • Java Multithreading Interview Questions 2024
  • Top 10 Reasons to know why Java is Important?
  • What is Java? A Beginners Guide to Java
  • Differences between JDK, JRE, and JVM: Java Toolkit
  • Variables in Java: Local, Instance and Static Variables
  • Data Types in Java - Primitive and Non-Primitive Data Types
  • Conditional Statements in Java: If, If-Else and Switch Statement
  • What are Operators in Java - Types of Operators in Java ( With Examples )
  • Java VS Python
  • Looping Statements in Java - For, While, Do-While Loop in Java
  • Jump Statements in JAVA - Types of Statements in JAVA (With Examples)
  • Java Arrays: Single Dimensional and Multi-Dimensional Arrays
  • What is String in Java - Java String Types and Methods (With Examples)

03 Intermediate

  • OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism
  • What is Class in Java? - Objects and Classes in Java {Explained}
  • Access Modifiers in Java: Default, Private, Public, Protected
  • Constructors in Java: Types of Constructors with Examples
  • Polymorphism in Java: Compile time and Runtime Polymorphism
  • Abstract Class in Java: Concepts, Examples, and Usage
  • What is Inheritance in Java: Types of Inheritance in Java
  • Exception handling in Java: Try, Catch, Finally, Throw and Throws

04 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • MERN: Full-Stack Web Developer Certification Training
  • Data Structures and Algorithms Training
  • Assignment Operator In Ja..

Assignment operator in Java

Java Programming For Beginners Free Course

Assignment operators in java: an overview.

We already discussed the Types of Operators in the previous tutorial Java. In this Java tutorial , we will delve into the different types of assignment operators in Java, and their syntax, and provide examples for better understanding. Because Java is a flexible and widely used programming language. Assignment operators play a crucial role in manipulating and assigning values to variables. To further enhance your understanding and application of Java assignment operator's concepts, consider enrolling in the best Java Certification Course .

What are the Assignment Operators in Java?

Assignment operators in Java are used to assign values to variables . They are classified into two main types: simple assignment operator and compound assignment operator.

The general syntax for a simple assignment statement is:

And for a compound assignment statement:

Read More - Advanced Java Interview Questions

Types of Assignment Operators in Java

  • Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign, where the operand is on the left side and the value is on the right. The right-side value must be of the same data type as that defined on the left side.
  • Compound Assignment Operator:  Compound assignment operators combine arithmetic operations with assignments. They provide a concise way to perform an operation and assign the result to the variable in one step. The Compound Operator is utilized when +,-,*, and / are used in conjunction with the = operator.

1. Simple Assignment Operator (=):

The equal sign (=) is the basic assignment operator in Java. It is used to assign the value on the right-hand side to the variable on the left-hand side.

Explanation

2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):.

Read More - Java Developer Salary

5. Division Operator (/=):

6. modulus assignment operator (%=):, example of assignment operator in java.

Let's look at a few examples in our Java Playground to illustrate the usage of assignment operators in Java:

  • Unary Operator in Java
  • Arithmetic Operators in Java
  • Relational Operators in Java
  • Logical Operators in Java
  • Ternary Operator in Java

Q1. Can I use multiple assignment operators in a single statement?

Q2. are there any other compound assignment operators in java, q3. how many types of assignment operators.

  • 1. (=) operator
  • 1. (+=) operator
  • 2. (-=) operator
  • 3. (*=) operator
  • 4. (/=) operator
  • 5. (%=) operator

About Author

Author image

  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

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

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

  • incrementing/decrementing a value by one
  • negating an expression
  • inverting the value of a boolean

Java Unary Operator Example: ++ and --

Java unary operator example 2: ++ and --, java unary operator example: ~ and , java arithmetic operators.

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example

Java arithmetic operator example: expression, java left shift operator.

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

Java Left Shift Operator Example

Java right shift operator.

The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand.

Java Right Shift Operator Example

Java shift operator example: >> vs >>>, java and operator example: logical && and bitwise &.

The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

Java AND Operator Example: Logical && vs Bitwise &

Java or operator example: logical || and bitwise |.

The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

Another Example:

Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.

Java Assignment Operator Example

Java assignment operator example: adding short.

After type cast:

You may also like

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Java operator

last modified January 27, 2024

In this article we show how to work with operators in Java.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: which works with three operands.

Certain operators may be used in different contexts. For example the + operator. It can be used in different cases. It adds numbers, concatenates strings, or indicates the sign of a number. We say that the operator is overloaded .

Java sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to signal that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

Java assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

This expression does not make sense in mathematics, but it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.

This code line results in syntax error. We cannot assign a value to a literal.

Java concatenating strings

In Java the + operator is also used to concatenate strings.

We join three strings together.

Strings are joined with the + operator.

An alternative method for concatenating strings is the concat method.

Java increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. Java has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

And here is the output of the example.

Java arithmetic operators

The following is a table of arithmetic operators in Java.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

We see the result of the program.

Java Boolean operators

In Java we have three logical operators. The boolean keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. For instance, boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in Java.

The code example shows the logical and (&&) operator. It evaluates to true only if both operands are true.

Only one expression results in true .

The logical or ( || ) operator evaluates to true if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true .

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions. We will see if they are called.

The One method returns false. The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false, the result of the logical conclusion is always false. Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true, the logical or is always true.

Java relational operators

Relational operators are used to compare values. These operators always result in a boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In Java we use the == to compare numbers. (Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.)

Java bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of a number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like Java.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3 and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

Java compound assignment operators

Compound assignment operators are shorthand operators which consist of two operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

The following example uses two compound operators.

We use the += and *= compound operators.

The a variable is initiated to one. Value 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

Java instanceof operator

The instanceof operator compares an object to a specified type.

In the example, we have two classes: one base and one derived from the base.

This line checks if the variable d points to the class that is an instance of the Base class. Since the Derived class inherits from the Base class, it is also an instance of the Base class too. The line prints true.

The b object is not an instance of the Derived class. This line prints false.

Every class has Object as a superclass. Therefore, the d object is also an instance of the Object class.

Java lambda operator

Java 8 introduced the lambda operator ( -> ).

This is the basic syntax for a lambda expression in Java. Lambda expression allow to create more concise code in Java.

The declaration of the type of the parameter is optional; the compiler can infer the type from the value of the parameter. For a single parameter the parentheses are optional; for multiple parameters, they are required.

The curly braces are optional if there is only one statement in an expression body. Finally, the return keyword is optional if the body has a single expression to return a value; curly braces are required to indicate that the expression returns a value.

In the example, we define an array of strings. The array is sorted using the Arrays.sort method and a lambda expression.

Lambda expressions are used primarily to define an inline implementation of a functional interface, i.e., an interface with a single method only. Interfaces are abstract types that are used to enforce a contract.

In the example, we create a greeting service with the help of a lambda expression.

Interface GreetingService is created. All objects implementing this interface must implement the greet method.

We create an object that implements GreetingService with a lambda expression. The object has a method that prints a message to the console.

We call the object's greet method, which prints a give message to the console.

There are some common functional interfaces, such as Function , Consumer , or Supplier .

The example uses a lambda expression to compute squares of integers.

Function is a function that accepts one argument and produces a result. The operation of the lamda expression produces a square of the given integer.

Java double colon operator

The double colon operator (::) is used to create a reference to a method.

In the code example, we create a reference to a static method with the double colon operator.

We have a static method that prints a greeting to the console.

Consumer is a functional interface that represents an operation that accepts a single input argument and returns no result. With the double colon operator, we create a reference to the greet method.

We perform the functional operation with the accept method.

Java operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first. The result of the above expression is 40.

Java operators precedence list

The following table shows common Java operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence. If we use operators with the same precedence, then the associativity rule is applied.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence than the bitwise OR. First, the initial true value is negated to false, then the | operator combines false and true, which gives true in the end.

Java associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion, and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated. The assignment operators, ternary operator, increment, decrement, unary plus and minus, negation, bitwise NOT, type cast, object creation operators are right to left associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and then the compound assignment operator is applied.

Java ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on the age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

Calculating prime numbers

In the following example, we are going to calculate prime numbers.

In the above example, we deal with several operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers from 1 to the selected number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We will calculate primes from these numbers.

Values 0 and 1 are not considered to be primes.

We skip the calculations for 2 and 3. They are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease i by one each loop cycle. When i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We will divide the 9 number by 3 and 2. This is sufficient for our calculation.

If the remainder division operator returns 0 for any of the i values, then the number in question is not a prime.

In this article we covered Java expressions. We mentioned various types of operators and described precedence and associativity rules in expressions.

Java operators - tutorial

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials .

types of assignment operators in java

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands , and then return a result.

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator " = " is far more common than the unsigned right shift operator " >>> ". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

Table of Contents

Different types of operators in java, java operators precedence and association, a detailed guide on operators in java.

Operators in Java

As the name gives out, operators in Java perform various operations on different variables and values. Java provides many types of operators to perform other actions. In this tutorial, you will go through all kinds of operators with examples.

Java offers the following operators:

  • Unary Operators
  • Arithmetic Operators
  • Bitwise Operators
  • Logical Operators
  • Relational Operators
  • Shift Operators
  • Ternary Operators
  • Assignment Operators

Now that you know the types of operators in Java, it’s time to understand each of them with examples.

Java Unary Operators

Unary operators in Java require only one operand. They are used to increment/decrement and negotiate a value. It is also possible to invert a Boolean value with unary operators. The table depicted below shows different unary operators and what they do.

Here's How to Land a Top Software Developer Job

Here's How to Land a Top Software Developer Job

Here’s an example using the unary operators.

unaryoperators

Java Arithmetic Operators

Arithmetic operators in Java perform multiplicative and additive operations such as addition, subtraction, multiplication, division, and modulus. The table below shows different arithmetic operators and what they do.

The example below shows the usage of all the arithmetic operators.

arithmeticoperators

Java Bitwise Operators

Bitwise operators in Java perform operations on individual bits. The table below shows different bitwise operators and what they do.

Let’s look at the example below to understand the bitwise operator. Consider the value of a is 108, and that of b is 29. The binary format of these values is:

108: 0110 1100

29: 0001 1101

Now the values of:

a&b = 0000 1100 = 12

a|b = 0111 1101 = 125

a^b = 0111 0001 = 113

~a = 1001 0011 = -109 (Don’t get confused, it calculates the answer in 2’s complement form as it is a signed binary number).

Now, look at whether our Java program gives the same results.

BitwiseOperators

Java Logical Operators

Logical operators in Java are used to perform logical AND, OR, and NOT operations. The table below shows different logical operators and what they do.

The example below shows the use of logical operators in Java.

LogicalOperators

The significant difference between the logical AND and bitwise AND is that the logical AND only checks the second expression in the event that the first one is true. Whereas, the bitwise AND operator will check the second expression even if the first one is true. Similarly, the difference between logical OR and bitwise OR is that the logical OR would check the 2nd expression, only in the case where the first one is false. On the other hand, the bitwise OR will check the second expression even if the first one is false.

Java Relational Operators

Relational operators in Java are used to check relations between two operands. The table below shows different relational operators and what they do.

Let’s look at an example to see the use of relational operators in Java.

RelationalOperators

Java Shift Operators

Shift operators in Java are used to shift the binary bits of a number to the left or right. By shifting the bits, it will multiply or divide the operand by two. The table below shows different shift operators and what they do.

The example below shows the use of shift operators.

ShiftOperators

Java Ternary Operator

A ternary operator in Java is used as a shorthand replacer to if-else statements. It is also referred to as a miscellaneous operator. The table below shows different ternary operators and what they do.

Let’s look at an example to use the ternary operator in Java.

TernaryOperator

Kickstart Your UI/UX Career Right Here!

Kickstart Your UI/UX Career Right Here!

Java Assignment Operators

As the name suggests, assignment operators in Java assign values specified on its right, to the operands on its left. It assigns the right value to the left operand because it has a right to left associativity (you will look at precedence and associativity of each type of operator later in this tutorial). The table below shows different assignment operators and what they do.

You can also combine the assignment operator with other operators to shorten the statement. For instance, we can combine = with + to write a+=10, instead of writing a=a+10. Similarly, we can combine = with -, *, /, %, and more operators. The example below shows the use of the assignment operator.

AssignmentOperators

When there is over one operator in a single statement, precedence determines how they will be evaluated and executed. For instance, multiplication has higher precedence than addition. Hence, in the statement a=8+3*4, a will become 20 and not 44 as 3 will be multiplied by 4 first and then added to 12. Similarly, all the operators in Java have precedence. They also have an association, which determines whether the operators will be evaluated from left to right or vice versa. The table below shows Java operators’ precedence and association. Operators higher in the table have higher precedence than the lower ones.

Get a firm foundation in Java, the most commonly used programming language in software development with the  Java Certification Training Course .

If you are interested in Java programming and want to pursue a software development career, Simplilearn’s Online Java Certification Course can help you excel. The course offers 60 hours of applied learning and implementation projects to help you grasp Java programming concepts.

If you have any questions for us, leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Recommended Reads

Free eBook: Pocket Guide to the Microsoft Certifications

An Introduction to Different Types of Matlab Operators

Operators in C#: An Ultimate C# Operations Guide With Examples

Free eBook: Enterprise Architecture Salary Report

What Is Operator Overloading in C++?

An Absolute Guide to Know Everything on Expressions in C

Get Affiliated Certifications with Live Class programs

Full stack java developer job guarantee program.

  • 8X higher engagement in live online classes by industry experts
  • Industry recognized certification

Java Certification Training

  • 24x7 learner assistance and support
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Vired Library

Data Science

Future tech.

Complimentary 8-week Gen AI Course with Select Programs.

Request a callback

or Chat with us on

Java Operators: Meaning and Types Explained

Last Updated on :  March 19, 2024

types of assignment operators in java

While learning Java, you will come across the concept of operators. What is a Java operator? Java operators are symbols useful for performing operations on variables. They also help manipulate the values of the operands.

The different Java operators are useful for performing various functions. Dive into this article to learn more about Java operators, their types, and their importance.

Why are Operators Important in Java Programming?

Java Operators Meaning and Types

Learn: Full Stack Development with Cloud for Web and Mobile

Major Types of Operators in Java 

Now that you know what is a Java operator, you should learn about the different types of operators in Java.

  • Arithmetic Operators
  • Ternary Operators
  • Bitwise Operator
  • Relational Operators
  • Logical Operators
  • Unary Operators
  • Assignment Operator

Shift Operator in Java

Arithmetic operators in java.

Arithmetic operators in Java are useful for executing addition, multiplication, division, subtraction, and modulus. As you can see, these operators in Java are valuable for mathematical operations.

Examples of Arithmetic Operators (Kindly put all the code related content in a highlighted section)

Ternary operators in java.

The ternary operator in Java is conditional. These Java operators can help minimize the line of code while making comparisons. The ternary operator in Java is a replacement for nested if-else or if-else statements. Sometimes, the ternary operator in Java is also called the conditional operator, inline if, or ternary if.

Examples of Ternary Operator Java

Bitwise operator in java.

The bitwise operator in Java operates on a bit array, bit string, or binary number. The fast and simple operator in Java is directly supported by the processor. You can also refer to the bitwise operation as bit-level programming.

Examples of Bitwise Operators in Java

Relational operators in java.

The relational operators in Java can compare two numbers to deliver a boolean value. This operator can be useful for defining a test or relation between two operands. 

Examples of Relational operators in Java

Logical operators in java.

Logical operators in Java help combine two or more conditions. It is useful for performing the original condition under consideration.

Examples of Logical Operators in Java

Unary operators in java.

The unary operators in Java demand a single operand. These Java operators can increase or decrease the value. As a result, an expression becomes negative, or the boolean value gets inverted.

Examples of Unary Operators in Java

Assignment operators in java.

The assignment operators in Java are beneficial for allocating new values to a variable. In assignment operators in Java, the left side is called a variable. The right side of these Java operators is called value.

Examples of Assignment Operators in Java

The shift operator in Java can transfer bits of a number to the left or right. The shift can be performed by dividing or multiplying the numbers. 

Examples of Shift Operators in Java

Java Operators Meaning and Types

.css-12zqz9u{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:1em;height:1em;display:inline-block;fill:currentColor;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;-webkit-transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;font-size:1.5rem;height:0.7em;} What is the ternary operator in Java, and how does it differ from other conditional statements?

.css-12zqz9u{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:1em;height:1em;display:inline-block;fill:currentcolor;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;-webkit-transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;font-size:1.5rem;height:0.7em;} how can i use assignment operators in java to simplify my code and improve readability, .css-12zqz9u{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:1em;height:1em;display:inline-block;fill:currentcolor;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;-webkit-transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;font-size:1.5rem;height:0.7em;} what are the advantages and limitations of using shift operators in java, .css-12zqz9u{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:1em;height:1em;display:inline-block;fill:currentcolor;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;-webkit-transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;font-size:1.5rem;height:0.7em;} how do i use the comparison operators in java to compare two values and return a boolean result, .css-12zqz9u{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:1em;height:1em;display:inline-block;fill:currentcolor;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;-webkit-transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;transition:fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;font-size:1.5rem;height:0.7em;} what are the best practices for using java operators in my code to ensure readability and maintainability, high-growth programs.

Choose the relevant program for yourself and kickstart your career

You may also like

Carefully gathered content to add value to and expand your knowledge horizons

Hero Vired logo

Accelerator Program in Business Analytics & Data Science

Integrated program in data science, ai and ml, accelerator program in ai and machine learning, advanced certification program in data science & analytics, certificate program in full stack development with specialization for web and mobile, certificate program in devops and cloud engineering, certificate program in application development, certificate program in cybersecurity essentials & risk assessment, integrated program in finance and financial technologies, certificate program in financial analysis, valuation and risk management, certificate program in strategic management and business essentials, executive program in product management, certificate program in product management, certificate program in technology-enabled sales, certificate program in gaming & esports, certificate program in extended reality (vr+ar), professional diploma in ux design, vired links.

  • * These figures are indicative in nature and subject to inter alia a learner's strict adherence to the terms and conditions of the program. The figures mentioned here shall not constitute any warranty or representation in any manner whatsoever.

COMMENTS

  1. Java Assignment Operators with Examples

    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. Types of Assignment Operators in Java

    Types of Assignment Operators in Java. Java is a popular programming language that software developers use to construct a wide range of applications. It is a simple, robust, and platform-independent object-oriented language. There are various types of assignment operators in Java, each with its own function.

  3. Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials

    This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators. The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics.

  4. Java 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 ...

  5. Java Assignment Operators

    Java assignment operators are classified into two types: simple and compound. The Simple assignment operator is the equals ( =) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...

  6. All Java Assignment Operators (Explained With Examples)

    There are mainly two types of assignment operators in Java, which are as follows: Simple Assignment Operator ; We use the simple assignment operator with the "=" sign, where the left side consists of an operand and the right side is a value. The value of the operand on the right side must be of the same data type defined on the left side.

  7. Java Operators: Arithmetic, Relational, Logical and more

    For example, + is an operator used for addition, while * is also an operator used for multiplication. Operators in Java can be classified into 5 types: Arithmetic Operators. Assignment Operators. Relational Operators. Logical Operators. Unary Operators. Bitwise Operators. 1.

  8. Java Assignment Operators

    Java Assignment Operators. The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =. In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to ...

  9. Java Operators

    The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples. It assigns the value on its right to the operand on its left: int seven = 7; 9.2. Compound Assignments

  10. Java 8

    Assignment Operators Overview Top. The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression.

  11. Assignment operator in Java

    Assignment Operators in Java: An Overview. We already discussed the Types of Operators in the previous tutorial Java. In this Java tutorial, we will delve into the different types of assignment operators in Java, and their syntax, and provide examples for better understanding.Because Java is a flexible and widely used programming language. Assignment operators play a crucial role in ...

  12. Summary of Operators (The Java™ Tutorials > Learning the Java Language

    The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.

  13. Assignment Operator in Java with Example

    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 : int a = 10; // value 10 is assigned in variable a double d = 20.25; // value 20.25 is assigned in variable d char c = 'A'; // Character A is assigned in variable c. a = 20 ...

  14. Java Assignment Operators

    Java Assignment Operators: Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. ... If we assign the value which is out of range of variable type then 2's complement is assigned. Java supports shortcut/compound assignment operator. Java Code Editor ...

  15. Operators in Java

    Operators in Java. Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: Unary Operator, Arithmetic Operator, Shift Operator, Relational Operator, Bitwise Operator, Logical Operator, Ternary Operator and ; Assignment Operator. Java Operator ...

  16. Java operator

    The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and then the compound assignment operator is applied. $ java Associativity.java 0 0 0 0 0 Java ternary operator

  17. Operators (The Java™ Tutorials > Learning the Java Language

    Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest ...

  18. Types of Assignment Operators in Java

    Simple assignment operators handle plain, uncomplicated operations like addition, subtraction, multiplication and division. Compound assignment operators are used when there are more logical operations are required in the code, like ^, &, %, <>, >>, <<, etc. The Assignment Operator is generally of two types. They are: Simple Assignment Operator.

  19. A Detailed Guide on Operators in Java

    Java Assignment Operators. As the name suggests, assignment operators in Java assign values specified on its right, to the operands on its left. It assigns the right value to the left operand because it has a right to left associativity (you will look at precedence and associativity of each type of operator later in this tutorial).

  20. Java Operators

    Now that you know what is a Java operator, you should learn about the different types of operators in Java. Arithmetic Operators. Ternary Operators. Bitwise Operator. Relational Operators. Logical Operators. Unary Operators. Assignment Operator. Shift Operator in Java.