Javatpoint Logo

Java Tutorial

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

JavaTpoint

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

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

For example:

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

Using both assignment operators generates the same result.

Java supports the following assignment operators:

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

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Java Compound Operators

Last updated: March 17, 2024

compound assignment statement java

  • Java Operators

announcement - icon

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

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

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

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

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

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

Improve Java application performance with CRaC support

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

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

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

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

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

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

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

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

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

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

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

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

>> Become an efficient full-stack developer with Jmix

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

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

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

>> Take a look at DBSchema

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

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

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

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

>> The New “REST With Spring Boot”

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

>> LEARN SPRING

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

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

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

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

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

You can explore the course here:

>> Learn Spring Security

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

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

>> CHECK OUT THE COURSE

1. Overview

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

We’ll also explain how implicit casting works.

2. Compound Assignment Operators

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

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

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

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

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

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

Both x and y will hold the value 3 .

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

3. Types of Compound Assignment Operators

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

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

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

Then, we also have the bitwise operators:

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

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

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

4. Evaluation of Compound Assignment Operations

There are two ways Java evaluates the compound operations.

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

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

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

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

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

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

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

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

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

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

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

5. Implicit Casting

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

Formally, a compound assignment expression of the form:

is equivalent to:

E1 – (T)(E1 op E2)

where T is the type of E1 .

Let’s consider the following example:

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

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

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

This could be fixed with an explicit cast:

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

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

6. Conclusion

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

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

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

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

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

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

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

>> Try Alpaquita Containers now.

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

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

  • Trending Categories

Data Structure

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

Compound assignment operators in Java\n

The Assignment Operators

Following are the assignment operators supported by Java language −

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

This will produce the following result −

karthikeya Boyini

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

Kickstart Your Career

Get certified by completing the course

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.

compound assignment statement java

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

1.5. Compound Assignment Operators ¶

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

+ shortcuts

- shortcuts

* shortcut

/ shortcut

% shortcut

x = x + 1;

x = x - 1;

x = x * 2;

x = x / 2;

x = x % 2;

x += 1;

x -= 1;

x *= 2;

x /= 2;

x %= 2;

x++;

x- -;

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

coding exercise

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

exercise

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

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

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

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

1.5.1. Code Tracing Challenge and Operators Maze ¶

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

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

For example, given the following code:

The corresponding trace table looks like this:

Line

Statement

x

y

z

1

x = 10;

10

2

y = 15;

15

3

z = x * y;

150

4

z++;

151

5

x = z * 2;

302

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

Compressed Trace

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

1.5.2. Prefix versus Postfix Operator ¶

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

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

Example

Description

Type

System.out.println(count++);

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

Postfix

System.out.println(++count);

Add one to count, then print the new value

Prefix

x = y++;

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

Postfix

x = ++y;

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

Prefix

x = y- -;

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

Postfix

x = - -y;

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

Prefix

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

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

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

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

1.5.3. Summary ¶

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

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

01 Career Opportunities

02 beginner, 03 intermediate, 04 questions, 05 training programs, assignment operator in java, java online course free with certificate (2024), assignment operators in java: an overview, what are the assignment operators in java, types of assignment operators in java, 1. simple assignment operator (=):, explanation, 2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):, 5. division operator (/=):, 6. modulus assignment operator (%=):, example of assignment operator in java, q1. can i use multiple assignment operators in a single statement, q2. are there any other compound assignment operators in java, q3. how many types of assignment operators, live classes schedule.

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

About Author

compound assignment statement java

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

Advertisement

+= operator

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

Example with += operator

-= operator.

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

Example with -= operator

*= operator.

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

Example with *= operator

/= operator.

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

Example with /= operator

%= operator.

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

Example with %= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

© Copyright 2020 Decodejava.com. All Rights Reserved.

Compound-Assignment Operators

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

Compound-Assignment Operators in Java

Java supports 11 compound-assignment operators:

Example Usage

To assign the result of an addition operation to a variable using the standard syntax:

