Assignment Operators Shorthand in Java

Introduction

In Java, assignment operators are used to assign values to variables. In addition to the simple assignment (=), Java provides shorthand assignment operators that combine arithmetic operations with assignment. These operators make the code shorter, cleaner, and easier to read. This tutorial explains the most commonly used assignment operator shorthands in Java.


Code: Assignment Operators Shorthand Example

public class AssignmentOperatorsExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition assignment
a += b; // Equivalent to a = a + b
System.out.println("After a += b, a = " + a);
// Subtraction assignment
a -= b; // Equivalent to a = a - b
System.out.println("After a -= b, a = " + a);
// Multiplication assignment
a *= b; // Equivalent to a = a * b
System.out.println("After a *= b, a = " + a);
// Division assignment
a /= b; // Equivalent to a = a / b
System.out.println("After a /= b, a = " + a);
// Modulus assignment
a %= b; // Equivalent to a = a % b
System.out.println("After a %= b, a = " + a);
}
}

Explanation of Each Code Part

1. Variable Declaration

int a = 10;
int b = 5;
  • Two integer variables a and b are declared and initialized.
  • a is assigned 10, b is assigned 5.

2. Addition Assignment (+=)

a += b; // a = a + b
  • Adds the value of b to a and stores the result in a.
  • Shorthand for a = a + b.

3. Subtraction Assignment (-=)

a -= b; // a = a - b
  • Subtracts b from a and stores the result in a.
  • Shorthand for a = a - b.

4. Multiplication Assignment (*=)

a *= b; // a = a * b
  • Multiplies a by b and stores the result in a.
  • Shorthand for a = a * b.

5. Division Assignment (/=)

a /= b; // a = a / b
  • Divides a by b and stores the result in a.
  • Shorthand for a = a / b.

6. Modulus Assignment (%=)

a %= b; // a = a % b
  • Calculates the remainder of a divided by b and stores it in a.
  • Shorthand for a = a % b.

Conclusion

Shorthand assignment operators in Java:

  • Combine arithmetic operations and assignment in a concise way.
  • Make the code easier to read and write.
  • Can be used with integers, floats, doubles, and other numeric types.

By using these operators, you can simplify arithmetic operations on variables and reduce repetitive code.


Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper