Java Compound Operators

Last updated: March 17, 2024

compound assignment operators modulus

  • Java Operators

announcement - icon

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$

>> GET ACCESS NOW

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

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

>> LEARN SPRING

Building a REST API with 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

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

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.

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

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

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

Get started with Spring Boot and with core Spring, through the Learn Spring 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 .

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

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

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

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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.

The final value for x is

The final value for y is

The final value for z is

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.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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. –  πάντα ῥεῖ 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 .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • How might a physicist define 'mind' using concepts of physics?
  • Why do we say "he doesn't know him from Adam"?
  • Movie I saw in the 80s where a substance oozed off of movie stairs leaving a wet cat behind
  • TeX capacity exceeded, sorry [grouping levels=255] while using enumerate
  • Power series representation of 1/(2+x)
  • A man is kidnapped by his future descendants and isolated his whole life to prevent a bad thing; they accidentally undo their own births
  • `getTokenAccountsByDelegate` Method Not Available After Clean Install of `@solana/web3.js`
  • Has ever a country by its own volition refused to join United Nations, or those which havent joined it's because they aren't recognized as such by UN?
  • Why does setting `umask` to `0077` (and then downloading public key) makes a gpg public key unavailable for apt?
  • A Fantasy story where a man appears to have been crushed on his wedding night by a statue on the finger of which he has put a wedding ring
  • An application of the (100/e)% rule applied to postdocs: moving on from an academic career, perhaps
  • A question about syntactic function of the clause
  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
  • Sum of square roots (as an algebraic number)
  • Is 1.5 hours enough for flight transfer in Frankfurt?
  • Why is killing even evil brahmins categorized as 'brahma hatya'?
  • Who are the mathematicians interested in the history of mathematics?
  • Should the increasing energy retained in the atmosphere be considered in relation to global warming?
  • What is the difference in meaning between the two sentences?
  • How to use ogr2ogr -segmentize on a CSV file?
  • Regarding upper numbering of ramification groups
  • Why "Power & battery" stuck at spinning circle for 4 hours?
  • Which program is used in this shot of the movie "The Wrong Woman"
  • Dispute cancellation fees by 3rd-party airline booking

compound assignment operators modulus

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block

    

/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)      

expression
pointer
specifier

specifier (C++11)    
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++26)

