Reputation: 13
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?
Upvotes: 0
Views: 261
Reputation: 124275
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.
Upvotes: 1
Reputation: 7479
This works because of the implicit conversion. As you probably know, every character has it's ASCII number representation. For example, letter 'A' is number 64. When you write
sb.setCharAt(0, (char) (sb.charAt(0) + 1));
It automatically converts (implicitly) the character to integer because it needs to add 1 to it. So your result becomes 64+1 = 65.
After this, you explicitly call a typecast operator (char)
to convert the integer number of 65 to char it represents, and it's B.
Upvotes: 0
Reputation: 9963
sb.charAt(0)
is going to retrieve the first character. So sb.charAt(0) + 1
will add 1 to the first character (turning an A into a B, a B into a C, etc.). So, lets suppose the first character is an A. Then sb.charAt(0) + 1 == 'B'
so your method is sb.setCharAt(0, 'B')
, etc.
Upvotes: 0
Reputation: 201507
If the first character is an A
change the first character to a B
. Otherwise, set the first character to a C
. Your modified version
sb.setCharAt(0, (char) (sb.charAt(0) + 1));
would only work the same way for input of A
and B
respectively (because it increments the first character in the StringBuffer
).
Upvotes: 0