Check double value null or not(if double value set in Bean class)
17,007
Solution 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.
Solution 2
Use Double instead of double, this will do exactly what you want
Author by
Shiju K Babu
Java & Web UI Programmer Java, J2EE, Spring, Spring MVC, Hibernate, Angular, AngularJS, JavaScript, JQuery
Updated on June 17, 2022Comments
-
Shiju K Babu almost 2 years
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
-
Bohemian almost 11 years+1 for raw speed - not so much degree of difficulty :) Might as well add that it will print
null
as suggested by OP -
Alpesh Gediya almost 11 years@Jon, Double is wrapper class for double then Autoboxing feature need to take care of it, do not you think curious about internal stuff how its converting to nul.
-
Jon Skeet almost 11 years@AlpeshGediya: It's not converting anything to null. The value is null to start with.