Erwin Chen
Erwin Chen

Reputation: 11

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?

Upvotes: 0

Views: 212

Answers (4)

lqhcpsgbl
lqhcpsgbl

Reputation: 3782

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.

Upvotes: 0

Subhankar Biswas
Subhankar Biswas

Reputation: 11

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.

Upvotes: 1

John Castleman
John Castleman

Reputation: 1561

Because of this:

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

Upvotes: 1

Cody Anderson
Cody Anderson

Reputation: 124

When you put numbers like 0 inside ' ' you are returning the ASCII/unicode value of 0 which in this case is 48 which is why when you add 3 to '0' you get 51.

Upvotes: 1

Related Questions