File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String confusion" Watch "String confusion" New topic

String confusion

bala G

Joined: Jan 15, 2001
Posts: 6
When I compile the following code it compiles ok
<code>class CharTest{
public static void main(String args[]){

StringBuffer s=new StringBuffer("'\u0061'");

But when I run it I get the following runtime exception;Why is it?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 5
at java.lang.StringBuffer.setCharAt(
at CharTest.main(Compiled Code)

bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
It is because you are using unicode equivalent of the letter a in your code and this is resolved at compile time. So when you created you string buffer you really said:
StringBuffer sb = new StringBuffer("a");
And then you tried to access the 5th element which there is no fifth element in the string buffer.
Rajpal Kandhari
Ranch Hand

Joined: Aug 26, 2000
Posts: 126
Hello Bala,
Here is my explanation:
Accoring to the API:
public void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch. The string buffer is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.
"The offset argument must be greater than or equal to 0, and less than the length of this string buffer."
index - the index of the character to modify.
ch - the new character.
IndexOutOfBoundsException - if index is negative or greater than or equal to length().

Keeping in mind above explanation:
The following line
StringBuffer s=new StringBuffer("'\u0061'");
is creating a StringBuffer object whose length is 3.
length() method Returns the length (character count) of this string buffer.
In StringBuffer( also in String) index start from 0. So your following line
will work fine from 0 to 2 in place of 5.
you try your code by changing 5 from 0 to 2.

Afforts should be Appriciated.

Regards,<P>Raj.<BR>-------------------------<BR>Afforts should be Appriciated.<BR>-------------------------
bala G

Joined: Jan 15, 2001
Posts: 6
Thanks everyone
I agree. Here's the link:
subject: String confusion
It's not a secret anymore!