Java OCA OCP Practice Question 689

Question

What will happen when the following program is compiled and run?

public class Main { 
   public String checkIt (String s){ 
       if (s.length () == 0  || s == null){ 
          return "EMPTY"; 
       } //from   w ww . jav a 2  s .  c  om
       else 
          return "NOT EMPTY"; 
   } 
     
   public static void main (String [] args){ 
        Main a = new Main (); 
        a.checkIt (null); 
   } 
} 

Select 1 option

  • A. It will print EMPTY.
  • B. It will print NOT EMPTY.
  • C. It will throw NullPointerException.
  • D. It will print EMPTY if || is replaced with |.


Correct Option is  : C

Note

Because the first part of the expression (s.length () == 0) is trying to call a method on s, which is null.

The check s == null should be done before calling a method on the reference.

For Option D.

In this case, replacing || with | will not make any difference because s.length () will anyway be called before checking whether s is null or not.

The right expression would be:

if ( s == null  || s.length () == 0)  {  ...  } 

|| being a short circuit expression, s.length () == 0 will not be called if s == null returns true.

Hence, no NullPointerException will be thrown.




PreviousNext

Related