Multiple choice technology programming languages

  1. public class Test { 2. public static void main(String args[]) { 3. class Foo { 4. public int i = 3; 5. } 6. Object o = (Object)new Foo(); 7. Foo foo = (Foo)o; 8. System.out.println(“i = “ + foo.i); 9. } 10. } What is the result?

  1. i = 3

  2. Compilation fails.

  3. A ClassCastException is thrown at line 6.

  4. A ClassCastException is thrown at line 7.

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

The code compiles and runs successfully. A Foo object is created, upcast to Object type, then downcast back to Foo. Since the actual object is a Foo instance, the downcast succeeds and foo.i is accessible, printing 'i = 3'. This is a valid casting pattern in Java.