Question

  1. float ff = 1.2f;
  2. Float fo = new Float(1.2f);
  3. double fg = 3.2d;
  4. Double fh = new Double(2.1d);

Can I use '=' between the (1) and (3) or between the (2) and (4)??

Was it helpful?

Solution

Yes.

  1. Makes a plain old data type (AKA a primitive type) called "float."
  2. Makes a Java Object called Float that holds that value that happens to be identical to (1)

Responding to the edit questions:

You will see

  1. "possible loss of precision" message if you try ff = fg.
  2. "incompatible types" if you try fo = fh.
  3. fg = ff will work fine (the float fits in a double).
  4. fh = fo will still give you an "incompatible types".

OTHER TIPS

Yes, 2 creates an Object.

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

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.

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

Yeah primitive types can't be NULL, Objects can. Also the Float object has a bunch of useful utility functions attached to it.

  1. With this declaration you have a primitive type float and assigned it a value. Primitive type is a datatype that is composed of no other datatype and it cannot be split furthur(to explain it simply). primitive is generally a builtin type.

  2. In this case you have created an object and internally it consists of smaller data types and also contains methods.

Main difference between primitive type float and object type is the primitive is simply a format for data and has no properties or methods.

3=1 will work fine, rest will not.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top