0
import java.util.Date;
 public class Example {
 public static void main(String args[]) {
 Date d1 = new Date (99, 11, 31);
 Date d2 = new Date (99, 11, 31);
 method(d1, d2);
 System.out.println("d1 is " + d1+ "\nd2 is " + d2);
 }
 public static void method(Date d1, Date d2) {
 d2.setYear (100);
 d1 = d2;
 }
 }

The above code works fine. an output is

d1 is Fri December 31 00:00:00 GMT 1999
d2 is Sun December 31 00:00:00 GMT 2000

But when I use wrapper class like Integer in a simialr method the change is not reflected.why?

skaffman
405k96 gold badges825 silver badges775 bronze badges
asked May 19, 2011 at 7:00
3
  • show the code using Integers. Commented May 19, 2011 at 7:03
  • code Integer d1=new Integer(10); Integer d2=new Integer(20); meth(d1,d2); System.out.println("d1 is " + d1 + "\nd2 is " + d2);} public static void meth(Integer x,Integer y){ y=90;} Commented May 19, 2011 at 7:05
  • oh i dint know wrapper classes are immutable.Thanks amit. Commented May 19, 2011 at 7:09

2 Answers 2

2

Note that d1 doesn't get changed by that method, even 'though you assign d1 = d2. This is because the d1 inside the method is a copy of the reference stored in d1 in Main.

The only real modification you do is the call to setYear, which modifies the object referenced by d2.

Since Integer is immutable (i.e. Integer objects can't be changed once they are created), there is no way to do a manipulation like this. Simply assigning a new value to d1 or d2 inside the method will have no effect on d1 and d2 inside main.

All of this might get less confusing when you call the parameters of your method differently from your variables in main. That would make it clearer that they are not related in any way.

answered May 19, 2011 at 7:07
Sign up to request clarification or add additional context in comments.

Comments

0

Integer wrapper is immutable so there is no way you can do any modification to that object

answered May 19, 2011 at 7:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.