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 StringBuffer class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer class " Watch "StringBuffer class " New topic

StringBuffer class

shailendra vasale
Ranch Hand

Joined: Dec 17, 2000
Posts: 38
hi Guys,
Here is a program using StringBuffer class.The problem i came across is :
1. When there is no space between the double quotes [StringBuffer str = new StringBuffer("");],the program throws an error java.lang.StringIndexOutOfBoundsException for "for loop2" after j=0.
2. When there is single space,then "for loo2" throws exception after j=1.
3. And when the space is more than 3,the program runs successfully.
Can anybody plz throw a light on this.
import java.util.*;
public class ForLoop
Vector myStockSymbols;
Vector myStockValues;
private static char c[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
public ForLoop()
myStockSymbols = new Vector();
myStockValues = new Vector();
for(int i=0;i<10;i++)
System.out.println("for loop1 "+i);
StringBuffer str = new StringBuffer("");
for(int j=0;j<4;j++)
System.out.println("for loop2 "+j);
myStockValues.addElement(new Float(Math.random()*100f));
for(int k=0;k<10;k++)
System.out.println("for loop3 "+k);
System.out.println(" "+myStockSymbols.elementAt(k)+" "+myStockValues.elementAt(k));
public static void main(String[] args)
ForLoop loop = new ForLoop();

deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
Hi Shailendra,
in above line j is the index of the StringBuffer.
and when there is no value in the StringBuffer (i.e. StringBuffer contains "").so the StringIndexOutOfBoundsException is thrown.
again when StrinBuffer str = " " one space then loop tuns fine for index 0. but when it comes to index 1 then again there will be String...BoundsException.
and since u r running your lop only 4 times i.e. only 0,1,2,3 indexes will be looked for so whenever the str has length >3 i.e. 4/5/6......
the loop will run properly

shailendra vasale
Ranch Hand

Joined: Dec 17, 2000
Posts: 38
hi Deekasha,
Thankx for ur reply.I got the point where i was confused.
I tried the same using "StringBuffer str = new StringBuffer("abcd");",it works fine.
I agree. Here's the link:
subject: StringBuffer class
It's not a secret anymore!