Java OCA OCP Practice Question 1572

Question

This question may be considered too advanced for this exam.

What will the code shown below print when compiled and run with the following command line?.

java Main self
interface Printable  {
   void print (String a);
}

public class Main  {
   public static void main (String [] args){
       Printable x = null;/* ww w. java 2s .co  m*/
       if (args.length () > 0){
          x = new Printable (){
             public void print (String s){
                for (int i=0; i<s.length; i++){
                  System.out.println ("shot  : "+s.charAt (i));
                 }
              }
           };
        }

        if (x  != null){
          x .print (args [0]);
        }
    }
}

Select 1 option

  • A. It will not compile because interface Printable cannot be instantiated.
  • B. It will print shot:4 times, one at each line.
  • C. It will print "shot : s", "shot : e", "shot : l", "shot : f" one by one on 4 lines.
  • D. It will compile but will throw an exception at runtime.
  • E. None of these options is correct.


Correct Option is  : E

Note

For A.

An anonymous inner class that implements Printable interface is being created.

For C.

This would be correct, if args.length () is changed to args.length and s.length to s.length ().

For E.

Read the question carefully.

'args' is an array and length is an attribute (not a method) of arrays.

's' is a String and there is no attribute length in a String but a method length().

Expect questions that try to confuse by adding misleading statements.




PreviousNext

Related