Javatpoint Logo

Java Tutorial

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

JavaTpoint

In , assignment is used to assign values to a variable. In this section, we will discuss the .

The is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results in shorter syntax forms. In short, the compound assignment operator can be used in place of an assignment operator.

For example:

Let's write the above statements using the compound assignment operator.

Using both assignment operators generates the same result.

Java supports the following assignment operators:

Catagories Operator Description Example Equivalent Expression
It assigns the result of the addition. count += 1 count = count + 1
It assigns the result of the subtraction. count -= 2 count = count - 2
It assigns the result of the multiplication. price *= quantity price = price * quantity
It assigns the result of the division. average /= number_of_terms average = number_of_terms
It assigns the result of the remainder of the division. s %= 1000 s = s % 1000
It assigns the result of the signed left bit shift. res <<= num res = res << num
It assigns the result of the signed right bit shift. y >>= 1 y = y >> 1
It assigns the result of the logical AND. x &= 2 x = x & 2
It assigns the result of the logical XOR. a ^= b a = a ^ b
It assigns the result of the logical OR. flag |= true flag = flag | true
It assigns the result of the unsigned right bit shift. p >>>= 4 p = p >>> 4

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

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

Java Compound Operators

Last updated: March 17, 2024

what is compound assignment in java

  • Java Operators

announcement - icon

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

In this tutorial, we’ll have a look at Java compound operators, their types and how Java evaluates them.

We’ll also explain how implicit casting works.

2. Compound Assignment Operators

An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. The simplest is the “=” assignment operator:

This statement declares a new variable x , assigns x the value of 5 and returns 5 .

Compound Assignment Operators are a shorter way to apply an arithmetic or bitwise operation and to assign the value of the operation to the variable on the left-hand side.

For example, the following two multiplication statements are equivalent, meaning  a and b will have the same value:

It’s important to note that the variable on the left-hand of a compound assignment operator must be already declared. In other words,  compound operators can’t be used to declare a new variable.

Like the “=” assignment operator, compound operators return the assigned result of the expression:

Both x and y will hold the value 3 .

The assignment (x+=2) does two things: first, it adds 2 to the value of the variable x , which becomes  3;  second, it returns the value of the assignment, which is also 3 .

3. Types of Compound Assignment Operators

Java supports 11 compound assignment operators. We can group these into arithmetic and bitwise operators.

Let’s go through the arithmetic operators and the operations they perform:

  • Incrementation: +=
  • Decrementation: -=
  • Multiplication: *=
  • Division: /=
  • Modulus: %=

Then, we also have the bitwise operators:

  • AND, binary: &=
  • Exclusive OR, binary: ^=
  • Inclusive OR, binary: |=
  • Left Shift, binary: <<=
  • Right Shift, binary: >>=
  • Shift right zero fill: >>>=

Let’s have a look at a few examples of these operations:

As we can see here, the syntax to use these operators is consistent.

4. Evaluation of Compound Assignment Operations

There are two ways Java evaluates the compound operations.

First, when the left-hand operand is not an array, then Java will, in order:

  • Verify the operand is a declared variable
  • Save the value of the left-hand operand
  • Evaluate the right-hand operand
  • Perform the binary operation as indicated by the compound operator
  • Convert the result of the binary operation to the type of the left-hand variable (implicit casting)
  • Assign the converted result to the left-hand variable

Next, when the left-hand operand is an array, the steps to follow are a bit different:

  • Verify the array expression on the left-hand side and throw a NullPointerException  or  ArrayIndexOutOfBoundsException if it’s incorrect
  • Save the array element in the index
  • Check if the array component selected is a primitive type or reference type and then continue with the same steps as the first list, as if the left-hand operand is a variable.

If any step of the evaluation fails, Java doesn’t continue to perform the following steps.

Let’s give some examples related to the evaluation of these operations to an array element:

As we’d expect, this will throw a  NullPointerException .

However, if we assign an initial value to the array:

We would get rid of the NullPointerException, but we’d still get an  ArrayIndexOutOfBoundsException , as the index used is not correct.

If we fix that, the operation will be completed successfully:

Finally, the x variable will be 6 at the end of the assignment.

5. Implicit Casting

One of the reasons compound operators are useful is that not only they provide a shorter way for operations, but also implicitly cast variables.

Formally, a compound assignment expression of the form:

is equivalent to:

E1 – (T)(E1 op E2)

where T is the type of E1 .

Let’s consider the following example:

Let’s review why the last line won’t compile.

Java automatically promotes smaller data types to larger data ones, when they are together in an operation, but will throw an error when trying to convert from larger to smaller types .

So, first,  i will be promoted to long and then the multiplication will give the result 10L. The long result would be assigned to i , which is an int , and this will throw an error.

This could be fixed with an explicit cast:

Java compound assignment operators are perfect in this case because they do an implicit casting:

This statement works just fine, casting the multiplication result to int and assigning the value to the left-hand side variable, i .

6. Conclusion

In this article, we looked at compound operators in Java, giving some examples and different types of them. We explained how Java evaluates these operations.

Finally, we also reviewed implicit casting, one of the reasons these shorthand operators are useful.

As always, all of the code snippets mentioned in this article can be found in our GitHub repository .

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

Java Compound Assignment Operators

Java programming tutorial index.

Java provides some special Compound Assignment Operators , also known as Shorthand Assignment Operators . It's called shorthand because it provides a short way to assign an expression to a variable.

This operator can be used to connect Arithmetic operator with an Assignment operator.

For example, you write a statement:

In Java, you can also write the above statement like this:

There are various compound assignment operators used in Java:

Operator Meaning
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns
<<= Binary Left Shift  and assigns
>>= Binary Right Shift and assigns
>>>= Shift right zero fill and assigns
&= Binary AND assigns
^= Binary exclusive OR and assigns
|= Binary inclusive OR and assigns

While writing a program, Shorthand Operators saves some time by changing the large forms into shorts; Also, these operators are implemented efficiently by Java runtime system compared to their equivalent large forms.

Programs to Show How Assignment Operators Works

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.

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

One of the most common operators that you'll encounter is the simple assignment operator " = ". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

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. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.

Operator Description
Additive operator (also used for String concatenation)
Subtraction operator
Multiplication operator
Division operator
Remainder operator

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments . For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Operator Description
Unary plus operator; indicates positive value (numbers are positive without this, however)
Unary minus operator; negates an expression
Increment operator; increments a value by 1
Decrement operator; decrements a value by 1
Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo , tests the unary operators:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version ( ++result ) evaluates to the incremented value, whereas the postfix version ( result++ ) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo , illustrates the prefix/postfix unary increment operator:

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

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

what is compound assignment in java

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Preface
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Variables
  • 1.7 Java Development Environments (optional)
  • 1.8 Unit 1 Summary
  • 1.9 Unit 1 Mixed Up Code Practice
  • 1.10 Unit 1 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Lesson Workspace
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Variables' data-toggle="tooltip" >

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below.

+ shortcuts

- shortcuts

* shortcut

/ shortcut

% shortcut

x = x + 1;

x = x - 1;

x = x * 2;

x = x / 2;

x = x % 2;

x += 1;

x -= 1;

x *= 2;

x /= 2;

x %= 2;

x++;

x- -;

The most common shortcut operator ++ , the plus-plus or increment operator, is used to add 1 to the current value; x++ is the same as x += 1 and the same as x = x + 1 . It is a shortcut that is used a lot in loops. If you’ve heard of the programming language C++, the ++ in C++ is an inside joke that C has been incremented or improved to create C++. The -- decrement operator is used to subtract 1 from the current value: y-- is the same as y = y - 1 . These are the only two double operators; this shortcut pattern does not exist with other operators. Run the following code to see these shortcut operators in action!

coding exercise

Run the code below to see what the ++ and shorcut operators do. Use the Codelens to trace through the code and observe how the variable values change. Try creating more compound assignment statements with shortcut operators and guess what they would print out before running the code.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

Code Tracing is a technique used to simulate by hand a dry run through the code or pseudocode as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

For example, given the following code:

The corresponding trace table looks like this:

Line

Statement

x

y

z

1

x = 10;

10

2

y = 15;

15

3

z = x * y;

150

4

z++;

151

5

x = z * 2;

302

Alternatively, we can show a compressed trace by listing the sequence of values assigned to each variable as the program executes. You might want to cross off the previous value when you assign a new value to a variable. The last value listed is the variable’s final value.

Compressed Trace

Use paper and pencil to trace through the following program to determine the values of the variables at the end. Be careful, % is the remainder operator, not division.

