Handling of Chracter in Java -
this question has answer here:
i came across case in java prints character ascii. if try print 2 character prints sum of there ascii value.
system.out.println('c'); =>> c system.out.println('a'+'b'); =>> 195 (97+98)
just want know why in second case prints sum of there ascii value
behind scenes, compiler acting smart , replacing char + char
int constant value.
in first case println(char)
called , in second case println(int)
called
sample code :
public static void main(string[] args) { system.out.println('a'); system.out.println('a' + 'b'); // compiler first "resolves" expression 'a'+'b' (since char cannot added added ints) , tries call correct `println(int)` method. }
byte code:
public static void main(java.lang.string[]); descriptor: ([ljava/lang/string;)v flags: acc_public, acc_static code: stack=2, locals=1, args_size=1 0: getstatic #16 // field java/lang/system.out:ljav /io/printstream; 3: bipush 97 // single char. (pushed byte int) 5: invokevirtual #22 // method java/io/printstream.prin ln:(c)v 8: getstatic #16 // field java/lang/system.out:ljav /io/printstream; 11: sipush 195 // push sum of 2 chars short 14: invokevirtual #28 // method java/io/printstream.prin ln:(i)v 17: return
Comments
Post a Comment