float ff = 1.2f;
Float fo = new Float(1.2f);
double fg = 3.2d;
Double fh = new Double(2.1d);
Can I use '=' between the (1) and (3) or between the (2) and (4)??
float ff = 1.2f;
Float fo = new Float(1.2f);
double fg = 3.2d;
Double fh = new Double(2.1d);
Can I use '=' between the (1) and (3) or between the (2) and (4)??
Yes. The first declares a variable of the primitive type float
and initializes it to 1.2.
While the second declares a variable of the reference type Float
, creates an object of type Float
and then assigns a reference to the variable.
Yes.
Responding to the edit questions:
You will see
ff = fg
.fo = fh
.fg = ff
will work fine (the float fits in a double).fh = fo
will still give you an "incompatible types".Yes, first one is a primitive type and second is a boxing class which wraps capabilities of primitive float type, we need second for example for use in the collections. Before you have had to deal a lot with type conversion (I think until Java 1.5) now the existence of wrappers classes takes those capabilities. More information. here
Yeah primitive types can't be NULL, Objects can. Also the Float object has a bunch of useful utility functions attached to it.
new Float(1.2f) creates a new Float object every time, consuming memory.
If you use factory method Float.valueOf(1.2f) JVM may reuse existing Float object instances for the same value. It could create a new object instance only if there isn't already a Float instance with the same value.
Usually you'll want to use Float.valueOf(1.2f) instead of new Float(1.2f).
Also note that primitives and objects work differently with equals operator ==.
float x1 = 1.2f;
float x2 = 1.2f;
x1 == x2 // true
Float f1 = new Float(1.2f);
Float f2 = new Float(1.2f);
f1 == f2 // false
In real applications I suggest you not use float or Float, its not very accurate and almost never the right solution, use double or Double instead.