Java: sum of two integers being printed as concatenation of the two

前端 未结 10 1914
忘了有多久
忘了有多久 2020-12-03 19:41

Consider this code:

int x = 17;
int y = 013;
System.out.println(\"x+y = \" + x + y);

When I run this code I get the output 1711. Can anybod

相关标签:
10条回答
  • 2020-12-03 19:59

    Numbers prefixed with 0 are octal. 13 Octal is 11 decimal.

    The x + y call treats both paramters as strings, so you are combining the string "17" and "11".

    0 讨论(0)
  • 2020-12-03 19:59

    everyone mentioned 0 makes the number octal.
    I just want to add that 0x makes it hexadecimal

    0 讨论(0)
  • 2020-12-03 20:00

    013 is ocatal ... convert it to decimal and you will get 11. Have a look here for an explanation of the octal system.

    0 讨论(0)
  • 2020-12-03 20:04

    I would just add to Reed's explanation that 013 is interpreted as Octal 13, which is decimal 11.

    0 讨论(0)
提交回复
热议问题