This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators

  • 8 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator Meaning
Store the value of the second operand in the object specified by the first operand (simple assignment).
Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand.
Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand.
Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand.
Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand.

Operator keywords

Three of the compound assignment operators have keyword equivalents. They are:

Operator Equivalent

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

The built-in e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type, or it must be a constant expression that evaluates to 0. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of built-in assignment operators

The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

Was this page helpful?

Additional resources

Java Compound Operators

Last updated: March 17, 2024

compound assignment operators modulus

  • Java Operators

announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide :

Download the eBook

Handling concurrency in an application can be a tricky process with many potential pitfalls . A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Download the E-book

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

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, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

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.

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

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

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

Let's get started with a Microservice Architecture with Spring Cloud:

Download the Guide

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

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?

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

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

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 .

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.

>>Download the E-book

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

>> CHECK OUT THE COURSE

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints . Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

RWS Course Banner

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

How Does the Compound Modulo Work in C++?

I have been trying to create simple program which divides an input number into peso bills. The output I need is

and this was my initial code:

but the output I get is

so after a bit of tinkering I used this block of code which worked wonders!

So my question is, how why did using the compound modulo operator work? How is it different from the regular modulo operator? I don't think the math is the problem but the way the code is handled. This is my first few weeks of learning C++ (and programming in general) and it would be nice to clear up some of my confusion. Thank you in advance.

  • compound-assignment

jfelix-agda's user avatar

  • 2 LIke with any other compound assignment operator, it assigns the result of the operation to the left side in the equation. –  πάντα ῥεῖ Commented Oct 27, 2020 at 6:33

Here is a small program to illustrate the difference:

This outputs (fixed spaces to be nicer):

As you can see in the first part, the regular modulo operator leaves i at the original value. This means that we get 256 modulo 100, 12 and 3.

However, in the second part the compound modulo operator keeps changing i , so that the next modulo only operates on the remainder.

Frodyne'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 c++ operators compound-assignment or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • How am I supposed to solder this tiny component with pads UNDER it?
  • Alice splits the bill not too generously with Bob
  • When did St Peter receive the Keys of Heaven?
  • Project poles to ground from a sampled curve
  • A function to convert numbers from scientific notation to plain decimal
  • Why does fdisk create a 512B partition when I enter +256K?
  • Is the forced detention of adult students by private universities legal?
  • Example of a forcing notion with finite-predecessor condition that does not add reals
  • Why is 'это' neuter in this expression?
  • Why is Germany looking to import workers from Kenya, specifically?
  • For a fixed angle of attack, can increasing your speed cause a stall?
  • Is this a scammer or not
  • Is there an alternate default cursor up movement key in Vim normal mode?
  • Was the total glaciation of the world, a.k.a. snowball earth, due to Bok space clouds?
  • How can I assign a heredoc to a variable in a way that's portable across Unix and Mac?
  • How to translate the letter Q to Japanese?
  • Need help in tikzpicture
  • Is there a "hard problem of aesthetics?"
  • Text in item doesn't align properly after math mode in enumitem
  • how do I fix \operatorname adding a space on the left
  • Emergency belt repair
  • Understanding “Your true airspeed will be the same, but your airspeed as opposed to the ground is much faster.” Bhutan Paro International Airport PBH
  • Hungarian Immigration wrote a code on my passport
  • What are some limitations of this learning method?

compound assignment operators modulus

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

  • 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

Compound Assignment Operators

Operator Description Example Equivalent to
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Java, C++, C#

Visual basic.

Operator Description Example Equivalent to
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
\= Integer division assignment
^= Exponentiation assignment
Operator Description Example Equivalent to
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
//= Integer division assignment
%= Modulus Assignment
^= Exponentiation assignment

Looking at the “Equivalent to” column, it becomes clear that same result can be achieved by just using the classic assignment ( = ) operator. So the question that arises here is why do these operators exist?

