Issue
While practicing Java I randomly came up with this:
class test
{
public static void main(String arg[])
{
char x='A';
x=x+1;
System.out.println(x);
}
}
I thought it will throw an error because we can't add the numeric value 1 to the letter A in mathematics, but the following program runs correctly and prints
B
How is that possible?
Solution
In Java, char is a numeric type. When you add 1 to a char, you get to the next unicode code point. In case of 'A', the next code point is 'B':
char x='A';
x+=1;
System.out.println(x);
Note that you cannot use x=x+1 because it causes an implicit narrowing conversion. You need to use either x++ or x+=1 instead.
Answered By - Sergey Kalinichenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.