Operators
Java Program to Demonstrate Assignment Operators
A Java program to demonstrate the usage of assignment operators.
Problem Description
Write a Java program to demonstrate the usage of assignment operators (=, +=, -=, *=, /=, %=).
Code
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c);
c += a; // c = c + a
System.out.println("c += a = " + c);
c -= a; // c = c - a
System.out.println("c -= a = " + c);
c *= a; // c = c * a
System.out.println("c *= a = " + c);
a = 10;
c = 15;
c /= a; // c = c / a
System.out.println("c /= a = " + c);
a = 10;
c = 15;
c %= a; // c = c % a
System.out.println("c %= a = " + c);
}
}Output
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5Explanation
=: Simple assignment.+=: Add and assign.-=: Subtract and assign.*=: Multiply and assign./=: Divide and assign.%=: Modulus and assign.
Try Yourself
- Compound Loop: Use
+=inside a loop to sum numbers from 1 to 10. - Implicit Casting: Try
byte b = 10; b += 5;. Does it work? Now tryb = b + 5;. Why does one work and the other fail? - String Append: Use
+=with a String variable to build a sentence word by word. - Order of Operations: If
a = 5, what isa *= 2 + 3? Is it(5 * 2) + 3or5 * (2 + 3)? - Brain Twister: Can you use
^=to swap two integers without a temporary variable? (Recall the XOR swap).
