• 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

please clarify this.....

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");


the result is Not equal
how?
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

please use a better headline, which describes your problem better.
Coming to your problem, the trim()-method calls the substring()-method, which creates a new string object with the new keyword. So even if we have two strings with the same "value", we have two different objects. And because the "==" operator returns false, if the objects are different, you have your answer.
Check also this thread: General-problems

cheers
Bob
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String.trim() returns a new String object, which makes sense if you remember that Strings are immutable.
So you are in fact comparing two distinct objects for referential equality, using the == operator, which will return false.
Remember the difference between == and .equals() comparison for Objects.

Edit: Too slow as usual...
 
teja dharma
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you that's a silly question. I expected the same answer just after posting i should have done it before posting
this example clarifies my doubt much better which returns true
if("String".toString() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
 
Bob Wheeler
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I expect your problem is solved?
The toString() method doesn't create a new String object, it just returns the object itself.

cheers
Bob
 
reply
    Bookmark Topic Watch Topic
  • New Topic