Java OCA OCP Practice Question 1365

Question

Consider the following class...

public class Main {
   int i;//from w ww. jav  a  2s  .c o  m

   public Main(int i) {
      this.i = i;
   }

   public String toString() {
      if (i == 0)
         return null;
      else
         return "" + i;
   }

   public static void main(String[] args) {
      Main t1 = new Main(0);
      Main t2 = new Main(2);
      System.out.println(t2);
      System.out.println("" + t1);
   }
}

What will be the output of the following program?

Select 1 option

  • A. It will throw NullPointerException when run.
  • B. It will not compile.
  • C. It will print 2 and then will throw NullPointerException.
  • D. It will print 2 and null.
  • E. None of the above.


Correct Option is  : D

Note

The method print()/println() of OutputStream takes an Object and prints out a String by calling toString () on that object.

As toString() is defined in Object class, all objects in java have this method.

So it prints 2 first.

The second object's toString () returns null, so it prints "null".

There is no NullPointerException because no method is called on null.

Now, the other feature of print/println methods is that if they get null as input parameter, they print "null".

They do not try to call toString () on null.

So, if you have,

Object o = null; 
System.out.println(o); 

will print null and will not throw a NullPointerException.




PreviousNext

Related