Given the following code, what will be the result? public class Test {
Given the following code, what will be the result?
public class Test {
public static void main(String[] args) {
Object obj = new String("Hello");
String str = (String) obj;
System.out.println(str);
}
}
Show answerHide answer
Correct answer: (C) Hello will be printed.
Explanation
obj actually refers to a String object, so the downcast (String) obj succeeds at run time and "Hello" is printed. ClassCastException occurs only when the object is not of the target type.