Doubts about java.util.Date

1

Someone can explain to me what this will return:

java.util.Date date = new java.util.Date();
java.util.Date date1 = date;
java.util.Date date2 = (java.util.Date(date.clone()));
System.out.println(date==date1);
System.out.println(date==date2);
System.out.println(date.equals(date2)));
    
asked by anonymous 23.01.2017 / 23:21

1 answer

2

There are problems in two lines:

Nessa:

java.util.Date date2 = (java.util.Date(date.clone()));

The correct one is to make a cast to java.util.Date because clone() returns type Object :

java.util.Date date2 = (java.util.Date)date.clone();

and in this:

System.out.println(date.equals(date2)));

has an extra parenthesis, only remove the last.

Complete and trouble-free code:

java.util.Date date = new java.util.Date();
java.util.Date date1 = date;
java.util.Date date2 = (java.util.Date)date.clone();
System.out.println(date==date1); // saída: true
System.out.println(date==date2); // saída: false
System.out.println(date.equals(date2)); // saída: true

Example Online

In the site already has a question and answers that can clarify the reasons of the results obtained in the operations.

Reading:

23.01.2017 / 23:31