1.5.2. Prefix versus Postfix Operator ¶

What do you think is printed when the following code is executed? Try to guess the output before running the code. You might be surprised at the result. Click on CodeLens to step through the execution. Notice that the second println prints the original value 7 even though the memory location for variable count is updated to the value 8.

The code System.out.println(count++) adds one to the variable after the value is printed. Try changing the code to ++count and run it again. This will result in one being added to the variable before its value is printed. When the ++ operator is placed before the variable, it is called prefix increment. When it is placed after, it is called postfix increment.

Example

Description

Type

System.out.println(count++);

Print the current value of count, then add one to count

Postfix

System.out.println(++count);

Add one to count, then print the new value

Prefix

x = y++;

Copy the value of y into x, then add one to y

Postfix

x = ++y;

Add one to y, then copy the value of y into x

Prefix

x = y- -;

Copy the value of y into x, then subtract one from y

Postfix

x = - -y;

Subtract one from y, then copy the value of y into x

Prefix

  • System.out.println(score++);
  • Print the value 5, then assign score the value 6.
  • System.out.println(score--);
  • Print the value 5, then assign score the value 4.
  • System.out.println(++score);
  • Assign score the value 6, then print the value 6.
  • System.out.println(--score);
  • Assign score the value 4, then print the value 4.

When you are new to programming, it is advisable to avoid mixing unary operators ++ and -- with assignment or print statements. Try to perform the increment or decrement operation on a separate line of code from assignment or printing.

For example, instead of writing x=y++; or System.out.println(z--); the code below makes it clear that the increment of y happens after the assignment to x , and that the value of z is printed before it is decremented.

  • System.out.println(score); score++;
  • System.out.println(score); score--;
  • score++; System.out.println(score);
  • score--; System.out.println(score);

1.5.3. Summary ¶

Compound assignment operators (+=, -=, *=, /=, %=) can be used in place of the assignment operator.

The increment operator (++) and decrement operator (–) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Compound assignment operators in Java\n

The 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 assigns the result to left operand.
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns 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 assigns the result to the left operand.
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to left operand.
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns 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

This will produce the following result −

karthikeya Boyini

  • Related Articles
  • Compound Assignment Operators in C++
  • Compound assignment operators in C#
  • Perl Assignment Operators
  • Assignment operators in Dart Programming
  • Compound operators in Arduino
  • What is the difference between = and: = assignment operators?
  • Initialization, declaration and assignment terms in Java
  • Interesting facts about Array assignment in Java
  • Division Operators in Java
  • Java Boolean operators
  • Java Operators Precedence
  • Differences between & and && operators in Java.
  • Differences between | and || operators in Java
  • Logical Operators on String in Java
  • Floating point operators and associativity in Java

Kickstart Your Career

Get certified by completing the course

What are Compound Assignment Operators in Java and Why You Should Use Them

Cover image for What are Compound Assignment Operators in Java and Why You Should Use Them

Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand .

Compound Assignment Operator using Addition

Consider an example where we want to increase a given number by 3. The long version can be written as follows:

The number variable is used as the variable to store the expression value and as an operand. Because of this, we can use a shorter syntax of compound assignment operators. The code can be written as:

Let's see another example using string concatenation:

Using compound assignment operators, this can be condensed to:

Compound Assignment Operator using Subtraction

As another example, let's see how we can decrease a number by 3:

Again, since number is used as the variable to store the expression value and an operand, we can use the compound assignment operator:

All arithmetic and bitwise operators can be used in compound assignment operators. This post shows examples using addition and subtraction to show the general syntax. Division, multiplication, modulus, AND, OR, XOR,left shift, right shift, and unsigned right shift would also work. Overall, using the compound assignment operator requires less code to type and is more common to see code written this way.

