• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

proble with wraper class

 
kavan desai
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends public class wrappertest{
void overWrite(Double d)
{
d=null;
d=new Double(7.0);

}
public static void main(String args[])
{
Double d=new Double (5.0);
wrappertest t=new wrappertest();
t.overWrite(d);
System.out.println(" "+d);

}
}
please solve my problem it is very basic but ... i have a dought the above given code should print 7.0 as object is passed by referance and we r assigning d to new refernce they why it showing me out put 5.0 instade of 7.0 can i get the out put like 7.0 please explain me how?
thanks
Kavan
Preaparing for Scjp 1.4.0
 
Carol Enderlin
drifter
Ranch Hand
Posts: 1364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

First, a bit of business: the javaranch Naming Policy requires that you use a real first and last name.

You could head over here to fix that.

Second, this is a great question for the
Programmer Certification (SCJP) forum. Maybe a kind bartender or sheriff will move this post over there.

Third, regarding your question... check out this info on how java passes by value

Javaranch FAQ on call by reference vs. value

pass by value article
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a nutshell, the main method instantiates object d, and will continue to hold a reference to it, no matter what is done in overWrite(). Even though overWrite() abandons it's reference to the Double object with a value of 5.0 and creates a new one with a value of 7.0, main() still holds the original reference with a value of 5.0.

This type of manipulation only works with mutable (changeable) objects. Since Double is immutable, the only way you can change it is to drop the reference and create a new one.

If the object passed as a parameter were a mutable object, such as a StringBuffer, overWrite could manipulate the object, and main() could see the results of that manipulation. However, it is impossible for a called method to make the calling method give up or replace it's reference to an object.
 
kavan desai
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Carol & Merrill for replying me actully i am bit new to this forum.
Thanks.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We're glad to have you stick around. Please change your name to match our standards, though, as that helps us to maintain a friendly atmosphere. Also, choose the forum carefully to increase your chances of getting a good and quick answer. The SCJP or the Java in General (Beginner) forums would have been perfect.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic