raj
raj

Reputation: 23

Java method calls

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?

Upvotes: 0

Views: 115

Answers (2)

asela38
asela38

Reputation: 4644

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

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

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.

Upvotes: 2

Related Questions