Doubt about java.util.Date

Asked

Viewed 77 times

0

Can anyone 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)));
  • The way it is 2 errors! 2 lines have problems in this java.util.Date date2 = (java.util.Date(date.clone())); and in that System.out.println(date.equals(date2)));

  • 1

    and to make no mistake I would have to stay as?

  • I decided to write an answer and also explain the problems.

1 answer

2


There are problems in two lines:

In that:

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

it is right to make a cast for java.util.Date because clone() returns the type Object:

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

and in that:

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

have an extra parentheses, just 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

Online Example

In itself site already has a question and answers which may explain the reasons for the results obtained in the operations.

Reading:

  • and he knows me to say what will return ??

  • Edited .... @Stinrose, in the online example also has the answers!

  • I think it’s true, false, false... I’m right ?

  • @Stinrose I edited and put a link to read on the outputs.

  • 1

    Yes I get it ! Thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.