Number wrapper classes in Java
java
Solution
Firstly you can just use the primitive types:
int x = 12;
double d = 3.3456;
Secondly, you can optionally use the object wrappers for those numbers:
Integer x = new Integer(12);
Double d = new Double(3.3456);
Third, if you want the string representation you can do this simply with:
String s = Integer.toString(12);
or just:
int x;
String s = "x = " + x;
or even `printf()` like syntax:
int x = 12;
String s = String.format("x = %d", x);
Lastly, Java since version 5 has supported auto-boxing and unboxing, which may confuse you if you're not expecting it. For example:
Integer i = 1234; // autoboxes int to Integer
and
int i = new Integer(1234); // autounboxes Integer to an int
Just use the primitive types unless you need the `Number` wrappers. The most common reason to use them is to put them in collections (`List`s, etc).
Problem
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.