Check double value null or not(if double value set

2019-07-18 10:30发布

问题:

I have created a Java bean class like this

class BeanDemo
{
private double value;

//getter and setter
}

class myApp
{
BeanDemo beanDemo=new BeanDemo();

int val=7;
if(val<5)
{
   beanDemo.setValue(23.456);
}

double value=beanDemo.getValue(); // Always returns 0.0 if it is not set
System.out.println(value);
}

How can I check if that value is null? I mean if it is not set I should print something else(say null)

I cannot check if its 0.0 because may be i can set the value to 0.0 also.

Thanks

回答1:

It sounds like you should be using Double (the class) rather than double (the primitive). There's no such thing as a null value of type double:

class BeanDemo {
    private Double value;

    public void setValue(Double value) {
        this.value = value;
    }

    public Double getValue() {
        return value;
    }
}

class Test {
    public static void main(String[] args) {
        BeanDemo beanDemo = new BeanDemo();
        int val=7;
        if (val < 5) {
            beanDemo.setValue(23.456);
        }
        Double value = beanDemo.getValue(); // value will be null
        System.out.println(value);
    }
}

Note that you could make your setter take double instead of Double if you wanted to prevent it from becoming null again after being set once.



回答2:

Use Double instead of double, this will do exactly what you want



标签: java null double