File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question

 
Sherman Hung
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.print( v.i );
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.print(v.i);
System.out.print(i);
}//End of another
}
1) 10030
2) 20030
3) 209930
4) 10020
What is the correct answer?
I can understand 10 and 0 but 20. Is Java call by reference or call by value? Why it is not 30?
 
R K Singh
Ranch Hand
Posts: 5382
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All java calls are by value, i.e value is copied and passed to formal parameter of method.
In another() method when you change the value
v.i = 20;
it changes the value where v points and at that time it was pointing to ValHold object created in amethod().
hope this example will remove ur all doubt.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic