In Java, how do you check if a float variable is empty?

It seems that when it comes to * value.getFloat ("Value_Quotient", quotient_Float) == null *, it is facing a problem. How to fix it?

private void Store() { quotient_Float = posture_error/time; if(value.getFloat("Value_Quotient", quotient_Float)==null || quotient_Float < value.getFloat("Value_Quotient", quotient_Float)) { editor.putFloat("Value_Quotient", quotient_Float); editor.commit(); } } 
+6
source share
3 answers

float is a primitive data type, not an object . For objects, a zero check is used. For primitives, you should use the default check. For float, the default value is 0.0f.

+19
source

There is also a Float class that you can use. A Float object can be tested for null as its object representation of a Float data type. The Float is represented by capitol F, and the data type Float has a small f. Java preforms autoboxing, which means that you can easily switch back and a quarter between two, that is:

 float number = 0.56f; Float object = number; 

Or vice versa:

 Float object = new Float(1.43); float number = object; 

You can also pass a Float object to a method where the Float data type is expected, or vice versa.

If checking the default value does not work for any reason, this will allow you to check Float for null.

 if (object != null) { // do what you want to do } 
+4
source

Some points that may be useful (Java 8).

A float can be assigned to a float primitive. Then the primitive float can be 0 checked as follows:

  Float floatObj = new Float(0); float floatPrim = floatObj; if (floatPrim == 0) { System.out.println("floatPrim is 0"); // will display message } 

However, if your Float is NULL, than assigning it a primitive will cause NPE

  Float floatObj = null; float floatPrim = floatObj; //NPE 

So be careful.

One more thing, apparently, you can use the == operator on the Float object, because outsourcing happens.

  Float floatObj = new Float(0.0f); if (floatObj == 0) { System.out.println("floatObj is 0"); // will work } 
0
source

Source: https://habr.com/ru/post/952664/


All Articles