The answer is simple: It’s a matter of convenience. Once you start using them, your life finds a different meaning!

Notice : Please keep in mind that flowcharts are a loose method to represent an algorithm. Although the use of compound assignment operators is allowed in flowcharts, this website uses only the commonly accepted operators shown in the “Equivalent to” column. For example, the Java statement a += b is represented in a flowchart as

Related articles:

  • The Value Assignment Operator
  • Arithmetic Operators
  • What is the Precedence of Arithmetic Operators?
  • Incrementing/Decrementing Operators

compound assignment operators modulus

  • 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 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 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 Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Method Signatures (preview 2026 curriculum)
  • 1.13 Calling Class Methods (preview 2026 curriculum)
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Time estimate: 45 min.

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 the current value of x and assigns the result back 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. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.

Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!

Operator

Written out

= x + 1

= x - 1

= x * 2

= x / 2

= x % 2

Compound

+= 1

-= 1

*= 2

/= 2

%= 2

Extra concise

Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.

If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.

Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.

In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.

But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.

The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

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 = 0, y = 1, 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 ¶

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.

Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand 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.

../_images/traceTable.png

Trace through the following code:

1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.

After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!

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

The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.

Matthew, more or less

Matthew J. Clemente

What is the Modulus Operator? A Short Guide with Practical Use Cases

Addition, subtraction, multiplication, and division. These are the four mathematical operations I was taught during my childhood education, and their operators, + , - , * , / , are very familiar. I was not taught % , the modulus operator , which I recently discovered can be quite useful and interesting in its own right.

The modulus operator, written in most programming languages as % or mod , performs what is known as the modulo operation . You next response, understandably, might be, "That doesn't clarify anything," so let's take a closer look:

How It Works

The modulus operator - or more precisely, the modulo operation - is a way to determine the remainder of a division operation. Instead of returning the result of the division, the modulo operation returns the whole number remainder.

Some examples may help illustrate this, as it's not necessarily intuitive the first time you encounter it:

It may be helpful to think back to your early math lessons, before you learned fractions and decimals. Mathematics with whole numbers behaves differently - when dividing numbers that aren't even multiples, there's always some amount left over. That remainder is what the modulo operation returns.

If this seems strange, boring, or not particularly useful, bear with me a bit longer - or just skip ahead to the use cases .

The Modulo Operation Expressed As a Formula

As one final means of explication, for those more mathematically inclined, here's a formula that describes the modulo operation:

By substituting values, we can see how the modulo operation works in practice:

If you don't find the formula helpful, don't worry - I didn't either at first. Some people find this abstract representation helps deepen or clarify their understanding of the operation, but you don't need to know it.

A final note here - if you're wondering how the modulo operation functions with negative numbers or decimals, that's a bit outside the scope of this article. For our purposes here, we'll only be dealing with positive integers. [1]

Okay, enough with the math for now. While returning the remainder is what the modulo operation does, that's not its only use; indeed we'll see that it's handy for a good deal more - but that was a necessary starting point.

Use Cases for the Modulo Operation

When I first encountered the it, the modulus operator seemed little more than a bit of mathematical trivia. I found it far more interesting as I started to learn its practical utility. I'll discuss a few applications here.

Even / Odd and Alternating

One of the most basic use cases for the modulus operator is to determine if a number is even or odd. [2] This is possible because x % 2 always returns either 0 or 1. Even numbers, because they are evenly divisible by 2, always return 0, while odd numbers always return the remainder of 1. Here's what I mean:

So, what's the use case? This technique is often used to alternate values within a loop. The first time I used the modulus operator, it was to manually zebra-stripe table rows, with the row's background color based on whether it was even or odd. In a similar vein, I've used % to distribute the results of a web-form to two recipients, on an every-other basis; in pseudocode:

It's a convenient hack any time you have a group or stream of records, widgets, leads, etc., that you want to handle on an alternating basis.

Restrict Number to Range

When you're using the modulus operator for even/odd alternation, you're actually taking advantage of one of its more helpful properties, though you might not realize it. Here's the property: the range of x % n is between 0 and n - 1 , which is to say that the modulo operation will not return more than the divisor . [3]

Again, examples might help clarify this idea; in each instance here, the divisor is 5, so results will range from 0 - 4.

As you can see, regardless of the initial number, the modulus (divisor) limits the range of the result.

On its own, this property doesn't seem useful, but when applied within a larger set, it can be used to create a pattern of circular repetition. Here's an example of incrementing numbers with a modulus of 3:

Notice how the result of the modulo operation keeps repeating 0-1-2; the values wrap around. One way to describe these results is as a circular array , like numbers on the face of a clock. Let's take a closer look at a practical application of this property.

Rotating Through Limited Options (Circular Array)

In a situation with a limited number of options - weekdays, primary colors, company projects, clients, etc. - we can use the modulo operation to walk through them in a repeating loop. That is, we can treat the array of options as a circle that we just keep cycling through.

Here's a somewhat contrived example to illustrate this:

As we step through a list of employees, we assign each to a weekday. Once we've scheduled five employees, we reach Friday. With no more options, assignment then loops back to Monday and continues the cycle until all employees are scheduled. This is possible because, as shown in the previous section, the modulus of 5 (the number of weekdays) returns a circular array of 0-4, that we can map to options in our weekday array. Seeing and understanding this was a major revelation for me.

Every Nth Operations in a Loop

Another application of the modulo operation is determining an interval within a loop; that is, calculating occurrences such as "every fourth time," "once every ten," etc.

The principle, in this case, is that if n is an even multiple of x , then x % n = 0 . Consequently, x % 4 will return 0 every fourth time; x % 10 will return 0 every tenth time, and so on. One practical use of this is providing feedback within long or long running loops:

You could use a similar principle to trigger client/user interaction based on time or engagement. For example, send a promo every 90 days, or offer a feedback survey every 50 logins.

Keep in mind that time is also, in effect, a long running loop. Every hour has 60 minutes, repeating on a cycle. If you wanted to schedule a task to run four times an hour, you could achieve this using the modulo operation - just run it when minutes % 4 == 0 .

Converting Units of Measure

Converting units of measure is common example of the modulo operation's practical utility. The general use case is when you want to convert a smaller unit, such as minutes or inches/centimeters, to a larger unit, like hours or miles/kilometers; in these situations, decimals or fractions aren't always helpful.

For example, if we wanted to know the number of hours in 349 minutes, having the result expressed as 5 hours 49 minutes may be more helpful than 5.8167 hours . Here's a quick-and-dirty take at what that type of conversion function might look like:

Standard division (rounded down to the nearest integer) determines the number of hours, while the modulo operation is used to keep track of the remaining minutes. Whether you're dealing with time, distance, pressure, energy, or data storage, you can use this general approach for unit conversion.

You might think that I've exhausted all the situations in which you might use the modulus operator, but you'd be wrong. Here are a handful more that I found on Stack Overflow, Quora, and the internet at large:

  • Reversing a number
  • Converting linear data to a matrix
  • Determining if arrays are rotated versions of each other
  • Leap year calculation

Additionally, once you're comfortable with the modulo operation, you shouldn't have any trouble solving the FizzBuzz Question discussed here.

Some Helpful Reading

Credit where it's due - I learned a lot from these posts while I was researching and writing this article:

  • The Modulo Operator in Java
  • How to Use the Modulo Operator in PHP
  • Fun With Modular Arithmetic
  • Recognizing when to use the modulus operator (Stack Overflow)
  • In which cases is the Modulo (%) operation used in programming? (Quora)

Now you know it; go use it! If you've got other uses or examples that you'd like to share, I'd love to hear them.

