I am new to java.I was trying with the following code:-
The output that I am getting is
Now last day, I learned that Wrapper classes are objects.So no is an object but its not behaving like one.I am new to OOP and java and I don't have a clue whats happening.Please help.
I dont find any complicated stuff here. You are passing mv object to function valueChanger and setting its x variable value to 200. If you are confused between int and Interger go ahead read about Boxing (auto-Boxing)
Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Joined: Mar 20, 2009
Actually my question was why the value of no is not getting changed to 100 like the x variable of the mv object.
It *is* being changed--inside the method that's changing it. But you're doing different things: one statement sets the reference to a new value. One sets a member of a reference to a value. Try setting "mv" itself to a new value--what happens in the caller?
Yeah.It doesn't reflect in the main class then.But it is getting confusing.What is the rule then.If I pass an object and change the value of its member, then it would reflect outside, in the caller class and if I pass an object and change what it refers to,then it won't reflect?Is this the rule?Thank you very much for your reply.
Joined: Mar 05, 2009
Hi Rahul, I dint understand your question properly at the beginning. Have a look at following.
in the caller class and if I pass an object and change what it refers to,then it won't reflect?Is this the rule?
Try modifying your class as follows
And modify method like follows
In method valueChanger, you are changing content of object MyValue and you are reassigning 'no' to 100. Since you are reassigning 'no', change dint appear in calling method.
Now see in method valueChanger, I am doing mv = new MyValue(30,40); which is not at all affecting output.
Joined: Mar 20, 2009
Thank you for your reply.I did exactly this and got this output after getting the reply from David.The change in reference of the object does not reflect in the caller method.Now,like I posted before, what is the rule in java in such situations?If I change the object reference inside a method and make it refer to another(of course a compatible one), it won't reflect outside the method in which I am doing it but if I change the value of its members,then it would reflect?What if a member is an object itself?And if this is the rule, then why?I thought objects were passed by reference in java. I am really confused.Please help.