StringBuffer sb=new StringBuffer("A");
Now to increment the letter A I have written below code-
if (sb.charAt(0)=='A') {
sb.setCharAt(0, 'B');
} else {
sb.setCharAt(0, 'C');
}
But somewhere I read that this can be done with below code as well (and it worked!)
sb.setCharAt(0, (char)(sb.charAt(0) + 1));
Can somebody explain the above code?
When you do char + int
char
is interpreted as int
which represents index of used char in Unicode Table.
So when you execute sb.charAt(0) + 1
it is same as 'A' + 1
and is evaluated as 65 + 1
which equals 66
(and character indexed with that value in Unicode Table is B
).
Now since setCharAt
expects as second argument char
you must (cast) that int
to char
which gives you back 'B'
and sb.setCharAt(0, ..)
simply sets up that character at position 0
of in your StringBuffer.