rekotc
rekotc

Reputation: 555

Integer object is correctly instantiated inside a method but comes back null

I'm experiencing a weird behaviour using a java method inside an EJB class.

I have a couple of Integer, declared as follows:

Integer decimalDigit = null;
Integer decimalExponent = null;

I pass them to the following method, along with other parameters.

public void GetPrecision(Currency cur, String nodeCode, Integer decimalDigit, Integer decimalExponent) {

    decimalDigit = new Integer(cur.getDecimalDigit());
    decimalExponent = new Integer(cur.getDecimalExponent());

    if (!CommonHelper.isNullOrEmptyOrBlank(nodeCode)) {

        Node tempNode = nodeListProvider.getNodeList().get(nodeCode);

        if (tempNode != null && tempNode.getDecimalDigit() != null) {
            decimalDigit = (int) tempNode.getDecimalDigit();
            decimalExponent = 0;
        }
    }
}

The 2 objects are correctly istantiated inside the method using the new operator and they stay like that until the end of the call but, as soon as i get out, the 2 variables are again null.

I cannot explain this behaviour, any hint?

Thanks in advance

Upvotes: 1

Views: 61

Answers (3)

SirVirgin
SirVirgin

Reputation: 153

You're referring to the local variables the scope of which ends with the method with these lines:

decimalDigit = new Integer(cur.getDecimalDigit());
decimalExponent = new Integer(cur.getDecimalExponent());

because you have declared them as your formal parameters.

Rewrite the method as such to solve the issue:

public void GetPrecision(Currency cur, String nodeCode, Integer a, Integer b) {

//method body   

}

It's bad practice to use identifiers like a and b but you get the problem.

Upvotes: 0

Rbk
Rbk

Reputation: 72

if cur.getDecimalDigit() and cur.getDecimalExponent() both yielded null,decimalDigit and decimalExponent will still come out null upon any subsequent value set.so check the cur.getDecimalDigit() and cur.getDecimalExponent() values.

Upvotes: 0

davidxxx
davidxxx

Reputation: 131486

Arguments are passed by value but the method receives a copy of the references, not directly the references of your Integer.
So any assignation of the parameters inside the method will not change the value referenced by the references you have passed.

Your method should rather return a structure instance (array or a custom class) that contains the two Integer.

Besides a method named GetPrecision() is expected to return something.

Upvotes: 1

Related Questions