Exercises


Note

The solutions to these exercises are in Appendix B.

  1. Name four traits that arrays and objects have in common.

  2. Name two differences between arrays and objects.

  3. Objects are not passed as method arguments, but references to objects can be passed. When a reference is passed into a method, any changes made to the referenced object by the method should be visible to the method's caller. Write an application to demonstrate this.

    Your application will have two classes: Cat and Ager. The Cat class should have a single variable: an int called age. The Ager class should have a method whose signature is makeOlder(Cat kitty, int nYears). This method should add nYears to the age of the Cat object referenced by kitty. Your main method should go in the Ager class. It should create one instance of each class, set the cat's age, and then use the Ager's method to change the age. Your main should then print out the cat's new age, and verify that it really changed.

  4. What happens if you move the main method of the previous question from the Ager class to the Cat class?

  5. Write an application that causes a "null pointer exception" failure.

  6. What does the following application print out?

    public class Question {   static long x;   public static void main(String[] args)   {     Question q1 = new Question();     Question q2 = new Question();     q1.x = 10;     q2.x = q1.x + 20;     System.out.println("q1.x = " + q1.x);   } }




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net