Java – How to Print Current Date

javatime

I want to print current date and time in java..This is the code I am trying from a java tutorial:

import java.util.*;
  
public class Date {
   public static void main(String args[]) {
       // Instantiate a Date object
       Date date = new Date();
        
       // display time and date using toString()
       System.out.println(date.toString());
   }
}

It compiles fine. But the output given is:

Date@15db9742

While i am expecting a output like this:

Mon May 04 09:51:52 CDT 2009

What is wrong with the code?

EDIT:
I tried to rename the class.. The editted code:

import java.util.*;
  
public class DateDemo {
   public static void main(String args[]) {
       // Instantiate a Date object
       Date d = new Date();
        
       // display time and date using toString()
       System.out.println(d.toString());
   }
}

This is how I compiled the code and ran:

sou@sou-linux:~/Desktop/java$ javac DateDemo.java

sou@sou-linux:~/Desktop/java$ java DateDemo

The output is:

Date@15db9742

Best Answer

Your class is a custom class that is producing the output given by Object.toString. Rename the class to something else other than Date so that java.util.Date is correctly imported

Related Question