Programming languages vary in their approach to supporting and handing floating point (decimal) modulo operations, as well as negative numbers. Working with these is outside the scope of this article, my concern, and most practical use cases that I've read about or encountered. ↩︎

Lest I get called out in the comments, I should note that bitwise operators offer another, even more efficient approach to determining if a number is even or odd, but that's another topic for another day. ↩︎

I should note that the divisor in a modulo operation is also called the modulus. ↩︎

Search powered by Algolia

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

cppreference.com

C operator precedence.

(C11)
Miscellaneous
General
(C11)
(C99)

The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence.

Precedence Operator Description Associativity
1 Suffix/postfix increment and decrement Left-to-right
Function call
Array subscripting
Structure and union member access
Structure and union member access through pointer
){ } Compound literal(C99)
2 Prefix increment and decrement Right-to-left
Unary plus and minus
Logical NOT and bitwise NOT
) Cast
Indirection (dereference)
Address-of
Size-of
Alignment requirement(C11)
3 Multiplication, division, and remainder Left-to-right
4 Addition and subtraction
5 Bitwise left shift and right shift
6 For relational operators < and ≤ respectively
For relational operators > and ≥ respectively
7 For relational = and ≠ respectively
8 Bitwise AND
9 Bitwise XOR (exclusive or)
10 Bitwise OR (inclusive or)
11 Logical AND
12 Logical OR
13 Ternary conditional Right-to-left
14 Simple assignment
Assignment by sum and difference
Assignment by product, quotient, and remainder
Assignment by bitwise left shift and right shift
Assignment by bitwise AND, XOR, and OR
15 Comma Left-to-right
  • ↑ The operand of prefix ++ and -- can't be a type cast. This rule grammatically forbids some expressions that would be semantically invalid anyway. Some compilers ignore this rule and detect the invalidity semantically.
  • ↑ The operand of sizeof can't be a type cast: the expression sizeof ( int ) * p is unambiguously interpreted as ( sizeof ( int ) ) * p , but not sizeof ( ( int ) * p ) .
  • ↑ The expression in the middle of the conditional operator (between ? and : ) is parsed as if parenthesized: its precedence relative to ?: is ignored.
  • ↑ Assignment operators' left operands must be unary (level-2 non-cast) expressions. This rule grammatically forbids some expressions that would be semantically invalid anyway. Many compilers ignore this rule and detect the invalidity semantically. For example, e = a < d ? a ++ : a = d is an expression that cannot be parsed because of this rule. However, many compilers ignore this rule and parse it as e = ( ( ( a < d ) ? ( a ++ ) : a ) = d ) , and then give an error because it is semantically invalid.

When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expression * p ++ is parsed as * ( p ++ ) , and not as ( * p ) ++ .

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression a = b = c is parsed as a = ( b = c ) , and not as ( a = b ) = c because of right-to-left associativity.

[ edit ] Notes

Precedence and associativity are independent from order of evaluation .

The standard itself doesn't specify precedence levels. They are derived from the grammar.

In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands.

Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left ( sizeof ++* p is sizeof ( ++ ( * p ) ) ) and unary postfix operators always associate left-to-right ( a [ 1 ] [ 2 ] ++ is ( ( a [ 1 ] ) [ 2 ] ) ++ ). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: a. b ++ is parsed ( a. b ) ++ and not a. ( b ++ ) .

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • A.2.1 Expressions
  • C11 standard (ISO/IEC 9899:2011):
  • C99 standard (ISO/IEC 9899:1999):
  • C89/C90 standard (ISO/IEC 9899:1990):
  • A.1.2.1 Expressions

[ edit ] See also

Order of evaluation of operator arguments at run time.

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b

a[b]
*a
&a
a->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

for C++ operator precedence
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 31 July 2023, at 10:28.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • 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

Java Assignment Operators with Examples

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

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

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

Similar reads.

  • Java-Operators
  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

compound assignment operators modulus

  • Introduction to Python
  • Download and Install Python
  • The First Python Program in IDLE
  • Data Types in Python
  • Python Keywords and Identifiers
  • Python Variables and Constants
  • Python If Statement
  • Python If Else Statement
  • Python Elif Statement
  • Python Nested If Statement
  • Python Nested If Else Statement
  • Python While Loop
  • Python For Loop
  • Python Break Statement
  • Python Arithmetic Operators
  • Python Compound Assignment Operators
  • Python Relational Operators
  • Python Logical Operators
  • Python Conditional Operator
  • Python Classes
  • Python Constructors
  • Python Static Variable
  • Python Static Method
  • Python Class Method
  • Python Inheritance
  • Python Super() Function
  • Python Method Overriding
  • Python Polymorphism
  • Python Garbage Collection
  • Python Array from Array Module
  • Python Array from Numpy Module
  • Python two-dimensional Array
  • Python Exception Handling
  • Python Exception Propagation
  • Python Try, Except Block
  • Python Multiple Except Block
  • Python Try, Except, Else Block
  • Python Finally Block
  • Python Raise Keyword
  • Python User-Defined Exception
  • Python Functions
  • Python Functions with Arguments
  • Python Functions with Default Arguments
  • Python Recursive Function
  • Python Local Variables
  • Python Global Variables
  • Python Tuple
  • Python List
  • Python Dictionary
  • Python - String
  • Python - String Methods
  • Python - String capitalize() Method
  • Python - String upper() Method
  • Python - String isupper() Method
  • Python - String casefold() Method
  • Python - String lower() Method
  • Python - String islower() Method
  • Python - String swapcase() Method
  • Python - String title() Method
  • Python - String istitle() Method
  • Python - String strip() Method
  • Python - String lstrip() Method
  • Python - String rstrip() Method
  • Python - String isnumeric() Method
  • Python - String isdigit() Method
  • Python - String isalpha() Method
  • Python - String isalnum() Method
  • Python - String isdecimal() Method
  • Python - String isidentifier() Method
  • Python - String isprintable() Method
  • Python - String startswith() Method
  • Python - String endswith() Method
  • Python - String index() Method
  • Python - String find() Method
  • Python - String rfind() Method
  • Python - String rindex() Method
  • Python - String center() Method
  • Python - String rjust() Method
  • Python - String ljust() Method
  • Python - String replace() Method
  • Python - String count() Method
  • Python - String split() Method
  • Python - String rsplit() Method
  • Python - String splitlines() Method
  • Python - String partition() Method
  • Python - String rpartition() Method
  • Python - String zfill() Method
  • Python - String Formatting
  • Python - Input/Output Functions
  • Python - File and File Modes
  • Python - Read a File
  • Python - Write a File
  • Python - Append to a File
  • Python - Modify a File

Advertisement

+= operator

  • First, an add operation.
  • Next, the assignment of the result of an add operation.
  • 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

Example with += operator, -= operator.

  • Subtraction operation.
  • Assignment of the result of a 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 a 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.

  • floating-point division operation.
  • Assignment of the result of floating-point 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.0
  • Finally, the result of division i.e. 2.0 is assigned back to i, updating its value from 4 to 2.0.

Example with /= operator

//= operator.

  • Integer division operation, which gives us an integer quotient value after dividing two integers and it gives a floating-point quotient after dividing a floating-point number with an integer value or vice versa.
  • Assignment of the result of an integer 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

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

ReSharper 2024.2 Help

Code inspection: use compound assignment.

Category : Language Usage Opportunities

ID : ConvertToNullCoalescingCompoundAssignment

EditorConfig : resharper_convert_to_null_coalescing_compound_assignment_highlighting=[error|warning|suggestion|hint|none]

Default severity : Suggestion

Language : C#

Requires SWA : No

This inspection suggests using a compound assignment expression to make the code more concise and easier to read. Compound assignments are shorthand ways of combining arithmetic, boolean, bitwise, and other binary operators with the assignment operator = . They can help reduce repetitive code and make the intent of the code clearer.

