Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0030 Examples of Pre-and Post- Increment and Decrement Operations

Initial Value of x Expression Final Value of y Final Value of x 5 y = x++ 5 6 5 y = ++x 6 6 5 y = x-- 5 4 5 y = --x 4 4 For example: x = 42; y = ++x; y is set to 43, because the increment occurs before x is assigned to y. Thus, the line y = ++x; is the equivalent of these two statements: x = x + 1; y = x; However, when written like this, x = 42; y = x++; the value of x is obtained before the increment operator is executed, so the value of y is 42. In both cases x is set to 43. The line y = x++; is the equivalent of these two statements: y = x; x = x + 1; The following program demonstrates the increment operator. public class Main { public static void main(String args[]) { int a = 1; int b = 2; int c = ++b; int d = a++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } } The output of this program follows: a = 2 b = 3 c = 3 d = 1