Java OCA OCP Practice Question 1542

Question

What is the result of compiling and running the following code ?

public class Main{
   static int si = 10;
   public static void main  (String args []){
      new Main ();
    }//  ww w .j  a v a 2s.co m
   public Main (){
      System.out.println (this);
    }
   public String toString (){
      return "Main.si = "+this.si;
    }
}

Select 1 option

  • A. The class will not compile because you cannot override toString() method.
  • B. The class will not compile as si being static, this.si is not a valid statement.
  • C. It will print Main@nnnnnnnn, where nnnnnnn is the hash code of the Main object referred to by 'this'.
  • D. It will print Main.si = 10;
  • E. None of the above.


Correct Option is  : D

Note

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

This method returns a string equal to the value of:.

getClass ().getName () +  '@' + Integer.toHexString (hashCode ())



PreviousNext

Related