java double判断是否为空,检查double值是否为null(如果在Bean类中设置double值)

博客讨论了在Java中如何处理Bean类中double类型的属性为null的情况。建议使用Double类代替double原始类型,因为Double类允许值为null。通过这种方式,可以检查属性是否已设置。示例代码展示了如何在不设置值时打印null。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值