What is the result of the following program?
1:public class Main { 2: public static void addToInt(int x, int amountToAdd) { 3: x = x + amountToAdd; 4: } 5: public static void main(String[] args) { 6: int a = 15; 7: int b = 10; 8: Main.addToInt(a, b); 9: System.out.println(a); 10: } 11:}
B.
The code runs, so D and E are incorrect.
The value of a is not changed by the addToInt method, because only a copy of the value from a is passed into the parameter x. Therefore, a does not change.
Java always passes parameters by value.
public class Main { public static void addToInt(int x, int amountToAdd) { x = x + amountToAdd; /*from w w w.j a va 2 s. c o m*/ } public static void main(String[] args) { int a = 15; int b = 10; Main.addToInt(a, b); System.out.println(a); } }
The code above generates the following result.