Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Why does it do this? So confuuuusing.

like image 881
Devoted Avatar asked Nov 27 '22 23:11

Devoted


1 Answers

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".

like image 107
Platinum Azure Avatar answered Dec 09 '22 18:12

Platinum Azure