-1
final DateFormat dateFormat = DateFormat.getDateTimeInstance() ;
    GregorianCalendar time = new GregorianCalendar();
    GregorianCalendar limit = time;
    limit.add(GregorianCalendar.HOUR_OF_DAY, 4);

    String timeForm = dateFormat.format(time.getTime());
    String limitForm = dateFormat.format(limit.getTime());
    System.out.println(timeForm);
    System.out.println(limitForm);

The output should be the time "now" followed by the time after 4 hours.

When it prints out, both timeForm and limitForm display the time after 4 hours. Why is that?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Gabby Cervantes
  • 85
  • 2
  • 10
  • There's only one instance there. A variable is not an instance, it's a reference to one. `GeorgianCalendar limit = time;` does not create a new instance of `GeorgianCalendar`, it just tells `limit` to reference the same object that `time` is referencing. – Vince Aug 19 '16 at 03:52

2 Answers2

1

You set the second calendar equal to the first instead of creating a second instance. So when you change the instance it affects both variables. If you make limit = new GregorianCalendar(); the output will show 2 different values

Aaron Davis
  • 1,731
  • 10
  • 13
1

You want to step back and read how Java is dealing with "reference types".

In other words: anything in Java that is some sort of Object (like GregorianCalendar objects) is identified via a reference.

And when you make an assignment like

limit = time;

then you are not creating another Object. You just have to two variables, time and limit, that both "point" to the very same object.

Thus when you use one variable and make a status-changing change on the reference object; of course the other variable "sees" those changes, too.

GhostCat
  • 137,827
  • 25
  • 176
  • 248