• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is rule for this output ?  RSS feed

 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

output
-------
23
5
5
23

what is the rule for this output ? is there any operator precedence i have to think of ?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's working how i'd expect it to. it's doing addition in order from left to right.
 
Ben Buchli
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whenever you have doublequotes, java concatenate strings.
so (" " +2 + 3) is considered an empty string (" "), where 2 and 3 get added.
(2 + 3) of course is just int addition.
(2 + 3 +"") here you have addition of 2+3 which will be automatically converted to string because of your double quotes.
hope that helps.
 
Tim West
Ranch Hand
Posts: 539
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that + is right-associative, so "" + 2 + 3 is treated as (("" + 2) + 3). Thus two concatenations are performed. If you wanted to add the numbers numerically, you could add brackets to override the association: "" + (2 + 3) would result in String "5".
Also, because of right-association, 2 + 3 + "" results in String "5" because the 2 and 3, both ints, are added first.
--Tim
 
Dashing Dexter
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Program is doing addition in order from left to right
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!