• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Trim()

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • 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
  • 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.
 
Nothing up my sleeve ... and ... presto! A tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic