Wednesday, 5 August 2009

Java Certification Question 0055

What will happen when you attempt to compile and run the following code?


public class Agg{

static public long i=10;

public static void main(String argv[]){

switch(i){

default:

System.out.println("no value given");

case 1:

System.out.println("one");

case 10:

System.out.println("ten");

case 5:

System.out.println("five");

}

}

}

1) Compile time error
2) Output of "ten" followed by "five"
3) Output of "ten"
4) Compilation and run time error because of location of default



Answer 1:

1) Compile time error

This might be considered a "gocha" or deliberate attempt to mislead you because i has been given the data type of long and the parameter must be either a byte, char, short or int. If you attempt to compile this code with JDK 1.2 you will get an error that says something like "Incompatible type for switch, Explicit cast needed to convert long to int. Answering with option 2 would have been reasonable because if the parameter had been an integer type the lack of break statements would have caused this output. If you gave either of the answers you should probably revise the subject.

No comments: