2

I'm trying to figure out why you can do

Integer name = 1245;

and not need an instance created like this

Integer name = new Integer(1245);

Is it possible to create a class that doesn't need an instance created? And if you can create a class like that, how would you do it? I'm looking for something like

AsDigits digits = 1245;

instead of having to do

AsDigits digits = new AsDigits(1245);
user207421
  • 305,947
  • 44
  • 307
  • 483
Mike Sraj
  • 81
  • 1
  • 4

1 Answers1

2

It is due to the Autoboxing. From the doc

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Also, Autoboxing cannot be done for user-defined type. You can check this answer

stinepike
  • 54,068
  • 14
  • 92
  • 112