Reputation: 27
This program complies but won't run successfully, I am unable to find the bug.
public class Q1 {
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);
}
}
}
Upvotes: 0
Views: 188
Reputation: 5042
IN the statement:
StringBuffer[]stringBuffers = new StringBuffer[10];
you have just created an array of 10 elements. But you have not put any element in it.Each element in this array is still empty and by default, contains null
.
So when you called
stringBuffers[i].append("StringBuffer at index " + i);
here stringBuffers[i]
is still uninitialized and is pointing to null
.
So it is giving java.lang.NullPointerException.
As stated in other answers, if you do like this:
for(int i =0; i< stringBuffers.length;i++){
stringBuffers[i] = new StringBuffer();
This will initialize each element of stringBuffer array with the reference to a StringBuffer object.So stringBuffer[i] now is not empty.
By the way You should use StringBuilder. Both StringBuffer and StringBuilder provides mutable strings. Use StringBuffer only if your application is running in multithreading environment becoz it introduces performance overhead
Upvotes: 1
Reputation: 1325
You need to init the StringBuffer:
public class Q1 {
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);
}
}
}
Upvotes: 2
Reputation: 213261
You need to initialize the StringBuffer
objects in your array with the required String: -
for(int i =0; i< stringBuffers.length;i++){
stringBuffers[i] = new StringBuffer("StringBuffer at index " + i);
}
Upvotes: 1
Reputation: 382160
You don't initialize your stringbuffers
.
You should have something like
for(int i =0; i< stringBuffers.length;i++){
stringBuffers[i] = new StringBuffer();
or
for(int i =0; i< stringBuffers.length;i++){
stringBuffers[i] = new StringBuffer("StringBuffer at index " + i);
Upvotes: 6