Check double value null or not(if double value set

2019-07-18 10:17发布

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

标签: java null double
2条回答
对你真心纯属浪费
2楼-- · 2019-07-18 11:01

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

查看更多
爷的心禁止访问
3楼-- · 2019-07-18 11:08

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.

查看更多
登录 后发表回答