1
public class Bar {

 private Foo m_foo;

 private int getNumbers(){
   m_foo=new Foo();
   return 5;
 }


 public void test1(){
   m_foo.print(getNumbers());
 }
}

public class Foo {

 public void print(int x){
   System.out.println(x);
 }
}

public class Main {
  public static void main(String args[]){
  new Bar().test1();
 }
}

The NullPointerException occurs in test1()call, but I can't understand the reason behind. Isn't the m_foo supposed to be instantiated in the getNumbers() which should get evaluated first?

JohnLXiang
  • 168
  • 6
  • Have you looked at the byte-code? – Hovercraft Full Of Eels Feb 27 '20 at 04:10
  • 2
    You may find [this related](https://stackoverflow.com/questions/6800590/what-are-the-rules-for-evaluation-order-in-java) question helpful. In short, Java generally evaluates statements left-to-right, and so `m_foo` is resolved before the call to `getNumbers()` – Brian Feb 27 '20 at 04:10
  • Create the m_foo in the no argument CTor. You started using it way too early :-) – Geek Feb 27 '20 at 04:12
  • @Geek That is not really relevant to this question. The OP is asking about a niche case of the order of evaluation of expressions within a statement. You're nitpicking the semantics of the hypothetical code they are using to give an example of this issue. – Brian Feb 27 '20 at 04:16

1 Answers1

0

NullPointer occurs at

m_foo.print(getNumbers());

because m_foo is initialized in getNumbers method, and it is never got called before calling test1.

Java executes statement in a sequence from left to right. So first it will check for m_foo object. Ideal way to do this in a constructor of Bar.

public Bar(){
    m_foo=new Foo();
 }
Hemant Metalia
  • 25,838
  • 17
  • 67
  • 86
  • This is more or less a restatement of what the OP already stated in their question. As mentioned, the OP expects `m_foo` to be initialized by `getNumbers` within `test1` prior to the call to `m_foo.print`. Their question is why this isn't the case, not why a NPE occurs at all. – Brian Feb 27 '20 at 04:13
  • @Brian yes, but my purpose was just to explain in a different way so that it can be understood, – Hemant Metalia Feb 27 '20 at 04:16