printing an int value right after a String value

前端 未结 9 1425
日久生厌
日久生厌 2021-01-27 06:00

I have the following example code:

int pay = 80;
int bonus = 65;
System.out.println(pay + bonus + \" \" + bonus + pay);

could someone please ex

相关标签:
9条回答
  • 2021-01-27 06:14

    The 1st pay and bonus in the println returns an integer. So it computes pay+bonus and returns it as an integer before printing it out.

    However, after the "". The + operation then becomes a concatenation of strings and everything after that is returned as a concatenated string. Hence, ("" + bonus + pay) would be returned as "6580".

    0 讨论(0)
  • 2021-01-27 06:15

    bonus and pay are both ints, and therefore going to be combined into a single int result.

    You need to insert an empty string between them.

    0 讨论(0)
  • 2021-01-27 06:16

    first is plus operator and last is concat operator

    0 讨论(0)
  • 2021-01-27 06:20

    Because, this is operator overloading issue. Here, First + is plus operator and last + is concat operator.

     System.out.println(pay + bonus + " " + bonus + pay);
                            |                     |
                          (plus)                (concat)
    
    0 讨论(0)
  • 2021-01-27 06:21

    what is surrounded by " " is referred to as a 'literal print' and gets printed exactly. The "+" sign is the concatenator operator and concatenates the string with the value that is stored in the variables. pay and bonus are declared as int, but is automatically converted to a String for the purpose of printing out.

    You can print an arithmetic expression within a System.out.print statement. Use parentheses around the arithmetic expression to avoid unexpected problems.

            System.out.println("ex" + 3 + 4);   // becomes answer 34
            System.out.println("ex" + (3 + 4));   // becomes answer 7
    
    0 讨论(0)
  • 2021-01-27 06:23

    As the others are saying the compiler is first adding the integer values and then printing the result, after " " the total value is changed to String type and after that + operator is functioning as a concat action. To not get that output, you can do this:

    System.out.println(String.valueOf(pay) + String.valueOf(bonus) + " " + String.valueOf(bonus) + String.valueOf(pay));
    
    0 讨论(0)
提交回复
热议问题