what is compound assignment in java

  • Java history and features
  • Download and Install JDK
  • Environment setup & first program
  • Primitve Data types
  • Class Access Modifiers
  • Class Member Access Modifiers
  • Abstract Class
  • Final keyword in Java
  • Static keyword in Java
  • this keyword in Java
  • Encapsulation
  • Inheritance
  • Aggregation and composition
  • Polymorphism
  • Overloading
  • Constructors in Java
  • Coupling and cohesion
  • Stack and Heap in Java
  • Array in Java
  • 2-Dimensional Array in Java
  • Enums in Java
  • Return Types in Java
  • Var-args in Java
  • Garbage Collector
  • Method finalize()
  • Static Initialization Block
  • Instance Initialization Block
  • Static vs Instance Block
  • decision-making Statements
  • If Statement
  • If-Else Statement
  • Else-If Statement
  • Nested If Statement
  • Nested If-Else Statement
  • Switch Statement
  • Do-While Loop
  • Break Statement
  • Continue Statement
  • Labelled Break Statement
  • Labelled Continue Statement
  • Arithmetic Operator
  • Increment Operator
  • Decrement Operator
  • Compound Assignment Operators
  • Relational Operators
  • Logical Operators
  • Conditional Operator
  • instanceof operator
  • Character Wrapper Class
  • Boolean Wrapper Class
  • Byte Wrapper Class
  • Short Wrapper Class
  • Integer Wrapper Class
  • Long Wrapper Class
  • Float Wrapper Class
  • Double Wrapper Class
  • Autoboxing and Unboxing
  • Widening and Narrowing
  • What is Exception?
  • Checked Exception
  • Unchecked Exception
  • Exception Propagation
  • Try-Catch block
  • Multiple Catch Blocks
  • Finally block
  • Throw Keyword
  • Throws Keyword
  • User Defined Exception

Advertisement

+= operator

  • Add operation.
  • Assignment of the result of add operation.
  • Understanding += operator with a code -
  • Statement i+=2 is equal to i=i+2 , hence 2 will be added to the value of i, which gives us 4.
  • Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.
  • A special case scenario for all the compound assigned operators
  • All compound assignment operators perform implicit casting.
  • Casting the char value ( smaller data type ) to an int value( larger data type ), so it could be added to an int value, 2.
  • Finally, the result of performing the addition resulted in an int value, which was casted to a char value before it could be assigned to a char variable, ch .

Example with += operator

-= operator.

  • Subtraction operation.
  • Assignment of the result of subtract operation.
  • Statement i-=2 is equal to i=i-2 , hence 2 will be subtracted from the value of i, which gives us 0.
  • Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.

Example with -= operator

*= operator.

  • Multiplication operation.
  • Assignment of the result of multiplication operation.
  • Statement i*=2 is equal to i=i*2 , hence 2 will be multiplied with the value of i, which gives us 4.
  • Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.

Example with *= operator

/= operator.

  • Division operation.
  • Assignment of the result of division operation.
  • Statement i/=2 is equal to i=i/2 , hence 4 will be divided by the value of i, which gives us 2.
  • Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.

Example with /= operator

%= operator.

  • Modulus operation, which finds the remainder of a division operation.
  • Assignment of the result of modulus operation.
  • Statement i%=2 is equal to i=i%2 , hence 4 will be divided by the value of i and its remainder gives us 0.
  • Finally, the result of this modulus operation i.e. 0 is assigned back to i, updating its value from 4 to 0.

Example with %= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

© Copyright 2020 Decodejava.com. All Rights Reserved.

  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Difference between Simple and Compound Assignment in Java

Many programmers believe that the statement “x += i” is simply a shorthand for “x = x + i”. This isn’t quite true. Both of these statements are assignment expressions. The second statement uses the simple assignment operator (=), whereas the first uses a compound assignment operator. The compound assignment operators are +=, -=, *=, /=, %= etc. The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment, E1 = (T) ((E1) op (E2)), where T is the type of E1. In other words, compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion . Attempting to perform the equivalent simple assignment would generate a compilation error . Consider the following examples- 

You might expect the value of x to be 123456 after this statement executes, but it isn’t; it’s -7616. The int value 123456 is too big to fit in a short. The automatically generated cast. It silently removes the two high-order bytes of the int value. 

It is clear from above examples that compound assignment expressions can cause undesirable results and should be used carefully for types like byte, short, or char. If we use them, we must ensure that the type of expression on right is not of higher precision. 

Please Login to comment...

Similar reads.

  • Difference Between
  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Advantage of using compound assignment

What is the real advantage of using compound assignment in C/C++ (or may be applicable to many other programming languages as well)?

I looked at few links like microsoft site , SO post1 , SO Post2 . But the advantage says exp1 is evaluated only once in case of compound statement. How exp1 is really evaluated twice in first case? I understand that current value of exp1 is read first and then new value is added. Updated value is written back to the same location. How this really happens at lower level in case of compound statement? I tried to compare assembly code of two cases, but I did not see any difference between them.

  • compound-assignment

