01 Career Opportunities

02 beginner, 03 intermediate, 04 questions, 05 training programs, assignment operator in java, java online course free with certificate (2024), assignment operators in java: an overview, what are the assignment operators in java, types of assignment operators in java, 1. simple assignment operator (=):, explanation, 2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):, 5. division operator (/=):, 6. modulus assignment operator (%=):, example of assignment 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, live classes schedule.

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

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.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

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:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

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:

Operator Name Example Try it
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

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:

Operator Name Description Example Try it
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Java Bitwise Operators

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

Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001  1
| OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101  5
~ NOT - Inverts all the bits ~ 5  ~0101 1010  10
^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100  4
<< Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4

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.

Javatpoint Logo

Java Tutorial

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

JavaTpoint

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.

In this section, we will look at Java's many types of assignment operators, how they function, and how they are utilized.

To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side.

In the above example, the variable x is assigned the value 10.

To add a value to a variable and subsequently assign the new value to the same variable, use the addition assignment operator (+=). It takes the value on the right side of the operator, adds it to the variable's existing value on the left side, and then assigns the new value to the variable.

To subtract one numeric number from another, use the subtraction operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we create two integer variables, a and b, subtract b from a, and then assign the result to the variable c.

To combine two numerical numbers, use the multiplication operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, multiply their values using the multiplication operator, and then assign the outcome to the third variable, c.

To divide one numerical number by another, use the division operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, divide them by one another using the division operator, and then assign the outcome to the variable c.

It's vital to remember that when two numbers are divided, the outcome will also be an integer, and any residual will be thrown away. For instance:

The modulus assignment operator (%=) computes the remainder of a variable divided by a value and then assigns the resulting value to the same variable. It takes the value on the right side of the operator, divides it by the current value of the variable on the left side, and then assigns the new value to the variable on the left side.





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

JavaScript disabled. A lot of the features of the site won't work. Find out how to turn on JavaScript  HERE .

Java8 Homepage

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

Operator Meaning Example Result Notes
+=Addition 10
-=Subtraction 0
/=Division 3When used with an type, any remainder will be truncated.
*=Multiplication 25
%=Modulus 1Holds the remainder value of a division.
&=AND



















Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression.
|=OR



















Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression.
^=XOR



















Will check both operands for different values and assign or to the first operand dependant upon the outcome of the expression.

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.

Type
NONONONONONONO
NONONONONONONO
NONONONONONONO
NONOYESNONONONO
NOYESYESYESNONONO
NOYESYESYESYESNONO
NOYESYESYESYESYESNO
NOYESYESYESYESYESYES

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

Java Tutorial

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 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 −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C
+= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C − A
*= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

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 Assignment Operators

Java programming tutorial index.

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 "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:

Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables.

  • ▼Java Tutorial
  • Introduction
  • Java Program Structure
  • Java Primitive data type
  • ▼Development environment setup
  • Download and Install JDK, Eclipse (IDE)
  • Compiling, running and debugging Java programs
  • ▼Declaration and Access control
  • Class, methods, instance variables
  • Java Packages
  • ▼OOPS Concepts
  • Java Object Oriented Programming concepts
  • Is-A and Has-A relationship
  • ▼Assignments
  • Arrays - 2D array and Multi dimension array
  • Wrapper classes
  • ▼Operators
  • Assignment Operator
  • Arithmetic Operator
  • Conditional Operator
  • Logical Operator
  • ▼Flow Control
  • Switch Satement
  • While and Do loop
  • Java Branching Statements
  • ▼Exceptions
  • Handling Exceptions
  • Checked and unchecked
  • Custom Exception
  • Try with resource feature of Java 7
  • ▼String Class
  • String Class
  • Important methods of String class with example
  • String buffer class and string builder class
  • ▼File I/O and serialization
  • File Input and Output
  • Reading file
  • Writing file
  • Java Property File Processing
  • Java Serialization
  • ▼Java Collection
  • Java Collection Framework
  • Java ArrayList and Vector
  • Java LinkedList Class
  • Java HashSet
  • Java TreeSet
  • Java Linked HashSet
  • Java Utility Class
  • ▼Java Thread
  • Java Defining, Instantiating and Starting Thread
  • Java Thread States and Transitions
  • Java Thread Interaction
  • Java Code Synchronization
  • ▼Java Package
  • ▼Miscellaneous
  • Garbage Collection in Java
  • BigDecimal Method

Java Assignment Operators

Description.

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. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.

Assignment can be of various types. Let’s discuss each in detail.

Primitive Assignment:

The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.

Primitive Casting

Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.

assignment operator image-1

For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.

assignment operator image-2

Assigning Literal that is too large for a variable

When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)

Java Code: Go to the editor

assignment operator image-3

Reference variable assignment

We can assign newly created object to object reference variable as below

First line will do following things,

  • Makes a reference variable named s of type String
  • Creates a new String object on the heap memory
  • Assigns the newly created String object to the reference variables

You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.

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:

The += is called the addition assignment operator. Other shorthand operators are shown below table

Operator Name Example Equivalent
+= Addition assignment i+=5; i=i+5
-= Subtraction assignment j-=10; j=j-10;
*= Multiplication assignment k*=2; k=k*2;
/= Division assignment x/=10; x=x/10;
%= Remainder assignment a%=4; a=a%4;

Below is the sample program explaining assignment operators:

assignment operator image-4

  • Assigning a value to can be straight forward or casting.
  • 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:

Previous: Wrapper classes Next: Arithmetic Operator

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • Java Operators

Last updated: January 8, 2024

java multiple assignment operator

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

We’ve opened a new Java/Spring Course Team Lead position. Part-time and entirely remote, of course: Read More

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Overview

Operators are a fundamental building block of any programming language. We use operators to perform operations on values and variables.

Java provides many groups of operators. They are categorized by their functionalities.

In this tutorial, we’ll walk through all Java operators to understand their functionalities and how to use them.

2. Arithmetic Operators

We use arithmetic operators to perform simple mathematical operations. We should note that arithmetic operators only work with primitive number types and their boxed types , such as int and  Integer .

Next, let’s see what operators we have in the arithmetic operator group.

2.1. The Addition Operator

The addition operator (+) allows us to add two values or concatenate two strings:

2.2. The Subtraction Operator

Usually, we use the subtraction operator (-) to subtract one value from another:

2.3. The Multiplication Operator

The multiplication operator (*) is used to multiply two values or variables:

