What will be the output of the following program?
class IncDec{
public static void main(String s[]){
int a=1,b=2,c,d;
c = ++b;
d = a++;
c++;
System.out.println(“a = ” + a);
System.out.println(“b = ” + b);
System.out.println(“c = ” + c);
System.out.println(“d = ” + d);
}
}
A)
B)
C)
Program does not compile.
D)
a = 2
b = 3
c = 4
d = 2a = 2
b = 3
c = 4
d = 1a = 1
b = 2
c = 4
d = 2a = 1
b = 3
c = 4
d = 2
Execution of program starts from main. Four integer variables a, b, c, d are declared among which a, b are initialized to 1, 2 respectively. Variable c is assigned to ++b which is ++2 = 3. Now value of both c, b becomes 3 (since pre increment). Variable d is assigned to a++ which is 1++ = 2. Now value of d becomes 1 and a becomes 2. c++ performs increment but value is reflected for next usage of c(since post increment). The four display statements print the values as follows:
a = 2
b = 3
c = 4 (next usage after increment of c is here in display statement)
d = 1