• Home
  • Java Assignment Operators with Examples

Java Assignment Operators with Examples

In Java, assignment operators are used to assign a value to a variable. There are several types of assignment operators:

  1. Simple assignment operator (=): This operator is used to assign a value to a variable. For example:

int x = 10;

Here, the value 10 is assigned to the variable x.

  1. Compound assignment operators (+=, -=, *=, /=, %=): These operators are used to perform an operation on the variable and then assign the result to the same variable. For example:

int x = 10; x += 5;

Here, the value of x is first increased by 5 and then assigned to x. The value of x is now 15.

  1. Ternary operator (? :): This operator is used to assign a value to a variable based on a condition. For example:

int x = (y > 10) ? 20 : 30;

Here, if the value of y is greater than 10, the value 20 is assigned to x. Otherwise, the value 30 is assigned to x.