public class example { int i = 0; public static void main(String args[]) { int i = 1; change_i(i); System.out.println(i); } public static void change_i(int i) { i = 2; i *= 2; } }
A. The program does not compile. B. The program prints 0. C. The program prints 1. D. The program prints 2. E. The program prints 4.
Can somebody explain why the value is 1 for this question
The method change_i() changes the value of the i locally (i.e. inside the method). The value is lost once we are outside the method and so the System.out.println(i) only sees the local value for i in the main() method which has a value of 1. To print the changed value from change_i() you need to return the new value :
public class example { int i = 0; public static void main(String args[]) { int i = 1; i = change_i(i); System.out.println(i); } public static int change_i(int i) { i = 2; i *= 2; return i; } }
Hope that makes sense ? Finner [ June 15, 2006: Message edited by: Finner Jones ]