Check double value null or not(if double value set in Bean class)

核能气质少年 提交于 2019-12-10 22:35:12

问题


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



来源:https://stackoverflow.com/questions/16747391/check-double-value-null-or-notif-double-value-set-in-bean-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!