Wednesday, 25 April 2018

Core Java: Increment/Decrement

Java supports these unary arithmetic operators: increment (++) and decrement (--) for all numeric primitive types (byte, short, char, int, long, float and double, except boolean).
 
Operator
Description
Example
++
Increment the value of the variable by 1.
x++ or ++x is the same as x += 1 or x = x + 1
int x = 5;
x++; // x is 6
++x; // x is 7
--
Decrement the value of the variable by 1.
x-- or --x is the same as x -= 1 or x = x – 1
int y = 6;
y--; // y is 5
--y; // y is 4
Operatr
Description
Example
++var
Pre-Increment
Increment var, then use the new value of var
y = ++x;
same as x=x+1; y=x;
var++
Post-Increment
Use the old value of var, then increment var
y = x++;
same as oldX=x; x=x+1; y=oldX;
--var
Pre-Decrement
y = --x;
same as x=x-1; y=x;
var--
Post-Decrement
y = x--;
same as oldX=x; x=x-1; y=oldX;
 
For examples,
 
x = 5;
System.out.println(x++);  // Print x (5), then increment x (=6). Output is 5. (x++ returns the oldX.)
 
x = 5;
System.out.println(++x);  // Increment x (=6), then print x (6). Output is 6. (++x returns x+1.)
 
Prefix operator (e.g, ++i) could be more efficient than postfix operator (e.g., i++)?!

No comments:

Post a Comment

Please write your view and suggestion....