Rajesh's user avatar

  • There's a good chance that your compiler optimised it. Anyway, assembly language usually has increment opcodes. In fact, they don't have anything else. If you do something like 1 + 2 in C, it would be compiled to something like move 1,a and add 2,a . –  SeverityOne Commented Apr 19, 2018 at 13:22
  • @SeverityOne's response should be the answer... –  Frederick Commented Apr 19, 2018 at 13:27

6 Answers 6

For simple expressions involving ordinary variables, the difference between

is syntactical only. The two expressions will behave exactly the same, and might well generate identical assembly code. (You're right; in this case it doesn't even make much sense to ask whether a is evaluated once or twice.)

Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects. So if you have something like

it makes much more of a difference! The former tries to increment p twice (and is therefore undefined). But the latter evaluates p++ precisely once, and is well-defined.

As others have mentioned, there are also advantages of notational convenience and readability. If you have

it can be hard to spot the bug. But if you use

it's impossible to even have that bug, and a later reader doesn't have to scrutinize the terms to rule out the possibility.

A minor advantage is that it can save you a pair of parentheses (or from a bug if you leave those parentheses out). Consider:

Finally (thanks to Jens Gustedt for reminding me of this), we have to go back and think a little more carefully about what we meant when we said "Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects." Normally, we think of modifications as being side effects, and accesses as being "free". But for variables qualified as volatile (or, in C11, as _Atomic ), an access counts as an interesting side effect, too. So if variable a has one of those qualifiers, a = a + b is not a "simple expression involving ordinary variables", and it may not be so identical to a += b , after all.

Steve Summit's user avatar

  • Got the real issue now. I think most books does not highlight this concept of two time evaluation by giving good example. In fact this is the most important difference than the readability. @dbush also gave another good example where we can easily see the result of two time evaluation. Disadvantage indicated by chux also give us better clarity. –  Rajesh Commented Apr 19, 2018 at 14:58
  • No, they are not always the same. It depends on what a is. If it is volatile or _Atomic the result is fundamentally different. –  Jens Gustedt Commented Apr 19, 2018 at 18:54
  • How would tmp = *XYZ; be interpreted and why? my compiler interprets this as: Copy *XYZ to temp, and why not tmp = tmp * XYZ ? Note: XYZ is pointer. –  M Sharath Hegde Commented Aug 30, 2018 at 6:58
  • 1 @MSharathHegde If the compound assignment operator were spelled " =* ", there might be some ambiguity here, but since it is in fact spelled " *= ", it's perfectly clear that tmp=*XYZ must involve a pointer access, not a multiplication. (Now, in the earliest days of C, the compound assignment operator was spelled " =* ", and there was ambiguity, which is why the compound assignment operators were rejiggered to their modern form.) –  Steve Summit Commented Aug 30, 2018 at 9:27

Evaluating the left side once can save you a lot if it's more than a simple variable name. For example:

In this case some_long_running_function() is only called once. This differs from:

Which calls the function twice.

dbush's user avatar

There is a disadvantage too. Consider the effect of types.

10 + b addition below will use int math and overflow ( undefined behavior )

chux - Reinstate Monica's user avatar

  • even clang -Weverything don't produce warning... it's should ! –  Stargateur Commented Apr 19, 2018 at 14:42

This is what the standard 6.5.16.2 says:

A compound assignment of the form E1 op = E2 is equivalent to the simple assignment expression E1 = E1 op ( E2 ), except that the lvalue E1 is evaluated only once

So the "evaluated once" is the difference. This mostly matters in embedded systems where you have volatile qualifiers and don't want to read a hardware register several times, as that could cause unwanted side-effects.

That's not really possible to reproduce here on SO, so instead here's an artificial example to demonstrate why multiple evaluations could lead to different program behavior:

The simple assignment version did not only give a different result, it also introduced unspecified behavior in the code, so that two different results are possible depending on the compiler.

Eric Postpischil's user avatar

  • correct. in addition to volatile it can also make a difference for atomic qualified types. –  Jens Gustedt Commented Apr 19, 2018 at 18:57

Not sure what you're after. Compound assignment is shorter, and therefore simpler (less complex) than using regular operations.

