• Post Reply Bookmark Topic Watch Topic
  • New Topic

Pass by value  RSS feed

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Example of pass by value:
public class Passbyvalue {

public static void main(String[] args) {

int a=15,b;

System.out.println("Value of a before call:"+a);
Value value = new Value();
value.meth(a);
System.out.println("Value of a after call:"+a);

}
}


public class Value {

void meth(int i){
i *= i;

}
}
Here the value of a remains as 15.
If i perform same operation with return value the value of a is changed.


public class Passbyvalue {

public static void main(String[] args) {

int a=15,b;

System.out.println("Value of a before call:"+a);
Value value = new Value();
value.meth(a);

b= value.meth(a);
System.out.println("Value of a after call:"+b);
}
}


public class Value {

int meth(int i){
i *= i;
return i;
}
}
here value of a is changed to 255.It is pass by value and it changes the value.
Can you explain it HOW?
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nakuli Patidar wrote:

Here the value of a remains as 15.
If i perform same operation with return value the value of a is changed.


here value of a is changed to 255.It is pass by value and it changes the value.
Can you explain it HOW?

Where do you see that a has changed? the value of b gets set to 255, but if you actually printed a (you are printing b), you'll see it doesn't change.
 
Nakul P. Patel
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even after printing value of a:

a= value.meth(a);
System.out.println("Value of a after call:"+a);

the value of a is changed.

I request you all to run this code.

Please let me know if you have any idea.
 
Sheriff
Posts: 22845
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course the value of a is changed. Your code assigns it the value returned by the method, so it is completely unsurprising that it gets that value. This has nothing to do with parameter passing at all.
 
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nakuli



Try this instead.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nakuli Patidar wrote:

you've changed what you're doing here. "a" changes because you do some computation, and then reset "a" to that new value. if you had done this:

would you be surprised that "a" changed? No. What you should have done to see that "a" didn't change was this:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!