But use a compound-assignment operator to effect the same outcome with the simpler syntax:

  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • Conditional Operators
  • Conditional Statements in Java
  • Working With Arrays in Java
  • Declaring Variables in Java
  • If-Then and If-Then-Else Conditional Statements in Java
  • How to Use a Constant in Java
  • Common Java Runtime Errors
  • What Is Java?
  • What Is Java Overloading?
  • Definition of a Java Method Signature
  • What a Java Package Is In Programming
  • Java: Inheritance, Superclass, and Subclass
  • Understanding Java's Cannot Find Symbol Error Message
  • Using Java Naming Conventions

Java - Compound Arithmetic Assignment Operators

What are compound operators.

The basic arithmetic operators (+, -, *, /, and %) has a corresponding compound arithmetic assignment operator.

A compound arithmetic assignment operator is used in the following form:

The above expression is equivalent to the following expression:

Suppose you have two variables, num1 and num2.

To add the value of num1 to num2 together, write code as

The code above can be rewritten using the compound arithmetic operator += as follows:

For example,

is equivalent to

+= on String variables

The compound assignment operator += can be used on String variables.

operand1 must be of type String and the operand2 may be of any type. Only the += operator can be used with a String left-hand operand. For example,

can be rewritten as

boolean Promotion

boolean type cannot be used with += unless left-hand operand (i) is a String variable.

Java Operators

Java arithmetic operators, java unary plus and minus, java increment and decrement, java number division by zero, java assignment operator, java compound assignment, java operator precedence, java relational operators, java logical operators, java conditional operator, java instanceof operator, java new operator, java modulus operator, java java bitwise operators, java bitwise logical operators, java left shift operator, java right shift operator, java unsigned right shift, java bitwise compound operators, java short-circuit operators, java java arithmetic operators example, java example, java arithmetic compound assignment operators.

A compound assignment operator is an operator that performs a calculation and an assignment at the same time.

All of Java's binary arithmetic operators (the ones that work on two operands) have equivalent compound assignment operators.

Operator Description
+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment
/= Division and assignment
%= Remainder and assignment

The statement

is equivalent to

Also, the statement

Thus, any statement of the form

can be rewritten as

To prevent confusion, use compound assignment expressions by themselves, not in combination with other expressions.

Consider these statements:

Is a set to 7 or 8?

In other words, is the third statement equivalent to

The assignment has the lowest precedence of all, and the multiplication here is performed as part of the assignment. As a result, the addition is performed before the multiplication - and the answer is 8.

Here is a sample program that shows several op= assignments in action:

The output of this program is shown here:

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

Difference between Simple and Compound Assignment in Java

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

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

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

Please Login to comment...

Similar reads.

  • Difference Between
  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=)

So for binary operators on booleans, Java has & , | , ^ , && and || .

Let's summarize what they do briefly here:

  • JLS 15.22.2 Boolean Logical Operators &, ^, and |
  • JLS 15.23 Conditional-And Operator &&
  • JLS 15.24 Conditional-Or Operator ||
For & , the result value is true if both operand values are true ; otherwise, the result is false . For | , the result value is false if both operand values are false ; otherwise, the result is true . For ^ , the result value is true if the operand values are different; otherwise, the result is false . The && operator is like & but evaluates its right-hand operand only if the value of its left-hand operand is true . The || operator is like | , but evaluates its right-hand operand only if the value of its left-hand operand is false .

Now, among all 5, 3 of those have compound assignment versions, namely |= , &= and ^= . So my question is obvious: why doesn't Java provide &&= and ||= as well? I find that I need those more than I need &= and |= .

And I don't think that "because it's too long" is a good answer, because Java has >>>= . There must be a better reason for this omission.

From 15.26 Assignment Operators :

There are 12 assignment operators; [...] = *= /= %= += -= <<= >>= >>>= &= ^= |=

A comment was made that if &&= and ||= were implemented, then it would be the only operators that do not evaluate the right hand side first. I believe this notion that a compound assignment operator evaluates the right hand side first is a mistake.

From 15.26.2 Compound Assignment Operators :

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)) , where T is the type of E1 , except that E1 is evaluated only once.

As proof, the following snippet throws a NullPointerException , not an ArrayIndexOutOfBoundsException .

  • conditional-operator
  • assignment-operator
  • short-circuiting
  • compound-assignment

polygenelubricants's user avatar

  • 2 I go for the second, no one cares :P also, all these question about 'why feature x is not in language y?' should be asked to the language's designers, not to us :P –  Federico klez Culloca Commented Oct 1, 2009 at 17:40
  • 1 What does &= mean ? Some one please can tell me ? –  Tarik Commented Oct 1, 2009 at 17:43
  • @Aaron: a = a & b. It's written in the question –  Federico klez Culloca Commented Oct 1, 2009 at 17:44
  • 1 possible duplicate of Why does a "&&=" Operator not exist? –  Josh Lee Commented Aug 16, 2010 at 14:57
  • 1 @jleedev: That question is older, but this has more votes and incoming links. I'd say if there's any merge, merge the old one to this one (yes, that can be done). –  polygenelubricants Commented Aug 16, 2010 at 15:20

12 Answers 12

The operators &&= and ||= are not available on Java because for most of the developers these operators are:

  • error-prone

Example for &&=

If Java allowed &&= operator, then that code:

would be equivalent to:

This first code is error-prone because many developers would think f2() is always called whatever the f1() returned value. It is like bool isOk = f1() && f2(); where f2() is called only when f1() returns true .

If the developer wants f2() to be called only when f1() returns true , therefore the second code above is less error-prone.

Else &= is sufficient because the developer wants f2() to be always called:

Same example but for &=

Moreover, the JVM should run this above code as the following one:

Compare && and & results

Are the results of operators && and & the same when applied on boolean values?

Let's check using the following Java code:

Therefore YES we can replace && by & for boolean values ;-)

So better use &= instead of &&= .

Same for ||=

Same reasons as for &&= : operator |= is less error-prone than ||= .

If a developer wants f2() not to be called when f1() returns true , then I advice the following alternatives:

oHo's user avatar

  • 2 Hi @StriplingWarrior. I have checked with my colleague Yannick, our best Java expert. I have updated my answer using the Java code source used to check that point. As you said & and && give the same results. Thank you very much for your feedback. Do you like my answer? Cheers. –  oHo Commented Apr 3, 2012 at 8:31
  • 2 What if I want to do this very fast? &&= would be faster than &=, if it existed, so you should use if (a) a = b for speed –  adventurerOK Commented Jun 18, 2012 at 17:55
  • Hi @adventurerOK. Sorry I am not sure to understand what you mean... I think a&=b; is faster than if(a) a=b; when using values stored within the CPU registers. However, if b is in external memory (not cached), then if(a) a=b; is faster. Is it what you mean? Please provide more example code ;-) I am curious about your opinion. See you. Cheers –  oHo Commented Jun 25, 2012 at 13:08
  • 17 I don't agree when you say "And this is not what we want." If I write isOK &&= f2(); I would want it to short circuit just like && does. –  Tor Klingberg Commented Jun 4, 2013 at 13:32
  • 4 I do not agree with your claim that the operators would be error-prone or useless. Using compound assignments is something you do to take a shortcut for the usual A = A op B , so everyone perfectly knows what they are doing and can care for the implications themselves. If your reasons were indeed the cause for its absence, I would see it as unwanted patronizing. However, I wanna thank you for adding the line bool isOk = f1() || f2() || f3() || f4(); because that's what I was to blind to see myself. –  Franz B. Commented Jul 17, 2015 at 14:26

Probably because something like

looks like it ought to be assigning to x and evaluating someComplexExpression() , but the fact that the evaluation hinges on the value of x isn't apparent from the syntax.

Also because Java's syntax is based on C, and no one saw a pressing need to add those operators. You'd probably be better off with an if statement, anyway.

Josh Lee's user avatar

  • 45 I think this is not a good answer, because one can argue that x() && y() looks like it ought to evaluate both sides of the expression. Obviously people accept that && is short-circuiting, so that should also follows to &&= as well. –  polygenelubricants Commented Feb 24, 2010 at 8:41
  • 2 @jleedev, agreed. I believe in these situations it's important to remember that this isn't the equivalent of x = x && someComplexExpression() but the equivalent of x = someComplexExpression() && x. The right-hand side will/should be evaluated first to be consistent with every other assignment operator. And given that, &&= would have no different behavior than &=. –  PSpeed Commented Feb 24, 2010 at 8:46
  • 3 @PSpeed, you are mistaken. The JLS is very clear on what the compound assignment is supposed to do. See my addition above. –  polygenelubricants Commented Feb 24, 2010 at 8:52
  • 1 I think saying that they aren't there because the designers simply followed the precedence set by C is misleading, since they did add >>> and >>>= , which are entirely new. –  polygenelubricants Commented Feb 24, 2010 at 9:52
  • 2 @PSpeed: In that case, a -= b; would work entirely differently from a &&= b; . –  David Thornley Commented Mar 22, 2010 at 14:09

It is this way in Java, because it is this way in C.

Now the question why it is so in C is because when & and && became different operators (sometime preceding C's descent from B), the &= variety of operators was simply overlooked.

But the second part of my answer does not have any sources to back it up.

EFraim's user avatar

  • 3 On the funny side - the question was recently asked in the C forum; and this answer was linked (though not marked duplicate) Which makes completes the circular argument! –  UKMonkey Commented Mar 13, 2019 at 15:10

Largely because Java syntax is based on C (or at least the C family), and in C all those assignment operators get compiled to arithmetic or bitwise assembly instructions on a single register. The assignment-operator version avoids temporaries and may have produced more efficient code on early non-optimising compilers. The logical operator (as they are termed in C) equivalents ( &&= and ||= ) don't have such an obvious correspondence to single assembly instructions; they usually expand to a test and branch sequence of instructions.

Interestingly, languages like ruby do have ||= and &&=.

Edit: terminology differs between Java and C

p00ya's user avatar

  • I believe you mean the conditional operator equivalents don't have such obvious correspondence. In JLS terminology, the boolean logical operators are & , | and ^ ; && and || are the conditional operators. –  polygenelubricants Commented Feb 24, 2010 at 8:40
  • In C terminology, && and || are "logical operators", s6.5.13-14 in ISO 9899:1999. The bitwise operators are only "logical" when applied to a single bit (a boolean in java); there is no single-bit type in C and the logical operators there apply to all scalar types. –  p00ya Commented Feb 24, 2010 at 9:29
  • before C99, C didn't even have a bool type. That's 20 years in the language history with no bool. There was no reason to have &&= . bitwise operations were enough. –  v.oddou Commented Apr 2, 2020 at 8:05
  • +1 The only answer that really makes sense. There are no deeper reasons for the lack of those operators than Java's C heritage. C was (and largely still is) just a "high level assembler", and from this perspective there was no need for those operators, since they would not compile into more efficient machine code. –  Elmar Zander Commented Oct 15, 2021 at 8:20

One of Java's original aims was to be "Simple, Object Oriented, and Familiar." As applied to this case, &= is familiar (C, C++ have it and familiar in this context meant familiar to someone who knows those two).

&&= would not be familiar, and it would not be simple, in the sense that the language designers were not looking to think of every operator they could add to the language, so less extra operators are simpler.

Yishai's user avatar

Brian Goetz (Java Language Architect at Oracle) wrote :

https://stackoverflow.com/q/2324549/ [this question] shows that there is interest in having these operators and there are no clear arguments why they don't exist yet. The question is therefore: Has the JDK team discussed adding these operators in the past and if so what where the reasons against adding them?

I'm not aware of any specific discussion on this particular issue, but if someone were to propose it, the answer would likely be: it's not an unreasonable request, but it doesn't carry its weight.

"Carrying its weight" needs to be judged by its costs and benefits, and by its cost-benefit ratio relative to other candidate features.

I think you are implicitly assuming (by the phrase "there is interest") that the cost is near zero and the benefit is greater than zero, so it seems an obvious win. But this belies an incorrect understanding of cost; a feature like this affects the language spec, the implementation, the JCK, and every IDE and Java textbook. There are no trivial language features. And the benefit, while nonzero, is pretty small.

Secondarily, there are infinitely many features we could do, but we only have capacity to do a handful every few years (and users have a limited capacity to absorb new features.) So we have to be very careful as to which we pick, as each feature (even a trivial-seeming one) consumes some of this budget, and invariably takes it away from others. It's not "why not this feature", but "what other features will we not do (or delay) so we can do this one, and is that a good trade?" And I can't really imagine this being a good trade against anything else we're working on.

So, it clears the bar of "not a terrible idea" (which is already pretty good, a lot of feature requests don't even clear that), but seems unlikely to ever clear the bar of "a better use of our evolution budget than anything else."

Marcono1234's user avatar

For Boolean vars, && and || would use short circuit evaluation while & and | don't, so you would expect &&= and ||= to also use short circuit evaluation. There is a good use case for this. Especially if you are iterating over a loop, you want to be fast, efficient and terse.

Instead of writing

I want to write

and know that once bVal is true, fn() will not be called for the remainder of the iterations.

zanfilip's user avatar

  • 2 For that loop you probably just want to do if (fn(item)) { bVal = true; break; } . –  Radiodef Commented Jun 12, 2015 at 13:19

' & ' and ' && ' are not the same as ' && ' is a short cut operation which will not do if the first operand is false while ' & ' will do it anyway (works with both number and boolean).

I do agree that it make more sense to exist but it is not that bad if it is not there. I guess it was not there because C does not have it.

Really can't think of why.

NawaMan's user avatar

Funny I came across this question.

The operators ||= and &&= do not exist as their semantics are easily misunderstood; if you think you need them, use an if-statement instead.

Ely (post just above) got the gist right:

stops evaluating if the first operand evaluates to true since the result will be true, it's a logical operator.

So imagine what will happen if b == true;

b ||= somethingreturningaboolean(); // !!??

this will not invoke somethingreturningaboolean(), if b == true.

This behavior is more obvious in the long form:

b = b || somethingreturningaboolean();

That's why ||= and &&= ops do not exist. The explanation should be given as: The operators ||= and &&= do not exist as their semantics are easily misunderstood; if you think you need them, use an if-statement instead.

Martin F Schulz's user avatar

It is allowed in Ruby.

If I were to guess, I would say that it is not frequently used so it wasn't implemented. Another explanation could be that the parser only looks at the character before the =

zzawaideh's user avatar

  • 1 Java supports <<=, >>= and >>>=, so that isn't strictly true. –  Yishai Commented Oct 1, 2009 at 18:01
  • true. I didn't think of those. I guess the only explanation is then how frequently it is used. –  zzawaideh Commented Oct 5, 2009 at 14:41

I cannot think of any better reason then 'It looks incredible ugly!'

Daniel Brückner's user avatar

  • 10 But then C/Java was never meant to be beautiful. –  EFraim Commented Oct 1, 2009 at 17:45
  • 2 I'd barely consider &&= to be ugly –  asgs Commented May 17, 2017 at 7:32

verifies both operands, it's a bitwise operator. Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

stops evaluating if the first operand evaluates to false since the result will be false, it's a logical operator. It can be applied to booleans.

The && operator is similar to the  & operator, but can make your code a bit more efficient. Because both expressions compared by the & operator must be true for the entire expression to be true, there’s no reason to evaluate the second expression if the first one returns false. The & operator always evaluates both expressions. The && operator evaluates the second expression only if the first expression is true.

Having a &&= assignment operator wouldn't really add new functionality to the language. The bitwise operator's arithmetic is much more expressive, you can do integer bitwise arithmetic, which includes Boolean arithmetic. The logical operators can merely do Boolean arithmetic.

Ely's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • Searching for a 90s Anime with a Dark-to-Light Princess Twist
  • Is expired sushi rice still good
  • Was homology influenced by Euler's polyhedron formula?
  • Why doesn't Oppenheimer like the word "bomb" being used to describe the bomb?
  • What acceleration features did 2D PC video cards have? Comparing to video game consoles
  • Usage of Tabular method for Integration by Parts
  • Split column into lines using awk
  • Solving a system of inequalities involving Binomial
  • Why would radio-capable transhumans still vocalise to each-other?
  • Add author one line after section title in toc
  • Can I solder aged copper with patina on it?
  • Is "Non-Trivial amount of work" a correct phrase?
  • How are multiple sections of a large course assigned?
  • User does not have access to sudo on Debian 12 unless the system is rebooted
  • Borderlands 2 for PS3 has unbelievably low drop rates. Is something wrong?
  • Why are the Founders in Star Trek: Deep Space Nine considered so powerful?
  • Which programming language first used negative indexing to mean counting from the end?
  • Why have SIGPIPE when EPIPE exists?
  • The Puzzle Noob’s New Game
  • Does a router lookup in routing table twice for each packet?
  • Strange fact about files and the file system they belong on recent macOS
  • How should I acknowledge a reviewer who left a negative review?
  • Who was Dionysodorus of Melos?
  • Could mage hand be used for surgery on another creature?

compound assignment statement java

IMAGES

  1. Compound Assignment Operators in Java

    compound assignment statement java

  2. JAVA

    compound assignment statement java

  3. The Java Compound Statement

    compound assignment statement java

  4. Compound Assignment Operators in Java

    compound assignment statement java

  5. PPT

    compound assignment statement java

  6. 010

    compound assignment statement java

VIDEO

  1. #20. Assignment Operators in Java

  2. CPP Lect08: Compound Assignment Statement

  3. JAVA TUTORIAL

  4. Core

  5. CIS 1500

  6. Compound Assignment Operators in C language

COMMENTS

  1. Compound assignment operators in Java

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator)

  2. Compound Assignment Operator in Java

    Compound Assignment Operator in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods ...

  3. Java Compound Operators

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

  4. Java Compound Assignment Operators (With Examples)

    What are Compound Assignment Operators in Java? Compound assignment operators in Java are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform an operation on a variable's value and then assign the result back to the same variable in a single step.

  5. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  6. Java Compound Assignment Operators

    Java Compound Assignment Operators 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.

  7. Java Compound Assignment Operators

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

  8. Compound assignment operators in Java\n

    Compound assignment operators in Javan - The Assignment OperatorsFollowing are the assignment operators supported by Java language −OperatorDescriptionExample=Simple assignment operator. Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C+=Add AND assignment operator. It adds right ope.

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

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

  10. PDF Compound assignment operators

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

  11. 1.5. Compound Assignment Operators

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

  12. Assignment operator in Java

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

  13. Java

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

  14. compound assignment operator in java

    The compound assignment operator stores the original value of the left operand before evaluating the second operand and performing the compound assignment (addition + assignment in this example).

  15. What Is a Compound-Assignment Operator?

    Compound assignment operators provide a shorter syntax to assign the results of the arithmetic and bitwise operators.

  16. Java

    What are Compound Operators? The basic arithmetic operators (+, -, *, /, and %) has a corresponding compound arithmetic assignment operator.

  17. Java Arithmetic Compound Assignment Operators

    A compound assignment operator is an operator that performs a calculation and an assignment at the same time. All of Java's binary arithmetic operators (the ones that work on two operands) have equivalent compound assignment operators.

  18. Difference between Simple and Compound Assignment in Java

    The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment, E1 = (T) ( (E1) op (E2)), where T is the type of E1. In other words, compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side.

  19. Order of operations for compound assignment operators in Java

    In my thinking at this point k should be 4 because that was the new assignment, but the answer is actually 25, and not 28. Apparently compound operators have some order of precedence I'm not understanding, or my substitution principles are not correct.

  20. Java: compound assignment and expression based type promotion

    In the three bitwise left shift code fragments below, it's interesting that examples #2 and #3 are treated differently by Java. In the last example (#3), why does Java decide not to upgrade the compound assignment statement to an int?

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

    I believe this notion that a compound assignment operator evaluates the right hand side first is a mistake. From 15.26.2 Compound Assignment Operators: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.