Consider this:

Which one is easier to read and understand, and verify?

This, to me, is a very very real advantage, and is just as true regardless of semantic details like how many times something is evaluated.

unwind's user avatar

  • Arguably the main issue with your example is that you don't follow the law of Demeter. The difference between x += dt * speed and x =x + dt * speed is less, but still worth having. –  Pete Kirkham Commented Apr 19, 2018 at 13:38
  • I agree with this answer. Modern compilers usually do not need any "help" by programmers using specific language constructs. In fact today better readability of a code fragment usually also means better optimization by the compiler. –  Blue Commented Apr 19, 2018 at 13:41
  • @unwind I am mainly talking about performance related issues rather than readability. According to Microsoft, "However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation". Here is what I am expecting some kind of explanation. –  Rajesh Commented Apr 19, 2018 at 13:49

A language like C is always going to be an abstraction of the underlying machine opcodes. In the case of addition, the compiler would first move the left operand into the accumulator, and add the right operand to it. Something like this (pseudo-assembler code):

This is what 1+2 would compile to in assembler. Obviously, this is perhaps over-simplified, but you get the idea.

Also, compiler tend to optimise your code, so exp1=exp1+b would very likely compile to the same opcodes as exp1+=b .

And, as @unwind remarked, the compound statement is a lot more readable.

SeverityOne's user avatar

  • I am using TDM-GCC-64 compiler. Optimization is turned off. Here is the log 'gcc.exe -Wall -s -pedantic -Wextra -Wall -g -c "C:\sample_Project_Only_Main\main.c" -o Debug\main.o g++.exe -o Debug\sample_Project_Only_Main.exe Debug\main.o " –  Rajesh Commented Apr 19, 2018 at 13:54
  • Fair enough. Still, assembly always works along the lines of "add something to a register or memory location", which is what the += operator does. –  SeverityOne Commented Apr 19, 2018 at 17:03

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 c c11 compound-assignment 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

  • Counter in Loop
  • I stopped an interview because I couldn't solve some difficult problems involving technology I haven't used in years. What could I have done instead?
  • Why is Excel not counting time with COUNTIF?
  • Looking for a British childrens book, I think from the 1950s, called "C-for-Charlie"
  • Why do instructions for various goods sold in EU nowadays lack pages in English?
  • How do I loosen this nut of my toilet lid?
  • Can you continue a database log restore after putting an interim restore online?
  • Would several years of appointment as a lecturer hurt you when you decide to go for a tenure-track position later on?
  • how can I handle this challenge with S3 indicating Orange color
  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Getting "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'" when attempting to setup log shipping on Linux for a SQL Server database
  • 3D cartoon involving a lion with a crown on his head, a crystal, and artifacts that need to be found
  • Characterization of normed spaces based on violation of parallelogram law
  • Someone wants to pay me to be his texting buddy. How am I being scammed?
  • Examples of flat projective morphisms with non-divisorial branch locus
  • What counts as a pet?
  • Why is "a black belt in Judo" a metonym?
  • Functional derivative under a path integral sign
  • Dropper post won't actuate. Is this fixable?
  • Sharing course material from a previous lecturer with a new lecturer
  • Claims of "badness" without a moral framework?
  • How to get the value of a specified index number from the sorting of a column and fill it with null if missing?
  • What tool has a ring on the end of a threaded handle shaft?
  • How to declutter a mobile app home screen with a floating “Create Video” component?

what is compound assignment in java

IMAGES

  1. 010

    what is compound assignment in java

  2. Java Lesson 12

    what is compound assignment in java

  3. Compound Assignment Operators in Java

    what is compound assignment in java

  4. JAVA

    what is compound assignment in java

  5. Java Compound Operators

    what is compound assignment in java

  6. Java Compound Assignment Operators

    what is compound assignment in java

