开发者

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

W开发者_JAVA技巧hy does it do this? So confuuuusing.


Operator precedence and associativity.

Two points:

  • Operator + does string concatenation if one or both arguments are Strings.
  • Operator + works from left to right.

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

EDIT: As you say in a comment to another answer: If the numbers are first, then a numeric addition is done first, because the leftmost two operands are numbers. Then, only at the end, a string concatenation occurs. So that yields "16Hi".


Its just a matter of precedence. "Hi"+6+10 resolves to ("Hi"+6)+10. Since "Hi"+6 is then concatenated as a string "Hi6", to which 10 is again concatenated to get "Hi610"

To achieve what you are expecting just specify the precedence correctly using braces:

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


The "6" and the "10" are being coerced into strings.

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


By order of operations, this is equivalent to System.out.println(("Hi"+6)+10). At this point, the rules of Java state that to add "Hi" and 6 you convert both operands to string and concatenate, yielding System.out.println("Hi6" + 10), where "Hi6" + 10 are added according to concatenation again to give System.out.println("Hi610"), which will print Hi610 to stdout.


Because it's converting the integers to string. This is simply the way java string concatenation works.

There is extensive documentation on this subject. You may want to read it.

If you do 6+10+"Hi", you'd get 16Hi out. If you want to add the integers, use parenthesis.


6 and 10 are being taken as int which are converted to String by using +. So, you are printing: string+int(tostring)+int(tostring)

http://ideone.com/a3vuH

You expected something else?


You have run into the single overloaded operator in Java - + - and the rules for when it means what (string concatenation or addition) are not immediately obvious but very well defined.

As always when the precedence rules are non-intuitive, use parenthesis:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