<< Java's Game Changing Move: The First Step | Home | The Death Of An iPod >>

Friday Java Quiz: Finally And Explicit Return

Just as I was ready to leave for the weekend, David asked a Java question on his way out. And I'll make it a Friday Java quiz. Again, as usual, answer the question without the help of the Java compiler.

Q: What will the following program print?

public class Foo {
  public static void main(String[] args) {
    try {
      System.out.println(1024);
      return;
    } catch (RuntimeException e) {
      System.out.println(2048);
    } finally {
      System.out.println(4096);
    }
  }
}
Tags :


Re: Friday Java Quiz: Finally And Explicit Return

1024 4096

Re: Friday Java Quiz: Finally And Explicit Return

Another question could be: What will the following code do?
public class Main {
            
    public static void main(String[] args) {
        new Main();
    }
    public Main() {
        IPerson p = new Test();
        test(p);
        p = new PhysicsStudent();
        test(p);
        
        p = new Student();
        test(p);
        
        p = new Teacher();
        test(p);
        System.out.println("-------------");
        test(new Test());
        test(new PhysicsStudent());                
        test(new Student());
        test(new Teacher());
    }
    
    public void test(IPerson p) {
        System.out.println("IPerson:" + p.toString());
    }
    
    public void test(Student p) {
        System.out.println("Student:" + p.toString());
    }
    
    public void test(Teacher p) {
        System.out.println("Teacher:" + p.toString());
    }
    
    public void test(PhysicsStudent ps) {
        System.out.println("PhysicsStudent:" + ps.toString());
    }
    
    
    interface IPerson {
        String toString();
    }
    
    class PhysicsStudent extends Student {        
        public String toString() {
            return "PhysicsStudent";
        }
    }
    
    class Student implements IPerson {        
        public String toString() {
            return "Student";
        }
    }
    
    class Teacher implements IPerson {
        public String toString() {
            return "Teacher";
        }
    }
    
    class Test implements IPerson {
        public String toString() {
            return "Test";
        }
    }
}

Re: Friday Java Quiz: Finally And Explicit Return

1024
4096

Re: Friday Java Quiz: Finally And Explicit Return

The frist four should prefixed with IPerson, The next four should prefixed with it's own class name, that's IPerson, PhysicsStudent, Student, Teacher

Add a comment Send a TrackBack