COMMENTS

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

  2. Compound Assignment Operator in Java

    Compound Assignment Operator in Java. In Java, assignment operator is used to assign values to a variable. In this section, we will discuss the compound assignment operators in Java.. Compound Assignment Operator. The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator.

  3. Java Compound Operators

    Compound Assignment Operators. An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. The simplest is the "=" assignment operator: int x = 5; This statement declares a new variable x, assigns x the value of 5 and returns 5. Compound Assignment Operators are a shorter ...

  4. What Is a Compound-Assignment Operator?

    Compound-Assignment Operators in Java. Java supports 11 compound-assignment operators: += assigns the result of the addition. -= assigns the result of the subtraction. *= assigns the result of the multiplication. /= assigns the result of the division. %= assigns the remainder of the division. &= assigns the result of the logical AND.

  5. Compound Assignment Operators in Java (With Examples)

    Compound assignment operators of Java are particularly useful when you want to modify a variable's value by a specific amount or using a specific operation. Suggested Java Concepts:-Java Constants Operators in Java. Java Arithmetic Operators. Bitwise Operators in Java.

  6. Java Compound Assignment Operators

    This operator can be used to connect Arithmetic operator with an Assignment operator. For example, you write a statement: a = a+6; In Java, you can also write the above statement like this: a += 6; There are various compound assignment operators used in Java:

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

    You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1. The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

  8. 1.5. Compound Assignment Operators

    Compound Assignment Operators — CS Java. 1.5. Compound Assignment Operators. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below.

  9. Compound assignment operators in Java\n

    Compound assignment operators in Javan - The Assignment OperatorsFollowing are the assignment operators supported by Java language −OperatorDescriptionExample=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 ope.

  10. PDF Compound assignment operators

    The compound operators are different in two ways, which we see by looking more precisely at their definition. The Java language specification says that: The compound assignment E1 op= E2 is equivalent to [i.e. is syntactic sugar for] E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once. E1 is evaluated once.

  11. Java Assignment Operators with Examples

    The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a. 7 min read. Array Variable Assignment in Java. An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable.

  12. Java Compound Assignment Operators

    Learn about the Java Compound Assignment Operators. They are basically shorthand or shortcut operators for performing arithmetic and assigning a variable at ...

  13. What are Compound Assignment Operators in Java and Why You Should Use

    Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand. Compound Assignment Operator using Addition

  14. Java

    In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i=i+ (2*2), which results in i=i+4, and finally it returns 6 to i. All compound assignment operators perform ...

  15. Operators in Java (Examples and Practice)

    Assignment Operators. Assignment operators help you set or change the value of a variable. Think of them as shortcuts for common operations. The basic assignment operator is =. For example: int length = 15; This sets the value of length to 15. But there are also compound assignment operators that combine an operation with assignment: +=: Add ...

  16. Java Compound Operators

    Compound operators, also called combined assignment operators, are a shorthand way to update the value of a variableThey are+= (addition)-= (subtraction)*= (...

  17. Difference between Simple and Compound Assignment in Java

    The compound assignment operators are +=, -=, *=, /=, %= etc. The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment, E1 = (T) ((E1) op (E2)), where T is the type of E1. In other words, compound assignment expressions automatically cast the result of the computation they perform to the ...

  18. java compound assignment operator and assignment operator

    I have some problem understanding the compound assignment operator and the assignment operator in java. Can someone explain to me how these two operators really works? (Somwhere I found a really good example code using temporary variables to explain the working but sadly I've lost it.) Thank you very much in advantage.

  19. compound assignment operator in java

    In Java, you can replace a += b with a = a + b.And that is very important.. Hence your expression is equivalent to. a = a + (a = a + b) + c. Note that this will be evaluated as a = Term1 + Term2 + Term3 and in the order left to right.. Term1 is 2.. Term2 is the only tricky one. It is 5 (and has the side-effect of increasing a to 5 but that gets clobbered by the eventual assignment).

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

  21. Why don't Java's +=, -=, *=, /= compound assignment operators require

    In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign: byte -> short -> int -> long -> float -> double. The same will not work the other way round.

  22. Why doesn't Java have compound assignment versions of the conditional

    Largely because Java syntax is based on C (or at least the C family), and in C all those assignment operators get compiled to arithmetic or bitwise assembly instructions on a single register. The assignment-operator version avoids temporaries and may have produced more efficient code on early non-optimising compilers.

  23. Order of operations for compound assignment operators in Java

    The tricks here: k += captures the value of k before doing the calculation. += is called a compound assignment operator. Quoting the relevant part of the JLS: the value of the left-hand operand is saved and then the right-hand operand is evaluated. k = 4 returns the assigned value, so 4. edited Nov 17, 2015 at 15:44.

  24. c

    According to Microsoft, "However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation". Here is what I am expecting some kind of ...