• 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

Gone Mad!!

 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have really gone mad after trying this...Please give the rational..
- Thanks
public class AQuestion {
public static void main(String args[]) {

if(" String ".toString() == " String"+" ")
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
public class AQuestion {
public static void main(String args[]) {

if("String".trim() == "String".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
public class AQuestion {
public static void main(String args[]) {

if(" String ".trim() == " String ".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You just need to know when the String's functions return the same reference (without creating new one). As usual it's the case when nothing has to be changed (i.e. "str".trim() nothing to trim, so in that case "str" == "str".trim();
"str".toLowerCase()== "str"; TRUE
"str".replace("a", "c") == "str"; TRUE
"str".concat("") == str; TRUE and so on.
String's toString() method returns always the same reference, so
"string" == "string".toString(); always TRUE.
For the case of "string" == "str" + "ing"; (TRUE) I have not a good explanation but I found that "+" works quasi the JVM sees the whole word at once.
So, "s" + "t" + "r" + "i" + "n" + "g" == "string" always TRUE.
I think you know why "string" == "string" (from a pool of String literals).
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"str" + "ing" can be evaluated at compile time, so the compiler will make "string" of it. The same for "s" + "t" + "r" + "i" + "n" + "g".
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good Explanations!!!
Thanks
Anwar
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic