• 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

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:

Implementation of all compound assignment operator

Rules for resolving the Compound assignment operators

At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable.
  • First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Examples : Resolving the statements with Compound assignment operators

We all know that whenever we are assigning a bigger value to a smaller data type variable then we have to perform explicit type casting to get the result without any compile-time error. If we did not perform explicit type-casting then we will get compile time error. But in the case of compound assignment operators internally type-casting will be performed automatically, even we are assigning a bigger value to a smaller data-type variable but there may be a chance of loss of data information. The programmer will not responsible to perform explicit type-casting. Let’s see the below example to find the difference between normal assignment operator and compound assignment operator. 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.

For example, the following code is correct:

and results in x having the value 7 because it is equivalent to:

Because here 6.6 which is double is automatically converted to short type without explicit type-casting.

Refer: When is the Type-conversion required?

Explanation: In the above example, we are using normal assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) that’s results in compile time error. Here we have to do type-casting to get the result.

Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) apart from that we get the result as 20 because In compound assignment operator type-casting is automatically done by compile. Here we don’t have to do type-casting to get the result.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

Similar Reads

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Topic 1.4 Understanding Compound Assignment Operators and Increment/Decrement Operators in Java

What Are Compound Assignment Operators?

Compound assignment operators in Java allow you to perform an arithmetic operation and assignment in a single step. They help make your code shorter and often easier to read. Here are the compound assignment operators we'll cover:

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

How Do They Work?

Each compound assignment operator combines an arithmetic operation with assignment. Let's break down how each one works:

  • Addition Assignment (+=) : Adds a value to a variable and assigns the result back to that variable.

x += 3; // This is the same as x = x + 3;

// Now, x is 8

  • Subtraction Assignment (-=) : Subtracts a value from a variable and assigns the result back to that variable.

int y = 10;

y -= 4; // This is the same as y = y - 4;

// Now, y is 6

  • Multiplication Assignment (*=) : Multiplies a variable by a value and assigns the result back to that variable.

z *= 2; // This is the same as z = z * 2;

// Now, z is 14

  • Division Assignment (/=) : Divides a variable by a value and assigns the result back to that variable.

int a = 20;

a /= 5; // This is the same as a = a / 5;

// Now, a is 4

  • Modulus Assignment (%=) : Calculates the remainder of dividing a variable by a value and assigns the result back to that variable.

int b = 15;

b %= 4; // This is the same as b = b % 4;

// Now, b is 3

Real-World Example: Budget Management

Imagine you are managing a weekly budget. You start with $100, and every week you spend some money on different activities. You can use compound assignment operators to easily update your budget:

int budget = 100;

int groceries = 30;

int entertainment = 20;

// Spend money on groceries

budget -= groceries; // budget = budget - groceries

// Spend money on entertainment

budget -= entertainment; // budget = budget - entertainment

System.out.println("Remaining budget: " + budget);

Increment and Decrement Operators

The increment (++) and decrement (--) operators are used to add or subtract 1 from a variable, respectively.

  • Increment Operator (++) :

int count = 0;

count++; // This is the same as count = count + 1;

// Now, count is 1

  • Decrement Operator (--) :

int count = 5;

count--; // This is the same as count = count - 1;

// Now, count is 4

Full Java Program Example

Here is a simple Java program that demonstrates the use of compound assignment operators and increment/decrement operators:

public class Main {

    public static void main(String[] args) {

        // Compound assignment operators

        int x = 10;

        x += 5;  // x = x + 5

        x -= 3;  // x = x - 3

        x *= 2;  // x = x * 2

        x /= 4;  // x = x / 4

        x %= 3;  // x = x % 3

       

        System.out.println("Value of x: " + x); // Outputs the final value of x

        // Increment and decrement operators

        int count = 0;

        count++; // Increment count by 1

        count--; // Decrement count by 1

        System.out.println("Value of count: " + count); // Outputs the final value of count

    }

Programming Problem

Problem Statement:

Write a Java program to manage your daily water intake. You start with 0 liters of water. Each time you drink a glass of water (assume 0.25 liters), you should update your total intake. Use compound assignment operators to update your total water intake and increment/decrement operators if necessary.

Instructions:

  • Initialize a variable waterIntake to 0.
  • Use a compound assignment operator to add 0.25 to waterIntake each time you drink a glass of water.
  • Print the total water intake after a few glasses.

public class WaterIntake {

        double waterIntake = 0;

        waterIntake += 0.25; // Drank one glass of water

        waterIntake += 0.25; // Drank another glass of water

        System.out.println("Total water intake: " + waterIntake + " liters"); // Should print 0.75 liters

Now, try writing your program to keep track of your daily water intake. Happy coding!

IMAGES

  1. 1.4 Compound Assignment Operators

    1 4 compound assignment operators

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

    1 4 compound assignment operators

  3. PPT

    1 4 compound assignment operators

  4. Exploring Compound Assignment Operators in C

    1 4 compound assignment operators

  5. PPT

    1 4 compound assignment operators

  6. Compound Assignment Operators

    1 4 compound assignment operators

VIDEO

  1. How can we use assignment operators

  2. Java for Testers

  3. Chapter-4 Control Statements: Assignment, ++ and -- Operators Part 1

  4. Arithmetic Operators and Precedence in C++

  5. C++ 24

  6. Compound Assignment Operator #7

COMMENTS

  1. 1.4 Compound Assignment Operators Flashcards

    Study with Quizlet and memorize flashcards containing terms like compound assignment operator, compound assignment operator ex., int varName = 5; varName %= 2; System.out.print(varName); and more.

  2. 1.4

    The statement n = n + 100; is the same as... n +=100; Binary operators come _______. Assignment Operators come ______. first, after the binary operator. binary operator. operator with two operands (a number or cell reference used in a formula. In the case of only adding or subtracting one, the special format is... n++ (n + 1) and n-- (n - 1)

  3. 1.5. Compound Assignment Operators

    1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...

  4. CSA 1.1.4 Compound Assignment Operators Flashcards

    This is often referred to as "adding two strings". compound assignment operator. Performs two tsks in one step; it performs a mathematical calculation followed by an assignment. count--. count equals count minus 1. count++. count equals count plus 1. Increment and Decrement Operators. ++, increases the value of a variable by one.

  5. Compound assignment operators in Java

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

  6. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Assignment statements initialize or change the value stored in a variable using the assignment operator =. An assignment statement always has a single variable on the left hand side.

  7. Topic 1.4 Understanding Compound Assignment Operators and Increment

    Topic 1.4 Understanding Compound Assignment Operators and Increment/Decrement Operators in Java. ... Compound assignment operators in Java allow you to perform an arithmetic operation and assignment in a single step. They help make your code shorter and often easier to read. Here are the compound assignment operators we'll cover:

  8. Compound Assignment Operators

    Definition. Compound assignment operators are shorthand notations that combine an arithmetic operation with the assignment operator. They allow you to perform an operation and assign the result to a variable in a single step. congrats on reading the definition of Compound Assignment Operators. now let's actually learn it. ok, let's learn stuff.

  9. Compound Assignment Operators

    Review 1.4 Compound Assignment Operators for your test on Unit 1 - Primitive Types. For students taking AP Computer Science A.

  10. 1.4

    You asked for it, so here it is: more operators! Wait...you didn't ask for more operators? Well, what am I supposed to do with them all?00:00 - Intro00:13 - ...