• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array , string buffer question

 
Yuan Tseng
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I got this question from Sun, and I don't understand that. Is anyone be kindly explained to me? Thanks in advance for all of your help.

//
// 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.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create an array of objects (non-primitives), it initializes all members to null. Thus, if you did:

you would get:
Item 1 is null
Item 2 is null
Item 3 is null
....
Item 10 is null
To put things into the array, you would have to create the StringBuffers manually:

This will result in
Item 1 is bob1
Item 2 is bob2
Item 3 is bob3
....
Item 10 is bob10
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you change the code as follows it will work:
Notice that after you create an array of objects, you also have to create instances of (or instantiate) objects to put into the array.
HTH
Layne
 
Yuan Tseng
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joel & Layne for responding so quickly.
Yuan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic