Sunday 1 September 2019

Java post-increment and pre-increment

Hi reader,


Welcome to my simple explanation on post and pre-increment in Java.


Let have the following,
int a = 100;

Post-Increment

int b = a++;// post increment, compute result first, then increment
System.out.println(b);//prints 100
//now a = 101

Pre-Increment

int c = ++a;//pre increment, increment first then compute result
//increment a from 101 to 102
System.out.println(c);//print 102

Sample code

public class Calculations {

public Calculations() {}

public static void main(String[] args) {

postAndPreIncrement();

} public static void postAndPreIncrement() {

int a = 100;
int b = a++;// post increment, compute result first, then increment
System.out.println(b);//prints 100

//now a = 101

int c = ++a;//pre increment, increment first then compute result

//increment a from 101 to 102
System.out.println(c);//print 102
}
}

1 comment: