System.out.println ("Hello" + 6 + 10); prints Hi610?

Why is he doing this? So confuuuusing.

+4
source share
7 answers

Priority and associativity of operators.

Two points:

  • The + operator concatenates strings if one or both arguments are strings.
  • The + operator works from left to right.

So, in your example, "Hi"+6 is "Hi6" , and "Hi6"+10 is "Hi610" .

EDIT: as you say in the comment to another answer: if the numbers are the first, then the numeric addition is performed first, because the leftmost two operands are numbers. Then only at the end does the string concatenate. Thus, we get "16Hi" .

+17
source

This is just a matter of priority. "Hi"+6+10 allowed ("Hi"+6)+10 . Because "Hi"+6 then concatenated as the string "Hi6" to which 10 is concatenated again to get "Hi610"

To achieve what you expect, simply specify the priority correctly using curly braces:

 System.out.println("Hi" + (6 + 10)); 
+3
source

"6" and "10" are forced into strings.

Do you want "Hi 16"? In this case, try System.out.println("Hi " + (6+10));

+2
source

In order of operations, this is equivalent to System.out.println(("Hi"+6)+10) . At this point, the Java rules indicate that to add “Hi” and 6, you convert both operands to a string and concatenate, getting System.out.println("Hi6" + 10) , where “Hi6” + 10 are added according to the concatenation again to give System.out.println("Hi610") that will output Hi610 to standard output.

+2
source

Because it converts integers to string. This is just how java string concatenation works.

There is extensive documentation on this subject. You can read it.

If you do 6 + 10 + Hello, you will get 16Hi. If you want to add integers, use parentheses.

+1
source

6 and 10 are accepted as ints, which are converted to String using +. So you type: string + int (tostring) + int (tostring)

http://ideone.com/a3vuH

Did you expect anything else?

+1
source

You run a single overloaded operator in Java - + - and the rules when it means that (concatenating or adding a string) are not immediately obvious, but very clearly defined.

As always, when priority rules are not intuitive, use parentheses:

 System.out.println("Hi " + (6+10)); 
0
source

All Articles