• 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

Trim()

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Why does this give "Not Equal" as result

and

if("String".toString() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

code results in "Equal"

Thx
Sharanya
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sharanya,

In the first example, the trim method produced a new String instance that is equal to " String " with the leading and trailing spaces removed. That new String instance is not the same instance as the one in the String constant pool. In the second example, "String".toString(), the toString method simply returns a reference to itself, and no new instance is created.

I would say that those examples fall into a category that Kathy Sierra refers to as Java Trivia. You don't have to worry about finding anything like that on the real exam. The exam is not intended to test your knowledge of when the String.trim method returns a reference to a new or existing instance of a String.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic