In Java, you can cast char
to int
and vice-versa, using the char value or the ASCII value. If you cast an int variable to a char, you get the corresponding character. So, the following snippet will print 'a':
int x = 97;
System.out.println( (char)x ); // 'a'
But when I do this:
char ch = 'a', ch2 = 97, ch3 = 'b';
System.out.println( ( (ch+=1) > ch2 ) ? (char)ch2 : (int)ch3 );
the compiler prints out the int value 97, not 'a', even though the ternary operator return value on the 'true side' is (char)ch2. So I expected 'a' instead of 97. Why does it print 97 instead of 'a'?
The problem is that in:
System.out.println( ( (ch+=1) > ch2 ) ? (char)ch2 : (int)ch3 );
because you have (int)ch3
the compiler assumes that the returning type of the ternary operator will be an int
.
Check the following highlighted rule from 15.25. Conditional Operator? :
If you do
System.out.println( ( (ch+=1) > ch2 ) ? (char)ch2 : (char)ch3 );
it will print
'a'
Alternatively, you can apply brute-force ie cast the final result into char
as shown below:
System.out.println( (char) (( (ch+=1) > ch2 ) ? (char)ch2 : (int)ch3 ));
it will also print
'a'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.