-1

Does JVM understand that these two lines in Method are logically connected and execute them line by line. Or is there a slight possibility that these lines could be swapped and a NullPointerException thrown?

This Question is about a single threaded program.

   public void foo(Object object) {
      if(object == null) System.out.println("Oops!");
      if(object.list == null) System.out.println("Oops!");
    }

EDIT:

public void foo(Object object) {
  if(object == null) return;
  if(object.list == null) System.out.println("Oops!");
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Erwin Engel
  • 103
  • 1
  • 7

1 Answers1

2

Multithreading or not the JVM would never swap those two lines that would be pretty bad to say the least.

That being said your (original) code can throw a NPE:

if(object == null) System.out.println("Oops!");
if(object.list == null) System.out.println("Oops!");

since in the second if the object can be null. But I guess you are just using the method to prove a point. Better would have been the following:

public void foo(Object object) {
    ....
    else if(object == null) System.out.println("Oops!");
    else if (object.list == null) System.out.println("Oops!");
}

Your current example:

public void foo(Object object) {
   if(object == null) return;
   if(object.list == null) System.out.println("Oops!");
}

does not have the same issue.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117