Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Kindly Explain

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class TestThis{
public static void main(String args[]){
System.out.println(1 + 2 + "Strange");
System.out.println("Strange" + 1 + 2);
}
}
After compiling this
when you run this
The first output is 3Strange
why is the second output Strange12 rather than Strange3 ?
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think, it's because, arithmatic expression starts from left side ( if the operators are same) and for the first example it already added both the numbers and then got the String and added it that way. But in case of the 2nd, since the 1st member is String it took everything as String.
Guys please give your more technical explanation.
Ananda
I am new to Java, so any advice is welcome.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, Ananda , you are right
starting from left to right , java evaluate its expressions.
so, 1+2+"strange" will take the following steps:
1- take the first expression 1, and the second one , 2, then add them, giving 3
2- take 3, and the next expression which is a string, and add them, remember now this is not the arithmatic addition, this is the string concatenation +, becuase we have a string, so a new object is created with of type string and have the value "3strange"
if you follow the same logic ,the second statement should make sense.
hope this help
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic