Java - Assignment Operators

Java

In this tutorial we will learn about assignment operators in Java programming language.

We use the assignment operators to assign any value or result of an expression to a variable.

In the following example we are assigning integer value 10 to a variable points of int type.

int points = 10;

Shorthand Assignment Operators

Lets say, we have an int variable which is initially set to 10. Then we increase the value by 5 and assign the new value to it.

//declare and set value
int x = 10;

//increase the value by 5 and re-assign
x = x + 5;

Another way of writing the code x = x + 5 is by using the shorthand assignment += as shown below.

//declare and set value
int x = 10;

//increase the value by 5 and re-assign
x += 5;

Following is the list of shorthand assignment operators.

Simple assignmentShorthand assignment
x = x + 1x += 1
x = x - 1x -= 1
x = x * (n + 1)x *= (n + 1)
x = x / (n + 1)x /= (n + 1)
x = x % yx %= y

Example

In the following example we are adding y to x and assigning the result to x.

class Assignment {
  public static void main(String args[]) {
    int x = 10;
    int y = 20;
    
    // add x and y and save the result in x
    x = x + y;
    
    System.out.println("Result: " + x);
  }
}

Output:

Result: 30

We can achieve the same result by using the += shorthand notation.

class Assignment {
  public static void main(String args[]) {
    int x = 10;
    int y = 20;
    
    // add x and y and save the result in x using shorthand notation
    x += y;
    
    System.out.println("Result: " + x);
  }
}

Output:

Result: 30

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT