printing an int value right after a String value

前端 未结 9 1426
日久生厌
日久生厌 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:31

    Your code is interpreting the expression from left to right.

    1. pay + bonus is interpreted as a mathematical function, so it adds the values to make 145. The + here is a plus operator.
    2. The moment you concatenate the " ", Java converts the expression into a String. The + here is a concatenate operator.
    3. Performing + pay converts pay to a String and concatenates it, because the expression is a String.
    4. Also doing + bonus converts bonus to a String and concatenates it, also because of the previous expression.
    0 讨论(0)
  • 2021-01-27 06:33

    First it adds the two variables and at last it concatinates as string because the integers are converted into strings

    For concatenation, imagine a and b are integers:

    "" + a + b
    

    This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) for concatenation

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

    before " ",pay and bonus as integer, added result is 145. after " ",bonus and pay as String,result is "6580"

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