• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

concatenation

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I'm quite puzzled about this code:

Given:

It returns "86foo". But I wonder why? The return type of the foo method is String. I would guess that as soon as a String is involved as operand, all "+" operators would work as concatenation operators. Why not?

Thanks for your help

Ray
 
Sheriff
Posts: 7134
1360
IntelliJ IDE jQuery Eclipse IDE Postgres Database Tomcat Server Chrome Google App Engine
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java evaluates an expression from left-to-right. To understand this in practice, try the following statement.

System.out.println("" + x + y + foo());

Devaka
 
Ranch Hand
Posts: 196
Android Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Java evaluates an expression from left-to-right.



-->42L+44L+"String" evaluates as follows
---->86L+"String" (long+long)
----------->86String (long's toString() value+string)

if you give an expression like this "String"+42L+44L

-->"String42"+44L (String+Long's toString() Value)
---->"String4244" (String+Long's toString() Value)
 
Raymund Beyer
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your help, got it! This was new to me...

Cheers

Ray
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is unlikely the exam will try to trap you with this type of question but it helps to know this for work related knowledge. I do this all the time



A few missed quotes or brackets or a combination of string and ints / long can give the wrong result.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic