Reputation: 11
I am writing java code and want to know why the output of this code is x
. I was expecting t
since it is the 5th letter.
public class StringBufferDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer("ttsttxctlltnt");
System.out.println(sb.charAt(5));
}
}
Upvotes: 0
Views: 207
Reputation: 3442
It's because in java a StringBuffer
object is indexed starting at 0. 1st char at position 0, 2nd char at position 1, etc...
String ------ "t t s t t x c t l l"
ArrayIndex -- 0 1 2 3 4 5 6 7 8 9
Upvotes: 2
Reputation: 507
the index starts at 0 so the the character at 5 th posistion is x ... if u want t as the output then try the following
System.out.println(sb.charAt(4));
Upvotes: 1
Reputation: 595
The index starts from 0 and not 1. Hence in the string "ttsttxctlltnt", the character at position 5(0,1,2,3,4,5) i.e 'x' will be printed.
Upvotes: 1