I have the following example code:
int pay = 80;
int bonus = 65;
System.out.println(pay + bonus + \" \" + bonus + pay);
could someone please ex
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".
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.
first is plus operator
and last is concat operator
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)
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
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));