2.4. The Division Operator

The division operator (/) allows us to divide the left-hand value by the right-hand one:

When we use the division operator on two integer values ( byte , short , int , and long ), we should note that the result is the quotient value. The remainder is not included .

As the example above shows, if we calculate 15 / 2 , the quotient is 7, and the remainder is 1 . Therefore, we have 15 / 2 = 7 .

2.5. The Modulo Operator

We can get the quotient using the division operator. However, if we just want to get the remainder of a division calculation, we can use the modulo operator (%):

3. Unary Operators

As the name implies, unary operators only require one single operand . For example, we usually use unary operators to increment, decrement, or negate a variable or value.

Now, let’s see the details of unary operators in Java.

3.1. The Unary Plus Operator

The unary plus operator (+) indicates a positive value. If the number is positive, we can omit the ‘+’ operator:

3.2. The Unary Minus Operator

Opposite to the unary plus operator, the unary minus operator (-) negates a value or an expression:

3.3. The Logical Complement Operator

The logical complement operator (!) is also known as the “NOT” operator . We can use it to invert the value of a boolean variable or value:

3.4. The Increment Operator

The increment operator (++) allows us to increase the value of a variable by 1:

3.5. The Decrement Opeartor

The decrement operator (–) does the opposite of the increment operator. It decreases the value of a variable by 1:

We should keep in mind that the increment and decrement operators can only be used on a variable . For example, “ int a = 5; a++; ” is fine. However, the expression “ 5++ ” won’t be compiled.

4. Relational Operators

Relational operators can be called “comparison operators” as well. Basically, we use these operators to compare two values or variables.

4.1. The “Equal To” Operator

We use the “equal to” operator (==) to compare the values on both sides. If they’re equal, the operation returns true :

The “equal to” operator is pretty straightforward. On the other hand, the Object class has provided the equals() method. As the Object class is the superclass of all Java classes, all Java objects can use the equals() method to compare each other.

When we want to compare two objects – for instance, when we compare Long objects or compare String s –  we should choose between the comparison method from the equals() method and that of the “equal to” operator wisely .

4.2. The “Not Equal To” Operator

The “not equal to” operator (!=) does the opposite of the ‘==’ operator. If the values on both sides are not equal, the operation returns true :

4.3. The “Greater Than” Operator

When we compare two values with the “greater than” operator (>), it returns true if the value on the left-hand side is greater than the value on the right-hand side:

4.4. The “Greater Than or Equal To” Operator

The “greater than or equal to” operator (>=) compares the values on both sides and returns true if the left-hand side operand is greater than or equal to the right-hand side operand:

4.5. The “Less Than” Operator

The “less than” operator (<) compares two values on both sides and returns true if the value on the left-hand side is less than the value on the right-hand side:

4.6. The “Less Than or Equal To” Operator

Similarly, the “less than or equal to” operator (<=) compares the values on both sides and returns true if the left-hand side operand is less than or equal to the right-hand side:

5. Logical Operators

We have two logical operators in Java: the logical AND and OR operators. Basically, their function is pretty similar to the AND gate and the OR gate in digital electronics.

Usually, we use a logical operator with two operands, which are variables or expressions that can be evaluated as boolean .

Next, let’s take a closer look at them.

5.1. The Logical AND Operator

The logical AND operator ( && ) returns true only if both operands are true :

5.2. The Logical OR Operator

Unlike the ‘ && ‘ operator, the logical OR operator ( || ) returns true if at least one operand is  true :

We should note that the logical OR operator has the short-circuiting effect : It returns true as soon as one of the operands is evaluated as true, without evaluating the remaining operands.

6. Ternary Operator

A ternary operator is a short form of the if-then-else statement. It has the name ternary as it has three operands. First, let’s have a look at the standard if-then-else statement syntax:

We can convert the above if-then-else statement into a compact version using the ternary operator:

Let’s look at its syntax:

Next, let’s understand how the ternary operator works through a simple example:

7. Bitwise and Bit Shift Operators

As the article “ Java bitwise operators ” covers the details of bitwise and bit shift operators, we’ll briefly summarize these operators in this tutorial.

7.1. The Bitwise AND Operator

The bitwise AND operator (&) returns the bit-by-bit AND of input values:

7.2. The Bitwise OR Operator

The bitwise OR operator (|) returns the bit-by-bit OR of input values:

7.3. The Bitwise XOR Operator

The bitwise XOR (exclusive OR) operator (^) returns the bit-by-bit XOR of input values:

7.4. The Bitwise Complement Operator

The bitwise complement operator (~) is a unary operator. It returns the value’s complement representation, which inverts all bits from the input value:

7.5. The Left Shift Operator

Shift operators shift the bits to the left or right by the given number of times.

The left shift operator (<<) shifts the bits to the left by the number of times defined by the right-hand side operand. After the left shift, the empty space in the right is filled with 0.

Next, let’s left shift the number 12 twice:

n << x has the same effect of multiplying the number  n  with x power of two.

7.6. The Signed Right Shift Operator

The signed right shift operator (>>) shifts the bits to the right by the number of times defined by the right-hand side operand and fills 0 on voids left as a result.

We should note that the leftmost position after the shifting depends on the sign extension .

Next, let’s do “signed right shift” twice on the numbers 12 and -12 to see the difference:

As the second example above shows, if the number is negative, the leftmost position after each shift will be set by the sign extension.

n >> x has the same effect of dividing the number n by x power of two.

7.7. The Unsigned Right Shift Operator

The unsigned right shift operator (>>>) works in a similar way as the ‘>>’ operator. The only difference is that after a shift, the leftmost bit is set to 0 .

Next, let’s unsigned right shift twice on the numbers 12 and -12 to see the difference:

As we can see in the second example above, the >>> operator fills voids on the left with 0 irrespective of whether the number is positive or negative .

8. The “ instanceof ” Operator

Sometimes, when we have an object, we would like to test if it’s an instance of a given type . The “ instanceof ” operator can help us to do it:

9. Assignment Operators

We use assignment operators to assign values to variables. Next, let’s see which assignment operators we can use in Java.

9.1. The Simple Assignment Operator

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:

9.2. Compound Assignments

We’ve learned arithmetic operators. We can combine the arithmetic operators with the simple assignment operator to create compound assignments.

For example, we can write “ a = a + 5 ” in a compound way: “ a += 5 “.

Finally, let’s walk through all supported compound assignments in Java through examples:

