Type conversion of int and string, java

前端 未结 5 618
借酒劲吻你
借酒劲吻你 2021-01-02 00:23

last exam we had the exercise to determine the output of the following code:

System.out.println(2 + 3 + \">=\" + 1 + 1);

My answer was <

5条回答
  •  醉话见心
    2021-01-02 00:39

    Because "adding" a string to anything results in concatenation. Here is how it gets evaluated in the compilation phase:

    ((((2 + 3) + ">=") + 1) + 1)
    

    The compiler will do constant folding, so the compiler can actually reduce the expression one piece at a time, and substitute in a constant expression. However, even if it did not do this, the runtime path would be effectively the same. So here you go:

    ((((2 + 3) + ">=") + 1) + 1) // original
    (((5 + ">=") + 1) + 1)       // step 1: addition      (int + int)
    (("5>=" + 1) + 1)            // step 2: concatenation (int + String)
    ("5>=1" + 1)                 // step 3: concatenation (String + int)
    "5>=11"                      // step 4: concatenation (String + int)
    

    You can force integer addition by sectioning off the second numeric addition expression with parentheses. For example:

    System.out.println(2 + 3 + ">=" + 1 + 1);   // "5>=11"
    System.out.println(2 + 3 + ">=" + (1 + 1)); // "5>=2"
    

提交回复
热议问题