Java Double getting initialized to 0.0

2019-03-03 05:15发布

问题:

I have a bean where I have a field "CustAmount "which is double, I tried testing the bean and i dont seem to understand this: When i run on my local machine it gets initialized to 0.0 when instantiated. When i run the same code in my linux test environment it remains null. due to which there is a difference in the retrieved data meaning if i send the CustAmount as null to my Backend i get some data but if i send the CustAmount as 0.0 the query is done on the basis of 0.0 and sends me nothing back.

How is this possible if the code is same, By any chance is it possible that when i do new MyBean() compiled in java 1.5 the double remains null and in 1.6 it gets initialized to 0.0.

I dont know if this is something that happens in two Java versions but thats the only difference on my end.

Thanks for any hint.

Adding code snippet :

public class MyBean {

private double custAmount;

    public void setCustAmount(double custAmount) {
        this.custAmount = custAmount;
    }
public double getCustAmount() {
        return custAmount;
    }

}

And I just do

MyBean mybean =  new MyBean();

its not a Double but a double. Syed..

回答1:

A Java double field will be default initialized to 0.0. A Java Double field will be default initialized to null. These two facts will be true no matter what version of Java you use, and no matter what environment you run it in.


If you are seeing different behavior in different environments, then the most likely explanation is that you are executing DIFFERENT code in the respective environments (or calling the same code in different ways). Posting some code that exhibits the problem may point to some other problem, but I doubt it.


Based on your posted code, it is IMPOSSIBLE for custAmount to be null. In the case where you are seeing a null, you must be EITHER using a different version of that code, OR the null must be coming from some other source.



回答2:

I had a similar problem. I thought my Long initializes to 0. But it wasn't initialized itself, but from the <p:selectOneMenu /> on my page.

            <p:selectOneMenu value="#{myBean.myLongValue}">
                <f:selectItem value="#{null}" itemValue="#{null}" itemLabel="-" />
                <f:selectItems ... />
            </p:selectOneMenu>

So, try to check your page, if you are not setting it somehow from your form.



标签: java double