Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

reason for different outputs  RSS feed

 
sridevi chaluvadi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
can anyone please tell me the reason for the output for 4 codes. I am confused.................
1) 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;
}
}
output : 4
2)
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;
}
}
output : 1
3)
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
i[0] = 2;
i[0] *= 2;
}
}
output: 4
4)
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i = j;
}
}
output: 1
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I indicated in this thread, all Java method calls use pass by value semantics. This means that a parameter seen by a method is a copy of the argument that's passed in, and changing the value of a parameter does not affect any original argument variable.
Now, the tricky part is that arrays are objects, and it's references to objects that are passed by value -- i.e., you get a copy of a pointer to an object, not a copy of the object. So whereas assigning to the parameter "i" in change_i does nothing visible outside the method, assigning to the contents of i does have an observable effect.
Anyway, go read the campfire story on this topic. It does a better job than I've done here at explaining this.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!