Search code examples
javanew-operator

Calling function on new keyword


This is my code:

import java.util.Date;

class basic {
    public static void main(String[] args) throws IOException {
        String s = new Date().toString();
        System.out.println(s);
        System.exit(0);
    }
}

Can anyone please explain to me in complete detail, how the line new Date().toString(); gets executed by the JVM. I am not really interested in how new allocates a heap, but how can we use the .toString() operator on constructor Date(). Thanks in Advance.


Solution

  • new Date().toString(); is interpreted by Java's compiler as (new Date()).toString(). Which is the same as Date a = new Date(); a.toString();