Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println("abc"+3+2); why output is abc32 and not abc5? [duplicate]

Tags:

java

core

Possible Duplicate:
Difference between int and int received by ParseInt in java

System.out.println("abc"+3+2); // Output: abc32

System.out.println(3+2+"abc"); //Output: 5abc

What is the reason ?

like image 258
Rocky Avatar asked Jun 14 '12 14:06

Rocky


2 Answers

"abc"+3

converts 3 to a String

"abc3"

Then

"abc3" + 2

Converts 2 to a String as well

"abc32"

To get a numeric result do

"abc" + (3 + 2)
like image 148
Eran Medan Avatar answered Oct 04 '22 20:10

Eran Medan


Because the "+" operator you wrote means "string concatenate", not "add", because it is found with left context being a string value. In this case, you get a free coercion of the right value via an implicit ToString.

You'd probably get what you wanted by writing

System.out.println("abc"+(3+2))

The "3" is found with no left context, so it is just an integer; the following "+" is found with left context integer, so it is interpreted as a real add operator, thus (3+2) gives 5. That result is found with left context of "+", so it is coerced to a string and concatenated to produce "abc5".

like image 24
Ira Baxter Avatar answered Oct 04 '22 18:10

Ira Baxter