Alex. Liu
Alex. Liu

Reputation: 59

How does below Java code work? Is it a kind of the implicit type conversion?

I saw the following Java code in one project:

SimpleDateFormat dtFormater = new SimpleDateFormat("EEE, MMM dd");
long dt = weatherDataPerDay.getLong(JSON_KEY_DATETIME);
String result = dtFormater.format(dt * 1000).toString();

Firstly, above code works. I checked the definition of SimpleDateFormat and all its predecessors but didn't find a method like format(long time).

I only got 2 methods that accepted 1 parameter. They were

So far as I know, Java only supports the implicit type conversion among the numeric data types and only from small data type to big data type.

So I can't explain why above code works.

Upvotes: 1

Views: 42

Answers (2)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

As you already have noticed, the class SimpleDateFormat has 2 methods format: format(Object object) and format(Date date). Here as dt is a long, dt * 1000 will be a long too and thanks to autoboxing, it will be automatically converted as an instance of the wrapper class Long such that it will finally call format(Object object) with our Long instance as parameter.

The method format(Object object) will call behind the scene DateFormat#format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition) which only accepts as stated into the javadoc a Number or a Date as type of the parameter obj otherwise an IllegalArgumentException is thrown.

And when the parameter obj is of type Number which is the case here as Long is sub-class of Number, it automatically creates a new Date instance with new Date(((Number)obj).longValue()) which means that it excepts the Number to be a total amount of the milliseconds since January 1, 1970, 00:00:00 GMT.

Upvotes: 1

Roberto Attias
Roberto Attias

Reputation: 1903

consider this program:

public class A {
  public static void f(Object o) {
    System.out.println(o.getClass().getName());
  }

  public static void main(String[] args) {
    f(1);
  }
}

The output is java.lang.Integer. The compiler is seeing that you're passing a primitive value to a method receiving an object. It therefore "boxes" the primitive type into its Object counter part, so the int becomes an Integer. As Integer is an Object, the new instance can be happily passed to the method.

Upvotes: 1

Related Questions