aspose file tools*
The moose likes Beginning Java and the fly likes array , string buffer question  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array , string buffer question  " Watch "array , string buffer question  " New topic
Author

array , string buffer question

Yuan Tseng
Greenhorn

Joined: Mar 11, 2003
Posts: 21
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

Joined: Aug 20, 2001
Posts: 1815
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


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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


Java API Documentation
The Java Tutorial
Yuan Tseng
Greenhorn

Joined: Mar 11, 2003
Posts: 21
Thanks Joel & Layne for responding so quickly.
Yuan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: array , string buffer question
 
Similar Threads
Stringbuffers
Inner Thread Classes
Line Feed Carriage Return problem
Question about Strings
StringBuffer