0

Please explain me why am i getting an output 1234567 7654321

I want to know what exactly is happening here.

public static void main(String[] args) {
  Date date = new Date(1234567);
  m1(date);
  System.out.print(date.getTime() + " ");

  m2(date);
  System.out.println(date.getTime());
}

public static void m1(Date date) {
  date = new Date(7654321);
}

public static void m2(Date date) {
  date.setTime(7654321);
}
Bruno Carletti
  • 273
  • 1
  • 3
  • 18

1 Answers1

0

What you do in m1 is make the variable date point at a new object. But this variable exists only inside the scope of the method m1. The date variable inside your main method is a different one.

This is your code just with renamed variables

public static void main(String[] args) {
  Date var1 = new Date(1234567);
  m1(var1);
  System.out.print(var1.getTime() + " ");

  m2(var1);
  System.out.println(var1.getTime());
}

public static void m1(Date parameter) {
   parameter = new Date(7654321);
}

public static void m2(Date parameter) {
  parameter.setTime(7654321);
}

As you can see your method m1 only changes the value of parameter, not of the original var1. This method doesn't access the object which the variable parameter is pointing at but instead makes the variable point at a new object which has nothing to do with the object which was passed from var1.

m2 is not creating a new object. It is accessing the object which the variable parameter points at and calls the setTime(...) function to change attributes of the object. Since the object of parameter and var1 is still the same here, var1 later references the object which has been modified and the changes are "visible" to you.

It is a common miss assumption of young oop developers that objects and variables are one and the same. Objects are instances of classes created into the ram of your computer. Variables are just simply referencing those objects (accessing them through their memory address) and reading/writing from their memory. The same object can be referenced by multiple variables tho

// here both variables are pointing at the same object
Date var1 = new Date();
Date var2 = var1;

// this change is done to one object, referenced by both variables
var1.setTime(180128);
// Since both point at the same object, the output is exactly the same
System.out.println(var1);
System.out.println(var2);

// now we point var2 at a different object, the same one as var3
Date var3 = new Date();
var2 = var3;

// Var1 will still be the same as before. But var2 will match var3
System.out.println(var1);
System.out.println(var2);
System.out.println(var3);

So you see variables are not the same thing as objects. And a parameter of a method is also just another variable which points at the object that was passed to the method when it was called. Changing the object it is pointing at does not do any changes to the object it originally was pointing at.

Basti
  • 1,117
  • 12
  • 32