Java Certification Question (20111003)

Q1

QUESTION: What happens when you attempt to compile and run these two files in the same directory?

 

//File P1.java

package MyPackage;

class P1{

void afancymethod(){

System.out.println(“What a fancy method”);

}

}

//File P2.java

public class P2 extends P1{

public static void main(String argv[]){

P2 p2 = new P2();

p2.afancymethod();

}

}

 

A. Both compile and P2 outputs “What a fancy method” when run.

B. Neither will compile.

C. Both compile but P2 has an error at run time.

D. P1 compiles cleanly but P2 has an error at compile time.

Answer: D

Noticed that these two files said to be in the same directory, but second file didn’t have package declaration while first file have. Therefore, P2 will prompt error at compile time.

Q2

What will be the output of the following code?

 

public class Sample {

 

public String getCountryName(){

return “USA”;

}

 

public StringBuffer getCountryName(){

StringBuffer sb = new StringBuffer();

sb.append(“UK”);

return sb;

}

 

public static void main(String[] args){

Sample s = new Sample();

System.out.println(s.getCountryName().toString());

}

}

 

A. Compile with error

B. USA

C. UK

D. Runtime Exception

Answer: A.

Java allows overloading method, meant with same method name, but having different parameters. However, Java does not allow overloading method with different returned types if the parameter list is the same. Because you see, it is contradicted themselves.

Q3

What will be the result of attempting to compile and run the following code?

 

abstract class MineBase {

abstract void amethod();

static int i;

}

public class Mine extends MineBase {

public static void main(String argv[]){

int[] ar = new int[5];

for(i=0;i < ar.length;i++)

System.out.println(ar[i]);

}

}

 

A. A sequence of 5 0’s will be printed.

B. Error: ar is used before it is initialized.

C. Error: Mine must be declared abstract.

D. IndexOutOfBoundes Error

Answer: C.

The answer is C, Mine must be declared abstract, or Mine must implements the method abstract void method().

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

One thought on “Java Certification Question (20111003)”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.