File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array , string buffer question  " Watch "array , string buffer question  " New topic

array , string buffer question

Yuan Tseng

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

Joined: Aug 20, 2001
Posts: 1824

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.

Java API Documentation
The Java Tutorial
Yuan Tseng

Joined: Mar 11, 2003
Posts: 21
Thanks Joel & Layne for responding so quickly.
I agree. Here's the link:
subject: array , string buffer question
It's not a secret anymore!