Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
static void inc(int n) {
n++;
}
public static void main(String[] args) {
int x = 1;
inc(x);
System.out.println(x);
}
}1
- Expecting
2: Java passes arguments by value, sonis a copy ofx, andn++changes only the copy, which vanishes whenincreturns. - Expecting a compile error: a parameter is an ordinary local variable and may be changed; the change only never reaches the caller's variable.
- How would you change
incso thatmaingets the new value? - Does Java pass arguments by value or by reference?