The JavaTM Tutorial
Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Answers to Questions and Exercises: Arrays

Questions

  1. Question: What is the index of Brighton in the following array?
    String[] skiResorts = {
        "Whistler Blackcomb", "Squaw Valley", "Brighton",
        "Snowmass", "Sun Valley", "Taos"
    };
    
    Answer: 2.

  2. Question: Write an expression that refers to the string Brighton within the array.
    Answer: skiResorts[2].

  3. Question: What is the value of the expression skiResorts.length?
    Answer: 6.

  4. Question: What is the index of the last item in the array?
    Answer: 5.

  5. Question: What is the value of the expression skiResorts[4]?
    Answer: Sun Valley

Exercises

  1. Exercise: The following program, WhatHappens (in a .java source file), contains a bug. Find it and fix it.
    //
    // This program compiles but won't run successfully.
    //
    public class WhatHappens {
        public static void main(String[] args) {
            StringBuffer[] stringBuffers = new StringBuffer[10];
    
            for (int i = 0; i < stringBuffers.length; i ++) {
                stringBuffers[i].append("StringBuffer at index " + i);
            }
        }
    }
    
    Answer: The program generates a NullPointerException on line 6. The program creates the array, but does not create the string buffers, so it cannot append any text to them. The solution is to create the 10 string buffers in the loop with new StringBuffer() as follows: ThisHappens (in a .java source file)
    public class ThisHappens {
        public static void main(String[] args) {
            StringBuffer[] stringBuffers = new StringBuffer[10];
    
            for (int i = 0; i < stringBuffers.length; i ++) {
    	    stringBuffers[i] = new StringBuffer();
                stringBuffers[i].append("StringBuffer at index " + i);
            }
        }
    }
    

Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.