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.
Each Java primitive has a corresponding wrapper: boolean, byte, short, char, int, long, float, double.
What are Numeric Wrapper Classes? Byte, Short, Integer, Long, Float, and Double classes are numeric wrapper classes. They are all inherited from the Number class. The Number class is abstract.
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).
What you're looking at in the first example is called autoboxing / autounboxing. Java (starting with version 5) will automatically convert between 5
and Integer.valueOf(5)
, which constructs a wrapper of type Integer
from an int primitive. But the latter (Integer x = new Integer(12)
) is absolutely correct.
It doesnt work that way in the second case, however, if you wanted to write something like 5.toString()
. Autoboxing only occurs when assigning a primitive to a wrapper type, or passing a primitive where the wrapper type is expected, etc. Primitive types are not Objects and thus have no properties to be referenced.
Re: "why new", it's because all reference (non-primitive) types in Java are allocated dynamically, on the heap. So (autoboxing aside), the only way to get an Integer
(or other reference type) is to explicitly allocate space for one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With