1

There is a function get() that return a value if it is there in ArrayDeque otherwise returns null i.e x can be some value or null. If get() returns x then function B() should perform some computations otherwise should not do anything.

T get()
{
    //compute x
    return x;
}

void B()
{
     int z;
     if(y.get()!=null)
     {
          z=y.get(); // gives null pointer exception
          .....
     }
}

The problem is that y.get() already returns the value which is not assigned to any variable, thus gives null pointer exception. If i use something like if((z=y.get()) != 0) it gives exception in cases when x is null. How can i achieve this functionality?

7
  • How can you return null and assign it to the int variable z ?? Its type mismatch. Commented Mar 13, 2012 at 6:19
  • Neither of the versions you write should throw, unless it's get itself that throws. Are you sure you're looking at the right part of your code? Commented Mar 13, 2012 at 6:19
  • Thats why i put that check in if condition. Commented Mar 13, 2012 at 6:20
  • So, does get() return T, or an Integer? B() seems to assume that it's an Integer. Commented Mar 13, 2012 at 6:20
  • y.get() will throw a null pointer only if y is null...or may be some logic inside your get() is throwing an exception... Commented Mar 13, 2012 at 6:20

1 Answer 1

4

I suspect this is an ArrayDeque<Integer>, right?

When you have:

int z = y.get();

That's like saying:

int z = ((Integer) y.get()).intValue();

Just use:

Integer z = y.get();

instead. Then you can test whether z is null. On the other hand, if y.get() has already returned a non-null value, I'm surprised if it's then returning a null value - you'd expect it to return the same thing twice, right? Are there other threads involved?

Additionally, it's not clear what you mean by this:

The problem is that y.get() already returns the value which is not assigned to any variable, thus gives null pointer exception.

I don't see where the "thus" in here... it's fine to call a method and not store the return value in a variable. If that's throwing a NullPointerException, it would really suggest that y is null. Of course, all of this would be easier to diagnose if you would post a short but complete program demonstrating the problem.

As an aside, it's not clear why you're calling y.get() twice in the first place. I would restructure the code to:

void B()
{
     Integer z = y.get();
     if (z != null)
     {
         // Use z
     }
}

Do you really want to call it twice?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.