-1

Hi I am new to Java please can anybody explain the following code. And I replaced int with the Date type but the d1 value doesn't changed. But why the date is only changing and how the setYear(100) is print as 2000.

public static void main(String args[]){
  Date d1 = new Date(99,11,31);
  Date d2 = new Date(99,11,31);
  changeDate(d1,d2);
  System.out.println("d1: "+d1+" \nd2: "+d2);
}
static void changeDate(Date d1, Date d2){
  d1.setYear(100);
  d2 = d1;
}

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

3 Answers3

0

Java is reference by value. That means that the d1 and d2 Date objects in your changeDate method are different from the ones used in your main method, because they are method-specific (they are created in the method, not outside of it).

To fix this, you could declare d1 and d2 as class-wide variables and using those instead of the date objects in your methods.

More information

Community
  • 1
  • 1
nbokmans
  • 5,492
  • 4
  • 35
  • 59
0
d1.setYear(100);

Does refer to the object directly via the reference. Even if a copy of the reference is passed in the parameters, it still is able to access the object.

The method setYear() will change the year of your Date object to 1900 + the parameter

That's why d1.setYear(100) is 2000 (1900 + 100)


Why is d2 still referring to the same object?

Because inside your changeDate method, only the copy of the reference has been changed, not the original one.

More info

Community
  • 1
  • 1
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
-2

You have declared two times the object d1:

 Date d1 = new Date(99,11,31);
 Date d1 = new Date(99,11,31);

Maybe the second Date object should be d2.

Neculoiu Vlad
  • 35
  • 1
  • 7