(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

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
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • 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 25 January 2024, at 23:41.
  • This page has been accessed 428,577 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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.

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • If Statement in C
  • Understanding do...while loop in C
  • Understanding for loop in C
  • if else if statements in C Programming
  • If...else statement in C Programming
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Beginner's Guide to C Programming
  • First C program and Its Syntax
  • Escape Sequences and Comments in C
  • Keywords in C: List of Keywords
  • Identifiers in C: Types of Identifiers
  • Data Types in C Programming - A Beginner Guide with examples
  • Variables in C Programming - Types of Variables in C ( With Examples )
  • 10 Reasons Why You Should Learn C
  • Boolean and Static in C Programming With Examples ( Full Guide )
  • Operators in C: Types of Operators
  • Bitwise Operators in C: AND, OR, XOR, Shift & Complement
  • Expressions in C Programming - Types of Expressions in C ( With Examples )
  • Conditional Statements in C: if, if..else, Nested if
  • Switch Statement in C: Syntax and Examples
  • Ternary Operator in C: Ternary Operator vs. if...else Statement
  • Loop in C with Examples: For, While, Do..While Loops
  • Nested Loops in C - Types of Expressions in C ( With Examples )
  • Infinite Loops in C: Types of Infinite Loops
  • Jump Statements in C: break, continue, goto, return
  • Continue Statement in C: What is Break & Continue Statement in C with Example

03 Intermediate

  • Constants in C language
  • Getting Started with Data Structures in C
  • Functions in C Programming
  • Call by Value and Call by Reference in C
  • Recursion in C: Types, its Working and Examples
  • Storage Classes in C: Auto, Extern, Static, Register
  • Arrays in C Programming: Operations on Arrays
  • Strings in C with Examples: String Functions

04 Advanced

  • How to Dynamically Allocate Memory using calloc() in C?
  • How to Dynamically Allocate Memory using malloc() in C?
  • Pointers in C: Types of Pointers
  • Multidimensional Arrays in C: 2D and 3D Arrays
  • Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • C Programming Course
  • Data Structures and Algorithms Training
  • C Programming Assignment ..

C Programming Assignment Operators

C Programming Assignment Operators

compound assignment operators modulus

C Programming For Beginners Free Course

What is an assignment operator in c.

Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". The value on the right side must be of the same data type as the variable on the left side. Hence, the associativity is from right to left.

In this C tutorial , we'll understand the types of C programming assignment operators with examples. To delve deeper you can enroll in our C Programming Course .

Before going in-depth about assignment operators you must know about operators in C. If you haven't visited the Operators in C tutorial, refer to Operators in C: Types of Operators .

Types of Assignment Operators in C

There are two types of assignment operators in C:

Types of Assignment Operators in C
+=addition assignmentIt adds the right operand to the left operand and assigns the result to the left operand.
-=subtraction assignmentIt subtracts the right operand from the left operand and assigns the result to the left operand.
*=multiplication assignmentIt multiplies the right operand with the left operand and assigns the result to the left operand
/=division assignmentIt divides the left operand with the right operand and assigns the result to the left operand.
%=modulo assignmentIt takes modulus using two operands and assigns the result to the left operand.

Example of Augmented Arithmetic and Assignment Operators

There can be five combinations of bitwise operators with the assignment operator, "=". Let's look at them one by one.

&=bitwise AND assignmentIt performs the bitwise AND operation on the variable with the value on the right
|=bitwise OR assignmentIt performs the bitwise OR operation on the variable with the value on the right
^=bitwise XOR assignmentIt performs the bitwise XOR operation on the variable with the value on the right
<<=bitwise left shift assignmentShifts the bits of the variable to the left by the value on the right
>>=bitwise right shift assignmentShifts the bits of the variable to the right by the value on the right

Example of Augmented Bitwise and Assignment Operators

Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code.

The correct answer is 52. x starts at 50, increases by 5 to 55, then decreases by 3 to 52.

2. After executing the following code, what is the value of the number variable?

The correct answer is 144. After right-shifting 73 (binary 1001001) by one and then left-shifting the result by two, the value becomes 144 (binary 10010000).

Benefits of Using Assignment Operators

  • Simplifies Code: For example, x += 1 is shorter and clearer than x = x + 1.
  • Reduces Errors: They break complex expressions into simpler, more manageable parts thus reducing errors.
  • Improves Readability: They make the code easier to read and understand by succinctly expressing common operations.
  • Enhances Performance: They often operate in place, potentially reducing the need for additional memory or temporary variables.

Best Practices and Tips for Using the Assignment Operator

While performing arithmetic operations with the same variable, use compound assignment operators

  • Initialize Variables When Declaring int count = 0 ; // Initialization
  • Avoid Complex Expressions in Assignments a = (b + c) * (d - e); // Consider breaking it down: int temp = b + c; a = temp * (d - e);
  • Avoid Multiple Assignments in a Single Statement // Instead of this a = b = c = 0 ; // Do this a = 0 ; b = 0 ; c = 0 ;
  • Consistent Formatting int result = 0 ; result += 10 ;

When mixing assignments with other operations, use parentheses to ensure the correct order of evaluation.

Live Classes Schedule

ASP.NET Core Certification Training Jun 14 MON, WED, FRI Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jun 14 MON, WED, FRI Filling Fast
Angular Certification Course Jun 16 SAT, SUN Filling Fast
ASP.NET Core (Project) Jun 23 SAT, SUN Filling Fast
Azure Developer Certification Training Jun 23 SAT, SUN Filling Fast
Generative AI For Software Developers Jun 23 SAT, SUN Filling Fast
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN Filling Fast

Can't find convenient schedule? Let us know

About Author

Author image

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

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

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

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

This browser is no longer supported.

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

about_Assignment_Operators

  • 2 contributors

Short description

Describes how to use operators to assign values to variables.

Long description

Assignment operators assign one or more values to a variable. The equals sign ( = ) is the PowerShell assignment operator. PowerShell also has the following compound assignment operators: += , -= , *= , %= , ++ , -- , ??= . Compound assignment operators perform operations on the values before the assignment.

The syntax of the assignment operators is as follows:

  • <assignable-expression> <assignment-operator> <value>

Assignable expressions include variables and properties. The value can be a single value, an array of values, or a command, expression, or statement.

The increment and decrement operators are unary operators. Each has prefix and postfix versions.

  • <assignable-expression><operator>
  • <operator><assignable-expression>

The value of the assignable expression must be a number or it must be convertible to a number.

Using the assignment operator

Variables are named memory spaces that store values. You store the values in variables using the assignment operator = . The new value can replace the existing value of the variable, or you can append a new value to the existing value. For example, the following statement assigns the value PowerShell to the $MyShell variable:

When you assign a value to a variable in PowerShell, the variable is created if it didn't already exist. For example, the first of the following two assignment statements creates the $a variable and assigns a value of 6 to $a . The second assignment statement assigns a value of 12 to $a . The first statement creates a new variable. The second statement changes only its value:

Variables in PowerShell don't have a specific data type unless you cast them. When a variable contains only one object, the variable takes the data type of that object. When a variable contains a collection of objects, the variable has the System.Object data type. Therefore, you can assign any type of object to the collection. The following example shows that you can add process objects, service objects, strings, and integers to a variable without generating an error:

Because the assignment operator = has a lower precedence than the pipeline operator | , parentheses aren't required to assign the result of a command pipeline to a variable. For example, the following command sorts the services on the computer and then assigns the sorted services to the $a variable:

You can also assign the value created by a statement to a variable, as in the following example:

This example assigns zero to the $a variable if the value of $b is less than zero. It assigns the value of $b to $a if the value of $b isn't less than zero.

To assign an array (multiple values) to a variable, separate the values with commas, as follows:

To assign a hash table to a variable, use the standard hash table notation in PowerShell. Type an at sign @ followed by key/value pairs that are separated by semicolons ; and enclosed in braces { } . For example, to assign a hashtable to the $a variable, type:

To assign hexadecimal values to a variable, precede the value with 0x . PowerShell converts the hexadecimal value (0x10) to a decimal value (in this case, 16) and assigns that value to the $a variable. For example, to assign a value of 0x10 to the $a variable, type:

To assign an exponential value to a variable, type the root number, the letter e , and a number that represents a multiple of 10. For example, to assign a value of 3.1415 to the power of 1,000 to the $a variable, type:

PowerShell can also convert kilobytes KB , megabytes MB , and gigabytes GB into bytes. For example, to assign a value of 10 kilobytes to the $a variable, type:

Using compound assignment operators

Compound assignment operators perform numeric operations on the values before the assignment.

Compound assignment operators don't use dynamic scoping. The variable is always in the current scope.

In the following example, the variable $x is defined in the global scope. The braces create a new scope. The variable $x inside the braces is a new instance and not a copy of the global variable.

When you use the regular assignment operator, you get a copy of the variable from the parent scope. But notice that $x in the parent scope is not changed.

The assignment by addition operator

The assignment by addition operator += either increments the value of a variable or appends the specified value to the existing value. The action depends on whether the variable has a numeric or string type and whether the variable contains a single value (a scalar) or multiple values (a collection).

The += operator combines two operations. First, it adds, and then it assigns. Therefore, the following statements are equivalent:

When the variable contains a single numeric value, the += operator increments the existing value by the amount on the right side of the operator. Then, the operator assigns the resulting value to the variable. The following example shows how to use the += operator to increase the value of a variable:

When the value of the variable is a string, the value on the right side of the operator is appended to the string, as follows:

When the value of the variable is an array, the += operator appends the values on the right side of the operator to the array. Unless the array is explicitly typed by casting, you can append any type of value to the array, as follows:

When the value of a variable is a hash table, the += operator appends the value on the right side of the operator to the hash table. However, because the only type that you can add to a hash table is another hash table, all other assignments fail.

For example, the following command assigns a hash table to the $a variable. Then, it uses the += operator to append another hash table to the existing hash table, effectively adding a new key-value pair to the existing hash table. This command succeeds, as shown in the output:

The following command attempts to append an integer "1" to the hash table in the $a variable. This command fails:

The assignment by subtraction operator

The assignment by subtraction operator -= decrements the value of a variable by the value that's specified on the right side of the operator. This operator can't be used with string variables, and it can't be used to remove an element from a collection.

The -= operator combines two operations. First, it subtracts, and then it assigns. Therefore, the following statements are equivalent:

The following example shows how to use of the -= operator to decrease the value of a variable:

You can also use the -= assignment operator to decrease the value of a member of a numeric array. To do this, specify the index of the array element that you want to change. In the following example, the value of the third element of an array (element 2) is decreased by 1:

You can't use the -= operator to delete the values of a variable. To delete all the values that are assigned to a variable, use the Clear-Item or Clear-Variable cmdlets to assign a value of $null or "" to the variable.

To delete a particular value from an array, use array notation to assign a value of $null to the particular item. For example, the following statement deletes the second value (index position 1) from an array:

To delete a variable, use the Remove-Variable cmdlet. This method is useful when the variable is explicitly cast to a particular data type, and you want an untyped variable. The following command deletes the $a variable:

The assignment by multiplication operator

The assignment by multiplication operator *= multiplies a numeric value or appends the specified number of copies of the string value of a variable.

When a variable contains a single numeric value, that value is multiplied by the value on the right side of the operator. For example, the following example shows how to use the *= operator to multiply the value of a variable:

In this case, the *= operator combines two operations. First, it multiplies, and then it assigns. Therefore, the following statements are equivalent:

When a variable contains a string value, PowerShell appends the specified number of strings to the value, as follows:

To multiply an element of an array, use an index to identify the element that you want to multiply. For example, the following command multiplies the first element in the array (index position 0) by 2:

The assignment by division operator

The assignment by division operator /= divides a numeric value by the value that's specified on the right side of the operator. The operator can't be used with string variables.

The /= operator combines two operations. First, it divides, and then it assigns. Therefore, the following two statements are equivalent:

For example, the following command uses the /= operator to divide the value of a variable:

To divide an element of an array, use an index to identify the element that you want to change. For example, the following command divides the second element in the array (index position 1) by 2:

The assignment by modulus operator

The assignment by modulus operator %= divides the value of a variable by the value on the right side of the operator. Then, the %= operator assigns the remainder (known as the modulus) to the variable. You can use this operator only when a variable contains a single numeric value. You can't use this operator when a variable contains a string variable or an array.

The %= operator combines two operations. First, it divides and determines the remainder, and then it assigns the remainder to the variable. Therefore, the following statements are equivalent:

The following example shows how to use the %= operator to save the modulus of a quotient:

The increment and decrement operators

The increment operator ++ increases the value of a variable by 1. When you use the increment operator in a simple statement, no value is returned. To view the result, display the value of the variable, as follows:

To force a value to be returned, enclose the variable and the operator in parentheses, as follows:

The increment operator can be placed before (prefix) or after (postfix) a variable. The prefix version of the operator increments a variable before its value is used in the statement, as follows:

The postfix version of the operator increments a variable after its value is used in the statement. In the following example, the $c and $a variables have different values because the value is assigned to $c before $a changes:

The decrement operator -- decreases the value of a variable by 1. As with the increment operator, no value is returned when you use the operator in a simple statement. Use parentheses to return a value, as follows:

The prefix version of the operator decrements a variable before its value is used in the statement, as follows:

The postfix version of the operator decrements a variable after its value is used in the statement. In the following example, the $d and $a variables have different values because the value is assigned to $d before $a changes:

Null-coalescing assignment operator

The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

For more information, see Null-coalescing operator .

Microsoft .NET types

By default, when a variable has only one value, the value that's assigned to the variable determines the data type of the variable. For example, the following command creates a variable that has the System.Int32 type:

To find the .NET type of a variable, use the GetType method and its FullName property. Be sure to include the parentheses after the GetType method name, even though the method call has no arguments:

To create a variable that contains a string, assign a string value to the variable. To indicate that the value is a string, enclose it in quotation marks, as follows:

If the first value that's assigned to the variable is a string, PowerShell treats all operations as string operations and casts new values to strings. This occurs in the following example:

If the first value is an integer, PowerShell treats all operations as integer operations and casts new values to integers. This occurs in the following example:

You can cast a new scalar variable as any .NET type by placing the type name in brackets that precede either the variable name or the first assignment value. When you cast a variable, you are defining the type of data that can be stored in the variable.

For example, the following command casts the variable as a string type:

The following example casts the first value, instead of casting the variable:

You can't recast the data type of an existing variable if its value can't be converted to the new data type.

To change the data type, you must replace its value, as follows:

In addition, when you precede a variable name with a data type, the type of that variable is locked unless you explicitly override the type by specifying another data type. If you try to assign a value that's incompatible with the existing type, and you don't explicitly override the type, PowerShell displays an error, as shown in the following example:

In PowerShell, the data types of variables that contain multiple items in an array are handled differently from the data types of variables that contain a single item. Unless a data type is specifically assigned to an array variable, the data type is always System.Object [] . This data type is specific to arrays.

Sometimes, you can override the default type by specifying another type. For example, the following command casts the variable as a string [] array type:

PowerShell variables can be any .NET data type. In addition, you can assign any fully qualified .NET data type that's available in the current process. For example, the following command specifies a System.DateTime data type:

The variable will be assigned a value that conforms to the System.DateTime data type. The value of the $a variable would be the following:

Assigning multiple variables

In PowerShell, you can assign values to multiple variables using a single command. The first element of the assignment value is assigned to the first variable, the second element is assigned to the second variable, the third element to the third variable. This is known as multiple assignment .

For example, the following command assigns the value 1 to the $a variable, the value 2 to the $b variable, and the value 3 to the $c variable:

If the assignment value contains more elements than variables, all the remaining values are assigned to the last variable. For example, the following command contains three variables and five values:

Therefore, PowerShell assigns the value 1 to the $a variable and the value 2 to the $b variable. It assigns the values 3, 4, and 5 to the $c variable. To assign the values in the $c variable to three other variables, use the following format:

This command assigns the value 3 to the $d variable, the value 4 to the $e variable, and the value 5 to the $f variable.

If the assignment value contains fewer elements than variables, the remaining variables are assigned the value $null . For example, the following command contains three variables and two values:

Therefore, PowerShell assigns the value 1 to the $a variable and the value 2 to the $b variable. The $c variable is $null .

You can also assign a single value to multiple variables by chaining the variables. For example, the following command assigns a value of "three" to all four variables:

Variable-related cmdlets

In addition to using an assignment operation to set a variable value, you can also use the Set-Variable cmdlet. For example, the following command uses Set-Variable to assign an array of 1, 2, 3 to the $a variable.

  • about_Arrays
  • about_Hash_Tables
  • about_Variables
  • Clear-Variable
  • Remove-Variable
  • Set-Variable

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Arduino Tutorial

  • Arduino Tutorial
  • Arduino - Home
  • Arduino - Overview
  • Arduino - Board Description
  • Arduino - Installation
  • Arduino - Program Structure
  • Arduino - Data Types
  • Arduino - Variables & Constants
  • Arduino - Operators
  • Arduino - Control Statements
  • Arduino - Loops
  • Arduino - Functions
  • Arduino - Strings
  • Arduino - String Object
  • Arduino - Time
  • Arduino - Arrays
  • Arduino Function Libraries
  • Arduino - I/O Functions
  • Arduino - Advanced I/O Function
  • Arduino - Character Functions
  • Arduino - Math Library
  • Arduino - Trigonometric Functions
  • Arduino Advanced
  • Arduino - Due & Zero
  • Arduino - Pulse Width Modulation
  • Arduino - Random Numbers
  • Arduino - Interrupts
  • Arduino - Communication
  • Arduino - Inter Integrated Circuit
  • Arduino - Serial Peripheral Interface
  • Arduino Projects
  • Arduino - Blinking LED
  • Arduino - Fading LED
  • Arduino - Reading Analog Voltage
  • Arduino - LED Bar Graph
  • Arduino - Keyboard Logout
  • Arduino - Keyboard Message
  • Arduino - Mouse Button Control
  • Arduino - Keyboard Serial
  • Arduino Sensors
  • Arduino - Humidity Sensor
  • Arduino - Temperature Sensor
  • Arduino - Water Detector / Sensor
  • Arduino - PIR Sensor
  • Arduino - Ultrasonic Sensor
  • Arduino - Connecting Switch
  • Motor Control
  • Arduino - DC Motor
  • Arduino - Servo Motor
  • Arduino - Stepper Motor
  • Arduino And Sound
  • Arduino - Tone Library
  • Arduino - Wireless Communication
  • Arduino - Network Communication
  • Arduino Useful Resources
  • Arduino - Quick Guide
  • Arduino - Useful Resources
  • Arduino - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Arduino - Compound Operators

Assume variable A holds 10 and variable B holds 20 then −

Operator name Operator simple Description Example
increment ++ Increment operator, increases integer value by one A++ will give 11
decrement -- Decrement operator, decreases integer value by one A-- will give 9
compound addition += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand B += A is equivalent to B = B+ A
compound subtraction -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand B -= A is equivalent to B = B - A
compound multiplication *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand B*= A is equivalent to B = B* A
compound division /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand B /= A is equivalent to B = B / A
compound modulo %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand B %= A is equivalent to B = B % A
compound bitwise or |= bitwise inclusive OR and assignment operator A |= 2 is same as A = A | 2
compound bitwise and &= Bitwise AND assignment operator A &= 2 is same as A = A & 2

To Continue Learning Please Login

This page requires JavaScript.

Please turn on JavaScript in your browser and refresh the page to view its content.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter documents all the JavaScript language operators, expressions and keywords.

Expressions and operators by category

For an alphabetical listing see the sidebar on the left.

Primary expressions

Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ).

The this keyword refers to a special property of an execution context.

Basic null , boolean, number, and string literals.

Array initializer/literal syntax.

Object initializer/literal syntax.

The function keyword defines a function expression.

The class keyword defines a class expression.

The function* keyword defines a generator function expression.

The async function defines an async function expression.

The async function* keywords define an async generator function expression.

Regular expression literal syntax.

Template literal syntax.

Grouping operator.

Left-hand-side expressions

Left values are the destination of an assignment.

Member operators provide access to a property or method of an object ( object.property and object["property"] ).

The optional chaining operator returns undefined instead of causing an error if a reference is nullish ( null or undefined ).

The new operator creates an instance of a constructor.

In constructors, new.target refers to the constructor that was invoked by new .

An object exposing context-specific metadata to a JavaScript module.

The super keyword calls the parent constructor or allows accessing properties of the parent object.

The import() syntax allows loading a module asynchronously and dynamically into a potentially non-module environment.

Increment and decrement

Postfix/prefix increment and postfix/prefix decrement operators.

Postfix increment operator.

Postfix decrement operator.

Prefix increment operator.

Prefix decrement operator.

Unary operators

A unary operation is an operation with only one operand.

The delete operator deletes a property from an object.

The void operator evaluates an expression and discards its return value.

The typeof operator determines the type of a given object.

The unary plus operator converts its operand to Number type.

The unary negation operator converts its operand to Number type and then negates it.

Bitwise NOT operator.

Logical NOT operator.

Pause and resume an async function and wait for the promise's fulfillment/rejection.

Arithmetic operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

Exponentiation operator.

Multiplication operator.

Division operator.

Remainder operator.

Addition operator.

Subtraction operator.

Relational operators

A comparison operator compares its operands and returns a boolean value based on whether the comparison is true.

Less than operator.

Greater than operator.

Less than or equal operator.

Greater than or equal operator.

The instanceof operator determines whether an object is an instance of another object.

The in operator determines whether an object has a given property.

Note: => is not an operator, but the notation for Arrow functions .

Equality operators

The result of evaluating an equality operator is always of type boolean based on whether the comparison is true.

Equality operator.

Inequality operator.

Strict equality operator.

Strict inequality operator.

Bitwise shift operators

Operations to shift all bits of the operand.

Bitwise left shift operator.

Bitwise right shift operator.

Bitwise unsigned right shift operator.

Binary bitwise operators

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

Bitwise AND.

Bitwise OR.

Bitwise XOR.

Binary logical operators

Logical operators implement boolean (logical) values and have short-circuiting behavior.

Logical AND.

Logical OR.

Nullish Coalescing Operator.

Conditional (ternary) operator

The conditional operator returns one of two values based on the logical value of the condition.

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

Assignment operator.

Multiplication assignment.

Division assignment.

Remainder assignment.

Addition assignment.

Subtraction assignment

Left shift assignment.

Right shift assignment.

Unsigned right shift assignment.

Bitwise AND assignment.

Bitwise XOR assignment.

Bitwise OR assignment.

Exponentiation assignment.

Logical AND assignment.

Logical OR assignment.

Nullish coalescing assignment.

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

Yield operators

Pause and resume a generator function.

Delegate to another generator function or iterable object.

Spread syntax

Spread syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

Comma operator

The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Operator precedence
  • Programming

Rahul Awati

  • Rahul Awati

What is an operator in mathematics and programming?

In mathematics and computer programming , an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.

Depending on its type, an operator manipulates an arithmetic or logical value, or operand, in a specific way to generate a specific result. From handling simple arithmetic functions to facilitating the execution of complex algorithms, like security encryption , operators play an important role in the programming world.

Mathematical and logical operators should not be confused with a system operator , or sysop, which refers to a person operating a server or the hardware and software in a computing system or network.

Operators and logic gates

In computer programs, Boolean operators are among the most familiar and commonly used sets of operators. These operators work only with true or false values and include the following:

These operators and variations, such as XOR, are used in logic gates .

Boolean operators can also be used in online search engines , like Google. For example, a user can enter a phrase like "Galileo AND satellite" -- some search engines require the operator be capitalized in order to generate results that provide combined information about both Galileo and satellite.

Types of operators

There are many types of operators used in computing systems and in different programming languages. Based on their function, they can be categorized in six primary ways.

1. Arithmetic operators

Arithmetic operators are used for mathematical calculations. These operators take numerical values as operands and return a single unique numerical value, meaning there can only be one correct answer.

The standard arithmetic operators and their symbols are given below.

+

Addition (a+b)

This operation adds both the operands on either side of the + operator.

-

Subtraction (a-b)

This operation subtracts the right-hand operand from the left.

*

Multiplication (a*b)

This operation multiplies both the operands.

/

Division (a/b)

This operation divides the left-hand operand by the operand on the right.

%

Modulus (a%b)

This operation returns the remainder after dividing the left-hand operand by the right operand.

2. Relational operators

Relational operators are widely used for comparison operators. They enter the picture when certain conditions must be satisfied to return either a true or false value based on the comparison. That's why these operators are also known as conditional operators.

The standard relational operators and their symbols are given below.

==

Equal (a==b)

This operator checks if the values of both operands are equal. If yes, the condition becomes TRUE.

!=

Not equal (a!=b)

This operator checks if the values of both operands are equal. If not, the condition becomes TRUE.

>

Greater than (a>b)

This operator checks if the left operand value is greater than the right. If yes, the condition becomes TRUE.

<

Less than (a<b)

This operator checks if the left operand is less than the value of right. If yes, the condition becomes TRUE.

>=

Greater than or equal (a>=b)

This operator checks if the left operand value is greater than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

<=

Less than or equal (a<=b)

This operator checks if the left operand value is less than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

3. Bitwise operators

Bitwise operators are used to manipulate bits and perform bit-level operations . These operators convert integers into binary before performing the required operation and then showing the decimal result.

The standard bitwise operators and their symbols are given below.

&

Bitwise AND (a&b)

This operator copies a bit to the result if it exists in both operands. So, the result is 1 only if both bits are 1.

|

Bitwise OR (a|b)

This operator copies a bit to the result if it exists in either operand. So, the result is 1 if either bit is 1.

^

Bitwise XOR (a^b)

This operator copies a bit to the result if it exists in either operand. So, even if one of the operands is TRUE, the result is TRUE. However, if neither operand is TRUE, the result is FALSE.

~

Bitwise NOT (~a)

This unary operator flips the bits (1 to 0 and 0 to 1).

4. Logical operators

Logical operators play a key role in programming because they enable a system or program to take specific decisions depending on the specific underlying conditions. These operators take Boolean values as input and return the same as output.

The standard logical operators and their symbols are given below.

&&

Logical AND (a&&b)

This operator returns TRUE only if both the operands are TRUE or if both the conditions are satisfied. It not, it returns FALSE.

||

(a||b)

This operator returns TRUE if either operand is TRUE. It also returns TRUE if both the operands are TRUE. If neither operand is true, it returns FALSE.

!

Logical NOT (!a)

This unary operator returns TRUE if the operand is FALSE and vice versa. It is used to reverse the logical state of its (single) operand.

5. Assignment operators

Assignment operators are used to assign values to variables. The left operand is a variable, and the right is a value -- for example, x=3.

The data types of the variable and the value must match; otherwise, the program compiler raises an error, and the operation fails.

The standard assignment operators and their symbols are given below.

=

Assignment (a=b)

This operator assigns the value of the right operand to the left operand (variable).

+=

Add and assign (a+=b)

This operator adds the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a+b.

-=

Subtract and assign (a-=b)

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Logically, the operator means a=a-b.

*=

Multiply and assign (a*=b)

This operator multiplies the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a*b.

/=

Divide and assign (a/=b)

This operator divides the left operand and the right operand and assigns the result to the left operand.

Logically, the operator means a=a/b.

%=

Modulus and assign (a%=b)

This operator performs the modulus operation on the two operands and assigns the result to the left operand.

Logically, the operator means a=a%b.

6. Increment/decrement operators

The increment/decrement operators are unary operators, meaning they require only one operand and perform an operation on that operand. They sometimes are called monadic operators .

The standard increment/decrement operators and their symbols are given below.

++

Post-increment (a++)

This operator increments the value of the operand by 1 after using its value.

--

Post-decrement (a--)

This operator decrements the value of the operand by 1 after using its value.

++

Pre-increment (++a)

This operator increments the value of the operand by 1 before using its value.

--

Pre-decrement (--a)

This operator decrements the value of the operand by 1 before using its value.

See also: proximity operator , search string , logical negation symbol , character and mathematical symbols .

Continue Reading About operator

  • How to become a good Java programmer without a degree
  • How improving your math skills can help in programming
  • 10 best IT certs for beginners
  • Top 22 cloud computing skills to boost your career in 2022
  • Binary and hexadecimal numbers explained for developers

Related Terms

NBASE-T Ethernet is an IEEE standard and Ethernet-signaling technology that enables existing twisted-pair copper cabling to ...

SD-WAN security refers to the practices, protocols and technologies protecting data and resources transmitted across ...

Net neutrality is the concept of an open, equal internet for everyone, regardless of content consumed or the device, application ...

A proof of concept (PoC) exploit is a nonharmful attack against a computer or network. PoC exploits are not meant to cause harm, ...

A virtual firewall is a firewall device or service that provides network traffic filtering and monitoring for virtual machines (...

Cloud penetration testing is a tactic an organization uses to assess its cloud security effectiveness by attempting to evade its ...

Regulation SCI (Regulation Systems Compliance and Integrity) is a set of rules adopted by the U.S. Securities and Exchange ...

Strategic management is the ongoing planning, monitoring, analysis and assessment of all necessities an organization needs to ...

IT budget is the amount of money spent on an organization's information technology systems and services. It includes compensation...

ADP Mobile Solutions is a self-service mobile app that enables employees to access work records such as pay, schedules, timecards...

Director of employee engagement is one of the job titles for a human resources (HR) manager who is responsible for an ...

Digital HR is the digital transformation of HR services and processes through the use of social, mobile, analytics and cloud (...

A virtual agent -- sometimes called an intelligent virtual agent (IVA) -- is a software program or cloud service that uses ...

A chatbot is a software or computer program that simulates human conversation or "chatter" through text or voice interactions.

Martech (marketing technology) refers to the integration of software tools, platforms, and applications designed to streamline ...

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Operators
  • Precedence and Associativity of Operators in Python
  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic
  • Ternary Operator in Python
  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .

Operators

=

Assign the value of the right side of the expression to the left side operandc = a + b 


+=

Add right side operand with left side operand and then assign the result to left operanda += b   

-=

Subtract right side operand from left side operand and then assign the result to left operanda -= b  


*=

Multiply right operand with left operand and then assign the result to the left operanda *= b     


/=

Divide left operand with right operand and then assign the result to the left operanda /= b


%=

Divides the left operand with the right operand and then assign the remainder to the left operanda %= b  


//=

Divide left operand with right operand and then assign the value(floor) to left operanda //= b   


**=

Calculate exponent(raise power) value using operands and then assign the result to left operanda **= b     


&=

Performs Bitwise AND on operands and assign the result to left operanda &= b   


|=

Performs Bitwise OR on operands and assign the value to left operanda |= b    


^=

Performs Bitwise XOR on operands and assign the value to left operanda ^= b    


>>=

Performs Bitwise right shift on operands and assign the result to left operanda >>= b     


<<=

Performs Bitwise left shift on operands and assign the result to left operanda <<= b 


:=

Assign a value to a variable within an expression

a := exp

Here are the Assignment Operators in Python with examples.

Assignment Operator

Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.

S ubtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.

M ultiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.

D ivision Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.

M odulus Assignment Operator

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.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.

F loor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.

Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.

Bitwise XOR Assignment Operator 

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.

Walrus Operator

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.

Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.

author

Please Login to comment...

Similar reads.

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

compound assignment operators modulus

Announcing UNISTR and || operator in Azure SQL Database – preview

compound assignment operators modulus

Abhiman Tiwari

June 4th, 2024 0 0

We are excited to announce that the UNISTR intrinsic function and ANSI SQL concatenation ope ra tor ( || ) are now available in public preview in Azure SQL Database. The UNISTR function allows you to escape Unicode characters, making it easier to work with international text. The ANSI SQL concatenation ope ra tor ( || ) provides a simple and intuitive way to combine characters or binary strings. These new features will enhance your ability to manipulate and work with text data.  

What is UNISTR function?

The UNISTR function takes a text literal or an expression of characters and Unicode values, that resolves to character data and returns it as a UTF-8 or UTF-16 encoded string . This function allows you to use Unicode codepoint escape sequences with other characters in the string. The escape sequence for a Unicode character can be specified in the form of \ xxxx or \+ xxxxxx , where xxxx is a valid UTF-16 codepoint value, and xxxxxx is a valid Unicode codepoint value. This is especially useful for inserting data into NCHAR columns.  

The syntax of the UNISTR function is as follows:

  • The data type of character_expression could be char ,  nchar ,  varchar , or  nvarchar . For  char and  varchar  data types, the collation should be a valid UTF-8 collation only.
  • A single character representing a user-defined Unicode escape sequence. If not supplied, the default value is \.

Example #1:

For example, the following query returns the Unicode character for the specified value:

——————————-

Example #2:  

In this example, the UNISTR function is used with a user-defined escape character ( $ ) and a VARCHAR data type with UTF-8 collation.

I ♥ Azure SQL.

The legacy collations with code page can be identified using the query below:

What is ANSI SQL concatenation operator (||)?

The ANSI SQL concatenation ope ra tor ( || ) concatenates two or more characters or binary strings, columns, or a combination of strings and column names into one expression . The || ope ra tor does not honor the SET CONCAT_NULL_YIELDS_NULL option and always behaves as if the ANSI SQL behavior is enabled . This ope ra tor will work with character strings or binary data of any supported SQL Server collation . The || ope ra tor supports compound assignment || = similar to += . If the ope ra nds are of incompatible collation, then an error will be thrown. The collation behavior is identical to the CONCAT function  of character string data.

The syntax of the string concatenation operator is as follows:

  • The expression is a character or binary expression. Both expressions must be of the same data type, or one expression must be able to be implicitly converted to the data type of the other expression. If one ope ra nd is of binary type, then an unsupported ope ra nd type error will be thrown.

Example #1:  

For example, the following query concatenates two strings and returns the result:

Hello World!

Example #2:

In this example, multiple character strings are concatenated. If at least one input is a character string, non-character strings will be implicitly converted to character strings.

full_name order_details                                                                                                         item_desc

Josè Doe Order-1001~TS~Jun 1 2024 6:25AM~442A4706-0002-48EC-84FC-8AF27XXXX NULL

Example #3:  

In the example below, concatenating two or more binary strings and also compounding with T-SQL assignment operator.

V1          B1    B2

0x1A2B       0x4E  0xAE8C602E951AC245ADE767A23C834704A5

Example #4:  

As shown in the example below, using the || operator with only non-character types or combining binary data with other types is not supported.

Above queries will fail with error messages as below –  

In this blog post, we have introduced the UNISTR function and ANSI SQL concatenation operator (||) in Azure SQL Database.  The UNISTR function allows you to escape Unicode characters, making it easier to work with international text. ANSI SQL concatenation operator (||) provides a simple and intuitive way to combine characters or binary data. These new features will enhance your ability to manipulate and work with text data efficiently.  

We hope you will explore these enhancements, apply them in your projects, and share your feedback with us to help us continue improving.   Thank you!

compound assignment operators modulus

Abhiman Tiwari Senior Product Manager, Azure SQL

authors

Leave a comment Cancel reply

Log in to start the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

IMAGES

  1. PPT

    compound assignment operators modulus

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

    compound assignment operators modulus

  3. PPT

    compound assignment operators modulus

  4. Modulus Operator

    compound assignment operators modulus

  5. PPT

    compound assignment operators modulus

  6. PPT

    compound assignment operators modulus

VIDEO

  1. 1.5 Compound Assignment Operators

  2. C++ Basics: Operators

  3. Compound Assignment Operators in C language

  4. CIS 1500

  5. Complex Numbers ( Modulus , Argument & Polar form )

  6. Division Operators in Python || English

COMMENTS

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

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

  3. Compound assignment operators in Java

    The compound assignment operators are +=, -=, *=, /=, %= etc. The. 2 min read. 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 ...

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

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

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

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

  8. Compound assignment operators in Java

    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.

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

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

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

  12. operators

    i: 56, i %= 12: 8. i: 8, i %= 3: 2. 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.

  13. Assignment operators

    For all other compound assignment operators, the type of target-expr must be an arithmetic type. In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

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

  15. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=".

  16. Compound Assignment Operator in Java

    The compound assignment operator 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 ...

  17. What is the Modulus Operator? A Short Guide with Practical 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: a - (n * floor(a/n)) By substituting values, we can see how the modulo operation works in practice: 100 % 7 = 2. // a = 100, n = 7.

  18. Arithmetic operators

    For more information, see the -and -= operators article. Compound assignment. For a binary operator op, a compound assignment expression of the form. x op= y is equivalent to. x = x op y except that x is only evaluated once. The following example demonstrates the usage of compound assignment with arithmetic operators:

  19. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  20. about Assignment Operators

    Compound assignment operators perform numeric operations on the values before the assignment. Important. Compound assignment operators don't use dynamic scoping. The variable is always in the current scope. ... The assignment by modulus operator %= divides the value of a variable by the value on the right side of the operator.

  21. Arduino

    Increment operator, increases integer value by one: A++ will give 11: decrement--Decrement operator, decreases integer value by one: A-- will give 9: compound addition += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand: B += A is equivalent to B = B+ A: compound subtraction-= Subtract ...

  22. Basic Operators

    Compound Assignment Operators in page link. Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. One example is the addition assignment operator (+=): var a = 1 a += 2 // a is now equal to 3. The expression a += 2 is shorthand for a = a + 2. Effectively, the addition and the assignment are ...

  23. Expressions and operators

    Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.

  24. What is an operator in programming?

    5. Assignment operators. Assignment operators are used to assign values to variables. The left operand is a variable, and the right is a value -- for example, x=3. The data types of the variable and the value must match; otherwise, the program compiler raises an error, and the operation fails.

  25. Assignment Operators in Python

    Assignment Operator. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output. 8.

  26. Announcing UNISTR and || operator in Azure SQL Database

    We are excited to announce that the UNISTR intrinsic function and ANSI SQL concatenation operator (||) are now available in public preview in Azure SQL Database. The UNISTR function allows you to escape Unicode characters, making it easier to work with international text. The ANSI SQL concatenation operator (||) provides a simple and intuitive ...