Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
- Question: What is the index of
Brighton
in the following array?Answer: 2.String[] skiResorts = { "Whistler Blackcomb", "Squaw Valley", "Brighton", "Snowmass", "Sun Valley", "Taos" };
- Question: Write an expression that refers to the string
Brighton
within the array.
Answer:skiResorts[2]]
.
- Question: What is the value of the expression
skiResorts.length
?
Answer: 6.
- Question: What is the index of the last item in the array?
Answer: 5.
- Question: What is the value of the expression
skiResorts[4]
?
Answer:Sun Valley
- Exercise: The following program,
WhatHappens
, contains a bug. Find it and fix it.Answer: The program generates a// // 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); } } }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 withnew StringBuffer()
as follows:ThisHappens
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); } } }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.