The most commonly used compound assignment expression is probably the addition assignment ( x += y ), but there are other compound assignments that can come in handy. Here are some examples:

IMAGES

  1. 025 Compound assignment operators (Welcome to the course C programming)

    compound assignment operators modulus

  2. PPT

    compound assignment operators modulus

  3. Compound Assignment Operators

    compound assignment operators modulus

  4. PPT

    compound assignment operators modulus

  5. PPT

    compound assignment operators modulus

  6. PPT

    compound assignment operators modulus

VIDEO

  1. Java Compound Assignment Operators

  2. Day 10: Assignment and Compound Operators in Python Programming

  3. Compound Assignment Operators in C++ || C++ Programming #viral #subscribe

  4. 1.5 Compound Assignment Operators

  5. C++ Basics: Operators

  6. Compound Assignment Operators in C language

COMMENTS

  1. Assignment Operators In C++

    Compound Assignment Operators. In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. ... The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and ...

  2. Assignment operators

    The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

  3. Java Compound Operators

    Like the "=" assignment operator, compound operators return the assigned result of the expression: long x = 1; long y = (x+= 2); Copy. 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.

  4. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs. Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  5. Assignment Operators in Python

    The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand. ... The += and -= operators in Python are compound assignment operators. += adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand ...

  6. operators

    i: 8, i %= 3: 2. As you can see in the first part, the regular modulo operator leaves at the original value. This means that we get 256 modulo 100, 12 and 3. However, in the second part the compound modulo operator keeps changing , so that the next modulo only operates on the remainder.

  7. Compound Assignment Operators in Java (With Examples)

    Learn Java compound assignment operators with practical examples. Elevate coding skills effectively. ... Modulus and Assignment (%=) This operator calculates the remainder of the division of the left-hand operand by the right-hand operand and assigns the result back to the left-hand operand. Example: int e = 17; e %= 5; // e = e % 5; // Now 'e ...

  8. Assignment Operators in C

    Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A <<= ... C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining ...

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

  10. Compound Assignment Operators in C++

    The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −. The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ −. Multiply the value of the first operand by the ...

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

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

  13. Compound Assignment Operators

    Compound Assignment Operators. Many modern computer languages offers a special set of operators known as compound assignment operators, which can help you write code faster. Looking at the "Equivalent to" column, it becomes clear that same result can be achieved by just using the classic assignment ( = ) operator.

  14. 1.5. Compound Assignment Operators

    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 the current value of x and assigns the result back 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. If you need a mnemonic to remember whether the compound ...

  15. What is the Modulus Operator? A Short Guide with Practical Use Cases

    The modulus operator - or more precisely, the modulo operation - is a way to determine the remainder of a division operation. Instead of returning the result of the division, the modulo operation returns the whole number remainder. ... Older TIL: Compound Assignment Operators in... Newer Adobe ColdFusion Summit 2019. No data found for the given ...

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

  17. Assignment, Arithmetic, and Unary Operators

    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:

  18. C# Compound Assignment Operator

    Solution 1: In C#, compound assignment operators are used to perform an arithmetic operation on a variable and then assign the result back to the same variable in a single statement. This can help to make code more concise and readable. Here are some examples of compound assignment operators in C#: 1. Addition assignment operator (+=): csharp.

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

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

  20. C Operator Precedence

    They are derived from the grammar. In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands. Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always ...

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

  22. Python

    A special case scenario for all the compound assigned operators. i= 2; i+= 2 * 2; #equals to, i = i+(2*2); 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* ...

  23. Code inspection: Use compound assignment

    Compound assignments are shorthand ways of combining arithmetic, boolean, bitwise, and other binary operators with the assignment operator =. They can help reduce repetitive code and make the intent of the code clearer. The most commonly used compound assignment expression is probably the addition assignment ( x += y ), but there are other ...