Tuesday, 4 August 2009

Java Certification Question 0054

What will happen when you attempt to compile and run the following code?

public class Inc{

public static void main(String argv[]){

Inc inc = new Inc();

int i =0;

inc.fermin(i);

i = i++;

System.out.println(i);

}

void fermin(int i){

i++;

}

}

1) Compile time error
2) Output of 2
3) Output of 1
4) Output of 0


Answer 4:

4) Output of 0

The method fermin only receives a copy of the variable i and any modifications to it are not reflected in the version in the calling method. The post increment operator ++ effectivly modifes the value of i after the initial value has been assiged to the left hand side of the equals operator. This can be a very tricky conept to understand

No comments:

Post a Comment