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

help!!  RSS feed

 
sridevi chaluvadi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
why the output is 1 for the following code?
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;
}
}

thanks in advance
 
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
You should read the JavaRanch Campfire Story about "pass by value". If you understand this story, you'll be able to answer your own question. If you still don't, you can come back here and ask questions in this thread.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
inside the main method, the array delcared there "hides" the other one.

re-write your code like this and it's a little more obvious:

temp is a copy of the reference to the array. 'i' from main points to the actual array, as does temp. the line "temp = j" changes where temp points to, but doesn't do ANYTHING to i, or what i points to.
you might want to look
here for a better explanation.
 
Priya Sri
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai sridevi,
u have to know that there are two types of parameter passing
techniques. if u pass by value, the parameter change won't reflect in the main function.
That's why u are getting 1 instead of 2.
 
sridevi chaluvadi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest, Fred and Lakshmi
Thanks for ur help. I will go through the topic "Pass by value"
regards,
sridevi
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!