• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why this code is not giving me correct output  RSS feed

 
bharath sn
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(4+7+"2"+9+3+"1");

This code produces oputput 112931 which is 4+7=11 so 112931

the java is making all the integers as char
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37465
538
Eclipse IDE Java VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bharath,
Welcome to CodeRanch!

Java sees this as different steps:

4+7 = 11 (integer addition)
11 + "2" = "112" (string concatenation)
"112" + 9 = "1129" (string concatenation)
"1129" + 3 = "11293" (string concatenation)
"11293" + "1" = "112931" (string concatenation)

In Java, string concatenation is used if either or both arguments in a String. Integer addition is only used when both sides are numeric.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... and "+" has the same precedence for string concatenation as for integer addition - so it is left-associative here, meaning not even "9+3" will be added up.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again. It is all in the Java Language Specification, though that may be difficult to read.

And everybody else here has fallen into the same pitfall themselves.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!