E.g.
import java.util.*;
public class mainXX {
public static void main(String args[]){
System.out.println(new Date());
}
}
If I run this code I’m creating a new Date object but not calling any methods, it only calls the default constructor, which looks like this:
public Date() {
this(System.currentTimeMillis());
}
How does the System.out.println end up printing a string date (Tue Sep 27 12:04:42 EST 2011) from this declaration as a constructor can’t return a value?
I know this is a simple question but I can’t figure out what is happening. Thanks, m
You are correct that constructors themselves do not return values, but the expression formed by applying the new operator to a constructor “call”, does produce a value.
In other words
newis an operator. The expressionnew C ( args )invokes the constructorCon the given arguments. The result of thenewexpression is the newly constructed object. It is thenewoperator, not the constructor, that is producing the value. (I’m being technical and saying “producing” instead of “returning” because I think that is in the spirit of your question.)ADDENDUM
By way of further explanation: Constructors, do not actually “return” objects the way methods do. For example:
The methods
getX,getY, andtoStringreturn values, so when used in an expression like thisa value is returned.
The constructor has no return statement. More importantly you don’t call it directly. That is you cannot say
That would be an error. Instead, you use a “new-expression” which has the form
newapplied to the constructor name applied to an argument list. This invokes the constructor and produces a new object. For example:The right hand side is a newly created point object. All I was pointing out is that nothing is returned from the constructor itself; you have to apply the
newoperator to get the point object.Because the
newexpression produces an object, we can apply methods directly to it. The following are all acceptable:As other answerers have pointed out, in Java when you use an object in a context where a string is expected, the
toString()method is automatically called. Sowould actually print
(4,3).