|
x is a variable in the program x = x + value ; // Add value to the variable x x = x - value ; // Subtract value to the variable x x = x * value ; // Increase the variable x by value times and so on... |
Java has a shorthand operator for these kinds of assignment statements
Operator symbol | Name of the operator | Example | Equivalent construct |
---|---|---|---|
+= | Addition assignment | x += 4; | x = x + 4; |
-= | Subtraction assignment | x -= 4; | x = x - 4; |
*= | Multiplication assignment | x *= 4; | x = x * 4; |
/= | Division assignment | x /= 4; | x = x / 4; |
%= | Remainder assignment | x %= 4; | x = x % 4; |
public class Shorthand1 { public static void main(String[] args) { int x; x = 7; x += 4; System.out.println(x); x = 7; x -= 4; System.out.println(x); x = 7; x *= 4; System.out.println(x); x = 7; x /= 4; System.out.println(x); x = 7; x %= 4; System.out.println(x); } } |
How to run the program:
|
1. x = x + 1; and 2. x = x - 1; x is a variable in the program |
Java has shorthand operators to increment and decrement a variable by 1 (one).
Operator symbol | Name of the operator | Example | Equivalent construct |
---|---|---|---|
++ | Increment | x++; | x = x + 1; |
-- | Decrement | x--; | x = x - 1; |
public class Shorthand2 { public static void main(String[] args) { int x; x = 7; x++; System.out.println(x); x = 7; x--; System.out.println(x); } } |
How to run the program:
|