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

前端 未结 10 2015
忘了有多久
忘了有多久 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:50

    The 17 is there directly.

    013 is an octal constant equal to 11 in decimal.

    013 = 1*8 + 3*1 = 8 + 3 = 11
    

    When added together after a string, they are concatenated as strings, not added as numbers.

    I think what you want is:

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

    or

    System.out.println("x+y = " + (x + y));
    

    Which will be a better result.

提交回复
热议问题