10. Conclusion

Java provides many groups of operators for different functionalities. In this article, we’ve passed through the operators in Java.

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)

Java Operators

  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement

Java Ternary Operator

  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion

Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers

Java Operator Precedence

Java Bitwise and Shift Operators

  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

  • Java Math IEEEremainder()

Operators are symbols that perform operations on variables and values. 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. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

Here, the + operator is used to add two variables a and b . Similarly, there are various other arithmetic operators in Java.

Operator Operation
Addition
Subtraction
Multiplication
Division
Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

In the above example, we have used + , - , and * operators to compute addition, subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division operator.

If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.

% Modulo Operator

The modulo operator % computes the remainder. When a = 7 is divided by b = 4 , the remainder is 3 .

Note : The % operator is mainly used with integers.

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age .

Let's see some more assignment operators available in Java.

Operator Example Equivalent to

Example 2: Assignment Operators

3. java relational operators.

Relational operators are used to check the relationship between two operands. For example,

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false .

Operator Description Example
Is Equal To returns
Not Equal To returns
Greater Than returns
Less Than returns
Greater Than or Equal To returns
Less Than or Equal To returns

Example 3: Relational Operators

Note : Relational operators are used in decision making and loops.

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false . They are used in decision making.

Operator Example Meaning
(Logical AND) expression1 expression2 only if both and are
(Logical OR) expression1 expression2 if either or is
(Logical NOT) expression if is and vice versa

Example 4: Logical Operators

Working of Program

  • (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .
  • (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .
  • (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .
  • (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .
  • (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .
  • !(5 == 3) returns true because 5 == 3 is false .
  • !(5 > 3) returns false because 5 > 3 is true .

5. Java Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1 . That is, ++5 will return 6 .

Different types of unary operators are:

Operator Meaning
: not necessary to use since numbers are positive without using it
: inverts the sign of an expression
: increments value by 1
: decrements value by 1
: inverts the value of a boolean
  • Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1 , while -- decrease it by 1 . For example,

Here, the value of num gets increased to 6 from its initial value of 5 .

Example 5: Increment and Decrement Operators

In the above program, we have used the ++ and -- operator as prefixes (++a, --b) . We can also use these operators as postfix (a++, b++) .

There is a slight difference when these operators are used as prefix versus when they are used as a postfix.

To learn more about these operators, visit increment and decrement operators .

6. Java Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits. For example,

Here, ~ is a bitwise operator. It inverts the value of each bit ( 0 to 1 and 1 to 0 ).

The various bitwise operators present in Java are:

Operator Description
Bitwise Complement
Left Shift
Right Shift
Unsigned Right Shift
Bitwise AND
Bitwise exclusive OR

These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators .

Other operators

Besides these operators, there are other additional operators in Java.

The instanceof operator checks whether an object is an instanceof a particular class. For example,

Here, str is an instance of the String class. Hence, the instanceof operator returns true . To learn more, visit Java instanceof .

The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,

Here's how it works.

  • If the Expression is true , expression1 is assigned to the variable .
  • If the Expression is false , expression2 is assigned to the variable .

Let's see an example of a ternary operator.

In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator .

Now that you know about Java operators, it's time to know about the order in which operators are evaluated. To learn more, visit Java Operator Precedence .

Table of Contents

  • Introduction
  • Java Arithmetic Operators
  • Java Assignment Operators
  • Java Relational Operators
  • Java Logical Operators
  • Java Unary Operators
  • Java Bitwise Operators

Sorry about that.

Related Tutorials

Java Tutorial

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.

Operator Example Same As
= a = 10 a = 10
+= a += 5 a = a + 5
-= a -= 3 a = a - 3
*= a *= 6 a = a * 6
/= a /= 5 a = a / 5
%= a %= 7 a = a % 7
&= a &= 3 a = a & 3
|= a |= 3 a = a | 3
^= a ^= 2 a = a ^ 2
>>= a >>= 3 a = a >> 3
>>>= a >>>= 3 a = a >>> 3
<<= a <<= 2 a = a << 2

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

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.

Summary of Operators

The following quick reference summarizes the operators supported by the Java programming language.

Simple Assignment Operator

Arithmetic operators, unary operators, equality and relational operators, conditional operators, type comparison operator, bitwise and bit shift operators.

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

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

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in JavaScript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • DigitalOcean
  • Sign up for:

How To Use Operators in Java

  • Development

author

Toli and Rachel Lee

How To Use Operators in Java

The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

Introduction

An operator is one or more symbols in combination, such as the well-known arithmetic operators minus ( - ) and plus ( + ) or the more advanced instanceof . When you apply operators on values or variables, you get a result from the operation. Such operations are fundamental in programming because their result is assigned to a variable or further evaluated until the final goal of the program is accomplished.

For this tutorial, you have to be familiar with an operand , which is the value or variable on which the operators are applied. Depending on the number of operands, operators can be divided into three groups. First, when there is only one operand in the operation, the operators are called unary . Similarly, binary operators involve two operands. Finally, when there are three operands, the operator is ternary . Following this categorization, this tutorial is organized into three main parts for each type of operator.

In this tutorial, you will use all three types of operators to manipulate primitive data types, such as in math equations. You will also use operators in more advanced scenarios with reference types and explore some of the rules for operator precedence.

Prerequisites

To follow this tutorial, you will need:

An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:

  • Java (version 11 or above) installed on your machine, with the compiler provided by the Java Development Kit (JDK). For Ubuntu and Debian, follow the steps for Option 1 in our tutorial, How To Install Java with Apt on Ubuntu 22.04 . For other operating systems, including Mac and Windows, see the download options for Java installation .
  • To compile and run the code examples, this tutorial uses Java Shell , which is a Read-Evaluate-Print Loop (REPL) run from the command line. To get started with JShell, check out the Introduction to JShell guide.

Familiarity with Java and object-oriented programming, which you can find in our tutorial, How To Write Your First Program in Java .

An understanding of Java data types, which is discussed in our tutorial, Understanding Data Types in Java .

Unary Operators

Unary operators are applied to one operand, which makes them the most straightforward. Unary operators are often used because they make your code more concise and readable. They replace the need to explicitly describe operations like increasing and decreasing values. However, when combined with other operators, unary operators can also be challenging to use, as you’ll discover later in this section.

Next, you’ll use unary operators to increase and decrease values, as well as flip boolean values.

Increment and Decrement Operators

Increment and decrement operators, as their names suggest, increase and decrease numbers. The increment operator is the combination of two plus signs ( ++ ) and the decrement operator is two minus signs ( -- ). These operators are used before and after operands.

Preincrementing and Predecrementing

When you use the operators before an operand, you are preincrementing or predecrementing depending on whether you use ++ or -- . When you use the pre operators, you change the value of the operand before using it. Thus, when you actually use the value, it is already changed.

Info: To follow along with the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and hitting ENTER . To exit jshell , type /exit .

To use the preincrementing operator, type the following into jshell :

  • int theAnswer = 42 ;
  • System.out.println ( "Preincrementing: " + ++ theAnswer ) ;

On the first line, you define a variable theAnswer with the value 42 . On the second line, you use the println() method to print it and thus demonstrate how it has changed.

The preincrement operator in the above example is ++ , and it is placed before theAnswer . By using the preincrement operator in this way, you are first incrementing the value of theAnswer to 43 . After that, when println() processes it, it is already 43 , and thus you see printed:

Predecrementing works similarly, but instead of incrementing, you are decrementing the value of the operand. As an exercise, modify the above example so that instead of the preincrement operator ++ , you use the predecrement -- .

Postincrementing and Postdecrementing

In contrast to the pre operators, the post operators change the value of an operand after it is used. There are some specific cases in which post or pre operators are commonly used, but as a whole, it is a matter of personal preference.

To demonstrate how post operators work, you will postincrement the value of theAnswer and examine how its value changes. Add the following lines to jshell :

  • System.out.println ( "Postincrementing: " + theAnswer ++ ) ;
  • System.out.println ( "Final value: " + theAnswer ) ;

The variable theAnswer first equals to 42 . Then, it is printed and postincremented. On the last line, you print it again to see its final value.

Your output should be:

As you can see, theAnswer remains 42 during the postincrementing. It is when you print it again after postincrementing that it is 43 ( Final value: 43 ).

Postdecrementing works the same way. The value is first retrieved and used, and only after that, is it decremented. As an exercise, try replacing the postincrement operator ++ with the postdecrement operator -- , or even include one of the pre operators.

The NOT Operator

The NOT operator, also known as the logical complement operator , flips the value of a boolean operand. It is represented by the exclamation mark ! . Usually, you use the NOT operator when you have a boolean variable or value, and you want to reuse it with the opposite value. Thus, you don’t have to create another variable with the opposite value unnecessarily.

Here is an example of how the NOT operator works. For simplicity, you’ll flip the value of true :

  • boolean isJavaFun = ! true ;
  • System.out.println ( isJavaFun ) ;

You define the boolean variable isJavaFun as true . However, the NOT operator precedes true ; thus, the value of true is flipped to false . When you run the above code, the following output will print:

This is how the NOT operator works. It might be confusing and hard to spot it sometimes, so you should use it sparingly.

In the above case, instead of !true , you could have used false . This is the right approach because it’s cleaner and more intuitive. As a general rule, it’s best practice to use a literal or method directly, rather than alternatives that require additional operations. However, in some cases, it may not always make sense or even be possible. For example, it’s common to use the NOT operator to flip the result from a boolean method.

As an example, to check if a string contains another string, you can use the method contains() . However, if you want to check the opposite (that is, when a string does not contain another string), there is no alternative built-in method. You’ll need to use contains() with the NOT operator.

Imagine you have the string Java is smart. and you want to check whether:

  • The string contains smart .
  • The string does not contain hard .

To check these, you’ll use the following code:

  • String javaIsSmart = "Java is smart." ;
  • boolean isSmartPartOfJava = javaIsSmart.contains ( "smart" ) ;
  • boolean isHardNotPartOfJava = ! javaIsSmart.contains ( "hard" ) ;

On the first line, you define a String variable javaIsSmart . On the second line, you define a boolean variable isSmartPartOfJava as the result of the operation from the method contains() — in this case, whether the string smart is part of the javaIsSmart string. Similarly, on the third line, you define a boolean variable isHardNotPartOfJava , which is determined by whether hard is not found in javaIsSmart .

When you run this code in jshell , you will get the following output:

According to the above output:

  • isSmartPartOfJava is true because smart is found in javaIsSmart .
  • isHardNotPartOfJava is also true because hard is not found in javaIsSmart .

In this section, you explored incrementing, decrementing, and the NOT operator using one operand. Even though these operators have only one operand, they can be challenging to use, as demonstrated by the NOT operator. In the next step, you’ll build on this knowledge by using operators with two operands.

Binary Operators

Binary operators act on two operands and are commonly associated with arithmetic operations such as addition and subtraction. There are also other non-math related binary operators, such as logical operators and the special relational operator instanceof . In this section, you’ll begin with the arithmetic binary operators, which may be more familiar.

Arithmetic Binary Operators

These are the well-known operators used for arithmetic operations, such as addition ( + ) and subtraction ( - ). Here is an example with addition:

  • int theAnswer = 40 + 2 ;
  • System.out.println ( "The result is: " + theAnswer ) ;

On the first line, you add 40 to 2 and assign the result to theAnswer variable. When you print it, you get the final value 42 :

**NOTE:**In addition to arithmetic operations, the plus sign ( + ) is also used for concatenating strings. You have seen it in action in most of our examples with printing values, such as the one above. There, using the plus sign, you have concatenated "The result is: " with the variable theAnswer . However, this use of the plus sign is an exception, and no other arithmetic operators can be used similarly on reference types. So, for example, you cannot use the minus sign to remove parts of a string.

For additional practice, try using the other arithmetic operators, which you can find in the Java documentation .

Assignment Operators

The assignment operators assign the left operand to the value of the right operand. Usually, the left operand is a variable and the right one is a value or a reference to an object. This may sound familiar because you’ve used such assignments in all of your examples. In this section, you’ll practice using the basic assignment operator, some compound assignment operators, and the casting operator.

The basic assignment operator ( = ) is a well-known and commonly used operator.

  • int x = 1 ;

In this example, you declare an int variable x and assign it the value 1 . Using the equals sign ( = ) is how you assign a value to a variable.

Compound Assignment Operators

The compound assignment operators ( += , -= , *= , \= ) combine assignment along with an additional arithmetic operation such as addition or subtraction. These operators allow you to avoid boilerplate code, especially in arithmetic operations that are straightforward to follow and understand.

For example, use the compound += assignment operator to combine addition and assignment like this:

  • int y = 1 ;
  • System.out.println ( "x is: " + x ) ;

In the first two lines, you declare two integer variables called x and y , both with a value of 1 . Next, you reassign x using the compound += assignment, which means that x is added to y and then is assigned back to x .

The above code will return an output similar to this:

According to the above output, x and y get a value of 1 . On the third line, there is a temporary variable with a randomly-assigned name ( $11 ). It holds the value of x as a result of the compound assignment operation. On the last line, the value of x is printed: 2 .

The same code can be rewritten without the compound assignment operator like this:

  • x = x + y ;

In contrast to the previous example, you write additional code to describe explicitly the addition of x plus y on line 3.

Running this code will return the following output:

Ultimately, in both examples, x equals 2 . However, in the second example, jshell didn’t print a temporary variable name such as $11 . Instead, it used x directly to show that its value has changed ( x ==> 2 ). Such verbose output is very helpful for learning and is available only in jshell .

The rest of the compound operators combine subtraction ( -= ), multiplication ( *= ) and division ( /= ) along with assignment. Try changing the above examples to see how they can work.

It’s good to know about compound operators because they are frequently used. However, there is no performance benefit to using them, so using compound operators is a matter of personal choice. If they seem unnecessarily confusing, you don’t have to use them.

The Casting Operator

The last assignment operator you’ll review is the casting operator, which is a data type surrounded by parentheses: (data type) . The casting operator is used for casting values, which is interpreting one data type as another.

The data types have to be compatible, though. Whether one data type is compatible with another is determined by their relation, such as whether one class is a parent or sibling to another. For example, you can cast int to short because both data types are used for storing whole numbers. However, you cannot cast int to boolean because the two data types are incompatible.

In this section, you’ll explore some common examples of and problems with casting. For educational purposes, you’ll begin with an incorrect and incompatible casting:

  • boolean y = ( boolean ) 1 ;

With this line, you are trying to cast the integer 1 to a boolean value and assign it to the variable y . When you paste this in jshell , you’ll get the following error:

As the error message explains, you cannot convert an int value to a boolean . Boolean values are either true or false , and it’s impossible to determine which boolean value 1 should be.

Now, you’ll try an example with compatible data types. You’ll use two primitive types for storing whole numbers: int and short . The difference is in their capacity, that is, the amount of memory available to store information. int has a larger capacity and thus can store larger numbers.

Add the following lines to jshell :

  • int prize = 32767 ;
  • short wonPrize = ( short ) prize ;
  • System.out.println ( "You won: " + wonPrize ) ;

In the first line, you define the lottery prize as an int primitive type with the value of 32767 . On the second line, however, you decide that a short primitive type will be more suitable for the value of the wonprize , and you cast prize to short using (short) .

When you run the above code in jshell , the output is:

The above output confirms that prize and wonPrize values have been correctly set to 32767 . The last row uses the wonPrize variable to state how much you have won.

In the case of int and short , casting may seem unnecessary and you will probably not see such casting in reality. However, this example is useful for demonstrating the idea of casting.

Casting seems straightforward, but there is one caveat. When you cast from a data type with a larger capacity to a data type with a smaller capacity, you could exceed the smaller capacity limit, which is called overflow . To demonstrate this problem, reuse the previous example and increase the prize from 32767 to 32768 , like so:

  • int prize = 32768 ;

When you run the above in jshell , you will get the following output:

In this case, you lose information and get unexpected results. When cast to short , the value of 32768 becomes -32768 . This is because short ’s storage capacity ranges from - 32768 to 32767 . When you try to store a value larger than the maximum value, you overflow it and start from the beginning. In this case, you exceed the maximum capacity ( 32767 ) by 1 when you try to store 32768 . Because of this, the next value is assigned, starting from the lowest possible. In this case, this is the minimum value of -32768 .

That’s why the above output seems unexpected — the final prize has become a negative number. These kinds of problems are not always easy to spot, so you should use casting carefully. You may use casting in more complex scenarios, which will be addressed in future tutorials from the Java series.

Relational Operators

Relational operators compare two operands and return a boolean result. If the relation is asserted, the result is true . If not, the result is false .

The first types of relational operators are equals == and not equals != . They are used to assert the equality of values and objects. With primitive values and literals, their use is similar to mathematics.

To demonstrate the equals equality operator, compare two integer literals. In fact, it will be one and the same number: 1 . You’ll compare whether it is equal to itself so that you can get a true result. Paste the following code into jshell :

  • System.out.println ( 1 == 1 ) ;

In the above code, you are asserting whether 1 equals 1 . Since the numbers are equal, this expression evaluates to true. Thus, println() prints true :

As an exercise, try changing one of the values in order to get a false result.

Note: Make sure to differentiate between the operator for equality == and the assignment operator = . Even when you know they’re different, it is easy to confuse them. You may not always get a syntax error in your code, which can lead to problems that are hard to debug.

In contrast to comparing primitive values, comparing objects for equality is more complex because you are asserting whether two variables point to the same object. Try comparing two Integers as an example:

  • Integer myAnswer = Integer.valueOf ( 42 ) ;
  • Integer yourAnswer = Integer.valueOf ( 42 ) ;
  • System.out.println ( myAnswer == yourAnswer ) ;

In the above code, you create two Integer variables, each with a value of 42 . On the last line, you compare them for equality and print true if they are equal. From our previous tutorial Understanding Data Types in Java , you may know that Integer.valueOf() first checks the cache for an object with the same value and returns the same object if there is one already with this value. That’s how both myAnswer and yourAnswer receive the same object.

When you paste the above code in jshell , you will get the following output:

Such object comparison seems straightforward, but sometimes it’s challenging. The most confusing example is with strings. Try comparing two strings with the same values:

  • String answer1 = new String ( "yes" ) ;
  • String answer2 = new String ( "yes" ) ;
  • System.out.println ( answer1 == answer2 ) ;

First, you declare two new String variables ( answer1 and answer2 ) with the values "yes" . However, you used the new keyword to create the new String objects. Because of that, the two variables do not point to the same object — they actually point to two different objects (with the same value).

Even though answer1 and answer2 have the same value ( "yes" ), their equality is evaluated to false , which means they are not equal. It can be confusing if you intend to compare values, such as whether both answers are affirmative, and you’re not interested in the underlying objects. For this purpose, many classes, including String , have dedicated methods for asserting equality.

In the case of String, this method is equals() . Try changing the code to use equals() (instead of == ) like this:

  • System.out.println ( answer1. equals ( answer2 ) ) ;

The equals() method verifies that the strings contained in the compared objects are equal.

When you paste this code in jshell , you will get the following output:

The above output is similar to the previous output, but it finishes with true , confirming that the values of the two objects are equal. This example demonstrates that you have to be careful when comparing reference types and use corresponding methods when available.

The alternative equality operator, not equals != , is used similarly, but it asserts whether two variables or values are not the same (or unequal). As an exercise, try replacing == with != in some of the previous examples.

Similar to == and != , the next four relational operators also come from mathematics: less than < , less than or equal to <= , greater than > , and greater than or equal to => .

Here’s an example using the greater than operator:

  • System.out.println ( 4 > 5 ) ;

The above code first compares whether 4 is greater than 5 . Since it is not, the expression evaluates to false . The result of the comparison ( false ) is then printed by the println() method.

The last relational operator is instanceof , which evaluates whether a variable is an instance of a given class (or subclass) or an implementation of an interface. As explained in our Understanding Data Types in Java tutorial, an interface is an abstract entity with a group of requirements.

Use the following example to explore how instanceof works:

  • String greeting = "hello" ;
  • System.out.println ( greeting instanceof String ) ;

First, you create a String variable called greeting . Then, you evaluate in the parentheses whether greeting is an instance of String .

When you paste the code in jshell , you will get the following output:

Since greeting is an instance of String , the expression evaluates to true , which is printed on the screen by println() .

Logical Operators

The logical operators are logical AND ( & ), logical OR ( | ), and exclusive OR ( ^ ). They all evaluate two values as follows:

  • Logical AND is true when both values are true .
  • Logical OR is true when at least one of the values is true .
  • Exclusive OR is true if one value is true and the other is false .

When the logical operators are not true as per the above conditions, they are false.

To use the logical AND ( & ) operator, paste the following example into jshell :

  • boolean isJavaFun = true ;
  • boolean isJavaPowerful = true ;
  • System.out.println ( isJavaFun & isJavaPowerful ) ;

The first two lines define the boolean variables isJavaFun and isJavaPowerful both to true . On line three, in the parentheses, you perform a logical AND operation on isJavaFun and isJavaPowerful and the result is printed by println() .

Both variables are set to true , and a final true is printed as the result of the logical AND operation.

To extend your skills, try using the previous code example with some variations. You can try switching the values of the variables between true and false . You can also try changing the logical operators to logical OR ( | ) and exclusive OR ( ^ ).

An extended version of the logical operators are the so-called short-circuit logical operators : short-circuit AND ( && ) and short-circuit OR ( || ). They are similar to the regular logical AND and OR operators, but they have one important difference: if evaluating the first operator is sufficient for the operation, the second one is not evaluated. Thus, in order for the short-circuit AND to be true, both sides surrounding it have to be true . However, if the left side is false , the right side is not evaluated. Similarly, with the short-circuit OR , if the left side is false , the right is not evaluated.

Here is an example with short-circuit OR :

  • Boolean isNullFun = null ;
  • System.out.println ( isJavaFun || isNullFun ) ;

First, you assign the variable isJavaFun to true . For consistency with the previous examples, this variable is of the primitive type boolean . However, for the next variable, isNullFun , you use the Boolean reference type so that you can assign it to null . For the example, it’s important that you have a null pointing variable, but as you may recall from the tutorial on Understanding Java Data Types , primitives types cannot be null, and that’s why you are using a reference type.

When the short circuit OR takes place in the parentheses, isNullFun is ignored because the left side is true , and this is enough for the whole expression to be true . Thus, when you run the code in jshell , the following output will print:

The first and the second lines confirm that the variables are assigned to true and null . The third line prints true because the short-circuit OR operation has returned true .

The above example was chosen specifically with null in order to demonstrate how short-circuit operators work and that isNullFun will not be evaluated. To see isNullFun evaluated, try changing the short-circuit OR with a regular OR like this:

  • System.out.println ( isJavaFun | isNullFun ) ;

The regular logical OR evaluates both sides of the expression.

When the logical OR tries to evaluate null , you get the java.lang.NullPointerException . Because of this, short-circuit operators are preferred and are almost always used instead of regular logical operators.

As an exercise, practice using the short-circuit && and || , which are the most popular and useful of all.

In this section, you used binary operators in a range of examples, from basic arithmetic to more challenging operations involving casting and comparing objects for equality. In this next section, you’ll work with three operands.

The Ternary Operator

In the previous sections, you practiced using operators with one and two operands. In this final section, you’ll use the ternary operator, the only operator for three operands. Its syntax is this: first operand ? second operand : third operand . The first operand must be a boolean. If it is true , then the second operand is returned from the expression. If the first operand is false , then the third operand is returned.

The ternary operator is popular and frequently used because it can save you from writing complex statements, such as conditionals, and storing their results in temporary variables.

Try a ternary operator with the following example:

  • String shouldILearnJava = isJavaFun ? "yes" : "no" ;
  • System.out.println ( "Should I learn Java: " + shouldILearnJava ) ;

isJavaFun is set to true , and the variable shouldILearnJava is determined by it in a ternary operation. Because the first operand, isJavaFun , is true, the second operand is returned, which is the string "yes" . To verify this, the third line prints the variable shouldILearnJava , which should be yes at this point.

When you run the above code, you will get the following output:

For additional practice, try using the NOT operator in front of isJavaFun :

  • String shouldILearnJava = ! isJavaFun ? "yes" : "no" ;
  • System.out.println ( "Should I learn java: " + shouldILearnJava ) ;

By flipping the value of isJavaFun , you set it from true to false . As a result, the ternary expression will return the last operand, which is "no" .

Ternary expressions can be confusing, especially when you use additional operators such as the NOT operator. However, they can save you some boilerplate code and that’s why they are popular.

Operator Precedence

Once you know the important operators, you will be able to use and even combine them. But before you start combining them, you will need to know the rules for operator precedence.

Operator precedence determines in what order operators are evaluated. Since you are likely to use more than one operator, it’s important to understand operator precedence. While the rules are not always intuitive, you will likely need to know only a few essential rules in practice.

Understanding operator precedence helps you write clean code , which is the de-facto standard for modern programming. To write clean code means to write understandable and maintainable code. In regards to operators, the clean code paradigm translates to using as few operators as possible and creating separate statements instead of nesting and combining operators.

For example, statements such as the one below should be avoided because they are too confusing:

  • boolean isThisCleanCode = ! true || false && true ;

Even if you consult the operators documentation , you might not be able to guess the end result ( isThisCleanCode is false ).

Here are some of the most important and commonly used precedence rules, starting with the rules with the highest precedence:

  • Pre and post increment and decrement operators: They have the highest precedence and take effect before any other operators.
  • Arithmetic rules from math: All rules valid in math are also valid in Java. For example, division / has higher precedence than addition + . Parentheses override the precedence; that is, you can group operations with parentheses and they will be evaluated with priority.
  • Equality and relational operators: Since they evaluate equality or relation, they also work with the final values of their operands, and thus all other operations have to be completed.
  • Logical OR and AND operators (including short-circuit): Similar to the ternary operator, they all need the final values of their operands, hence their low precedence.
  • Ternary operator: The ternary operator needs the final value of the first operand. For this to happen, all other operations must have been completed. That’s why the ternary operator has such low precedence.
  • Assignment operators: They are evaluated last so that all other operations have been completed and the final result can be assigned to the operand on the left. As an example, think of every variable that you have assigned with the equals sign so far.

Now, you’ll use a math problem to explore operator precedence:

  • int x = 1 + 10 / 2 ;

According to the above output, x gets the value of 6 . This is because the following operations have been completed with decreasing priority:

  • 10 / 2 is evaluated first. It results in 5 .
  • 1 is added to the result of the first operation ( 5 ). This results in 6 .
  • The assignment operator comes into play and uses the final result ( 6 ) to assign it to the variable x .

Even though this math equation is relatively straightforward, you can always make it more verbose and ensure that precedence is easily understood by using parentheses. Consider rewriting it like this:

  • int x = 1 + ( 10 / 2 ) ;

When you paste the above in jshell , the same result as before will print:

In the last example, you didn’t change the precedence by using parentheses around 10 / 2 . Instead, their purpose was only to make the precedence of the operation inside them more obvious. Using parentheses like this helps you make your code more clean and understandable, which is especially important when the operations are more complex.

Precedence rules are interesting and spending some time learning them is a good idea. Keep in mind the clean code paradigm and consider the fact that unnecessary nesting and combining of operators is seen as a weakness in the code.

In this tutorial, you learned about the primary operators in Java. You wrote a few test code snippets in which you saw some of the most useful and interesting scenarios related to operators. You also learned about clean code and the fact that operators shouldn’t be overused unnecessarily.

For more on Java, check out our How To Code in Java series.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

Tutorial Series: How To Code in Java

Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

  • 1/9 How To Write Your First Program in Java
  • 2/9 Understanding Data Types in Java
  • 3/9 How To Use Operators in Java

Default avatar

Technical Editor

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative Commons

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Popular Topics

  • Linux Basics
  • All tutorials
  • Talk to an expert

Join the Tech Talk

Please complete your information!

Featured on Community

java multiple assignment operator

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

java multiple assignment operator

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

java multiple assignment operator

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Featured Tutorials

Digitalocean products, welcome to the developer cloud.

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Java Multiple Ternary operators

I'm studying some Java at the moment at I've come across the following piece of code. I understand how the typical ternary operator (e.g. the line beginning with "boolean a" below), but I can't understand how to read the expression on the line beginning with "boolean b". Any help on how to read this line would be much appreciated! Thanks!

  • conditional-operator
  • assignment-operator

Lino's user avatar

  • 2 Go through the details of operator precedence: docs.oracle.com/javase/tutorial/java/nutsandbolts/… . I feel for you--that code is abstruse. –  La-comadreja Commented Mar 3, 2014 at 15:54
  • Ternary operator has the following format (condition ? result when condition is true : result when condition is false). So here, we define the boolean a, then assign it the result of the ternary operator. –  Ali Cheaito Commented Mar 3, 2014 at 15:57

8 Answers 8

Break it up like this:

So here the testing condition is always set to true . So the branch of the ternary that executes is the ++i > 2 ? true : false part.

This simply checks to see if after incrementing, i is greater than 2 . If so, it will return true . Otherwise it will return false .

This whole expression is actually needlessly complex. It can simply be written as such:

However, the code is probably logically incorrect since this abstruse expression doesn't make that much sense. Since the previous line sets the value of a , I'm assuming that the next line actually intends to test a . So the actual intent might be:

In which case you can break it up as:

But you don't need to actually do a == true since a is already a boolean , so you can do:

Here, it checks to see if a is true . If it is, it performs the check we already went over (i.e., to see if the incremented value of i is greater than 2 ), otherwise it returns false .

But even this complicated expression can be simplified to just:

Vivin Paliath's user avatar

  • What about the last false? Does it do a truth table T v F = T? –  Engineer2021 Commented Mar 3, 2014 at 15:57
  • The last false would never be evaluated in this case since the test is always true . –  Vivin Paliath Commented Mar 3, 2014 at 15:59
  • 1 Thanks for your explanation Vivin (and everyone else). The code actually came from a sample OCJA exam which is possibly explains why it is written so needlessly complex. Thanks again! –  John Kilo Commented Mar 3, 2014 at 16:12
  • lol now i had -3 on my deleted question for being the first one to mention b = a = true is incorrect . And see your comment below Rohit Jain's answer.. –  Saro Taşciyan Commented Mar 3, 2014 at 16:14
  • @Zefnus I meant "correct" as in the code would compile. But yeah, it doesn't really make sense. –  Vivin Paliath Commented Mar 3, 2014 at 16:15

Ah! Never write code like that. But I would assume that is not written by you. But you can read it like this:

which can be broken further as:

which can be further broken down as:

Also, the first assignment:

can also be written as:

Rohit Jain's user avatar

  • I don't think this is correct. The boolean b = a = true is correct; it is just assigning the result to both a and b . –  Vivin Paliath Commented Mar 3, 2014 at 15:58
  • a == true is not too nice, but it does not assign true to a. –  Gábor Bakos Commented Mar 3, 2014 at 15:58
  • FYI, IntelliJ simplified it to boolean b = a = ++i > 2; . –  Arnaud Denoyelle Commented Mar 3, 2014 at 15:59
  • @VivinPaliath Updated the answer for that case, but I suspect it really meant that. That would be strange code in that case. –  Rohit Jain Commented Mar 3, 2014 at 16:01
  • @GáborBakos I know a == true is not too nice. Please see my updated answer. –  Rohit Jain Commented Mar 3, 2014 at 16:02

TorbenIT's user avatar

In boolean b = a = true ? ++i > 2 ? true:false:false; the following happens:

This will give a true value and evaluate to true .

Than we get another condition, ++i > 2 from ++i > 2 ? true:false , which will be also true in this case. The outcome will be true .

Gábor Bakos's user avatar

Ternary operators are

condition then true or false

The condition is always true (because a equals true).

Then the result is true because ++i is greater than 2 (it's 3).

Therefore, it assigns true to b . If the condition was false, it would assign false. That false would be assigned from the last false.

Engineer2021's user avatar

It would help if you could use parentheses and review that code as follows;

You can think it as:

Where if(true) is a Tautology and If Number:2 will always be executed. Therefore; it becomes;

Which can be evaluated to; a = (++i > 2) ? true : false); and which becomes: a = ++i > 2 as a result b = a which is ++i > 2 .

Saro Taşciyan's user avatar

With some guesses at what is being attempted and some renaming of variables, and assuming the a = true was meant to be a == true you get:

This can then be tidied up to the much more logical:

OldCurmudgeon's user avatar

Horrible code!

There are a couple of clues that the b = a = true ? ... should be b = a == true ? ... , since otherwise the previous line is a useless assignment (a is never read), and the final false of the line becomes unreachable code. The compiler will tell you that.

I'm going to answer assuming a corrected == - but you'll know whether it was a typo on your part, an unreliable source, or a 'spot the bug' test, and be able to use the same techniques on whatever code you like.

The trick is to refactor it step by step. First add brackets and indentation based on precedence rules.

Next note that:

  • a == true is equivalent to a .
  • boolean x = a ? true : false; is equivalent to boolean x = a .

If this is "serious" code, the way to approach this would be to write a set of unit tests that cover all the possible input cases. Then make these refactorings one at a time, each time re-running the tests to ensure that you've not changed the behaviour of the code.

Notice that there are no true or false literals in the reduced form. Seeing boolean literals in a ternary operation -- or indeed, ternary expressions for boolean values at all -- is a code smell, since the non-ternary version is usually simpler and clearer.

Ternary expressions are very useful for their intended purpose, which is mapping boolean conditions to non-boolean outputs:

slim's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java conditional-operator assignment-operator or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Does full erase create all 0s or all 1s on the CD-RW?
  • Sharing course material from a previous lecturer with a new lecturer
  • What was I thinking when I drew this diagram?
  • Why did Resolve[] fail to verify a statement whose counter-example was proven to be nonexistant by FindInstance[]?
  • Communicate the intention to resign
  • The minimal Anti-Sudoku
  • Someone wants to pay me to be his texting buddy. How am I being scammed?
  • Sums of X*Y chunks of the nonnegative integers
  • How are USB-C cables so thin?
  • When is internal use internal (considering licenses and their obligations)?
  • What is the lowest feasible depth for lightly-armed military submarines designed around the 1950s-60s?
  • How is delayed luggage returned to its owners from a location with infrequent flights?
  • Rock paper scissor game in Javascript
  • When would it be legal to ask back (parts of) the salary?
  • Is there any point "clean-installing" on a brand-new MacBook?
  • Why would luck magic become obsolete in the modern era?
  • What mode of transport is ideal for the cold post-apocalypse?
  • What are these on my cabbages?
  • Characterization of normed spaces based on violation of parallelogram law
  • Why didn't Walter White choose to work at Gray Matter instead of becoming a drug lord in Breaking Bad?
  • Why is Excel not counting time with COUNTIF?
  • I can't hear you
  • How can I cross an overpass in "Street View" without being dropped to the roadway below?
  • How can I obscure branding on the side of a pure white ceramic sink?

java multiple assignment operator

COMMENTS

  1. Java Assignment Operators with Examples

    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.

  2. 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 ...

  3. Java Operators

    Test yourself with multiple choice questions. Get Certified. Document your knowledge. ... 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: Example

  4. Types of Assignment Operators in Java

    To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side. Example: int x = 10; int x = 10; In the above example, the variable x is assigned the value 10.

  5. 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.

  6. 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.

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

  8. 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. operand1 operator_symbol operand2. In this tutorial, we will learn about different Assignment Operators available in Java programming language ...

  9. Java

    Example. =. Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A.

  10. 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 =. ... Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables. Example:

  11. 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.

  12. Java Assignment Operators

    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; The += is called the addition ...

  13. Operators in Java (Examples and Practice)

    Learn about all the different types of operators available in Java like Arithmetic, Assignment, Relational and Logical operators. Practice Problems to solidify your knowledge. ... When you have an expression with multiple operators, Java needs to know which operation to do first. This is where operator precedence and associativity come in.

  14. Java Operators

    Walk through all Java operators to understand their functionalities and how to use them. ... Next, let's see which assignment operators we can use in Java. 9.1. The Simple Assignment Operator. The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples.

  15. 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 ...

  16. Parallel assignment in Java?

    9. Python's multiple assignment is fairly powerful in that it can also be used for parallel assignment, like this: (x,y) = (y,x) # Swap x and y. There is no equivalent for parallel assignment in Java; you'd have to use a temporary variable: t = x; x = y; y = t; You can assign several variables from expressions in a single line like this:

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

    2. Java Assignment Operators. Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age. Let's see some more assignment operators available in Java.

  18. Compound assignment operators in Java

    The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction assignment operator) 3. *= (compound multiplication assignment operator) 4. /= (compound division assignment operator) 5. %= (compound modulo assignment operator)

  19. 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 ...

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

    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.

  21. assign

    Java does not allow returning multiple values. Python allows this: def foo(): return 1, 2, 3. a, b, c = foo() The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable: Wrapper wrapper = WrapperGenrator.generateWrapper(); You can not assign to a tuple on the LHS as you can in Python.

  22. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  23. How To Use Operators in Java

    These operators allow you to avoid boilerplate code, especially in arithmetic operations that are straightforward to follow and understand. For example, use the compound += assignment operator to combine addition and assignment like this: int x = 1; int y = 1; x += y; System.out.println ("x is: " + x);

  24. Java Multiple Ternary operators

    0. Ternary operators are. condition then true or false. The condition is always true (because a equals true). Then the result is true because ++i is greater than 2 (it's 3). Therefore, it assigns true to b. If the condition was false, it would assign false. That false would be assigned from the last false.