File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String confusion

 
bala G
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
When I compile the following code it compiles ok
<code>class CharTest{
public static void main(String args[]){


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

System.out.println(s);
s.setCharAt(5,'A');
System.out.println(s);
}
}</code>
But when I run it I get the following runtime exception;Why is it?
'a'
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 5
at java.lang.StringBuffer.setCharAt(StringBuffer.java:345)
at CharTest.main(Compiled Code)

------------------
 
bill bozeman
Ranch Hand
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Bill
 
Rajpal Kandhari
Ranch Hand
Posts: 126
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Bala,
Here is my explanation:
Accoring to the API:
setCharAt
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."
Parameters:
index - the index of the character to modify.
ch - the new character.
Throws:
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
s.setCharAt(5,'A');
will work fine from 0 to 2 in place of 5.
you try your code by changing 5 from 0 to 2.


------------------
Regards,
Raj.
-------------------------
Afforts should be Appriciated.
-------------------------
 
bala G
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic