• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Explanation Required

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anybody explain that why it produce the output 10050 why noy not 10010
?

class Valhold{
public int i=10;
}
public class Obparam {
public static void main(String s[]){
Obparam o=new Obparam();
o.amethod();
}
public void amethod(){
int i =99;
Valhold v=new Valhold();
v.i=30;
another(v,i);

System.out.println(v.i);
}
public void another(Valhold v,int i)
{
i=0;
v.i=50;
Valhold vh=new Valhold();
v=vh;
System.out.println(v.i);
System.out.println(i);
}
}
 
Ranch Hand
Posts: 242
Mac Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi AtulKumar Gaur

It's because

1.public void amethod(){
2.int i =99;
3.Valhold v=new Valhold();
4.v.i=30;
5.another(v,i);
6.
7.System.out.println(v.i);
8.}

v is still pointing to the object created at line 3

And for that you have chnged value in method another() by using its reference copy.. i.e. in line 4 in below snippet

1.public void another(Valhold v,int i)
2.{
3.i=0;
4.v.i=50;
5.Valhold vh=new Valhold();
6.v=vh;
7.System.out.println(v.i);
8.System.out.println(i);
9.}

That's why you are getting 50 not 10 for line 7 in method amethod()..

Regards..
 
Ranch Hand
Posts: 1609
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because in java even the references are actually passed by value.

"Valhold v" in "amethod()" and Valhold v in "another()" are two different references to the same object, and that "Valhold v" parameter in function "another()" is a reference which remains local to the function.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

If this link could help:

Pass By Value & Pass By Reference


Thanks,
 
A feeble attempt to tell you about our stuff that makes us money
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic