aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String confusion" Watch "String confusion" New topic
Author

String confusion

bala G
Greenhorn

Joined: Jan 15, 2001
Posts: 6
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

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.
Bill
Rajpal Kandhari
Ranch Hand

Joined: Aug 26, 2000
Posts: 126
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.
-------------------------


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

Joined: Jan 15, 2001
Posts: 6
Thanks everyone
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String confusion