Im coming from PHP world and im so confused about how to think when you declare objects in java.
so when traditionally you do like this:
Rectangle rect = new Rectangle();
cause rect is a Rectangle datatype.
According to the java tutorial page a number wrapper class is a subclass to Number.
So its a class but when you instantiate it the tutorial did it like this:
Integer x;
x = 12;
Why isn´t it like this like the traditional way:
Integer x = new Integer(12);
or
Integer x = new Integer();
And here is another example:
String s = new Integer(i).toString();
So here s is a String object. that i get. But you got new Integer(i). Why new? What does it mean here and what happens when it sends ‘i’ to the constructor. Where can i see what the constructor is doing with the parameters in java API?
Many questions, but couldnt find sources on the net explaining it.
Firstly you can just use the primitive types:
Secondly, you can optionally use the object wrappers for those numbers:
Third, if you want the string representation you can do this simply with:
or just:
or even
printf()like syntax:Lastly, Java since version 5 has supported auto-boxing and unboxing, which may confuse you if you’re not expecting it. For example:
and
Just use the primitive types unless you need the
Numberwrappers. The most common reason to use them is to put them in collections (Lists, etc).