简体   繁体   中英

System.out.println( '3' + 0 );

So if you run the statement above System.out.println( '3' + 0 );

you get 51 as the output.

If you run another similar statement,

System.out.println(  3  + '0' );

you get the same result, which is 51.

However, if you run the third statement,

System.out.println( '3' + '0' )

then you get 99 as the result.

Can anyone explain what exactly is going on behind these three results?

当您在''中放入0之类的数字时,您将返回ASCII / unicode值0,在这种情况下为48,这就是为什么将3加到'0'时得到51的原因。

Because of this:

char c = '0';
int ascii = (int) c; // ASCII of '0' is 48
System.out.println( 3 + ascii);

the ascii code of '3' is 51. when you add an integer 0 to it the result is 51 and it is printed. similarly the ascii code of '0' is 48 and you are adding 3 to it... but when you add '3' and '0' both in ascii format its adding 48 and 51 and hence the output is 99. this happens because of implicit type conversion in java.

When you use System.out.println( '3' + 0 ); or System.out.println( 3 + '0' ); here is a type switch, char 0 menas int 48, so '3' + 0 means 51 + 0 = 51 so does 3 + '0' .

So '3' + '0' means 51 + 48 = 99 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM