Win a copy of Pragmatic AI this week in the Artificial Intelligence forum!
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

== Operator  RSS feed

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

After study of the == operator I thought I already know how it behaves until I encountered this question.

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

Why does this piece of code prints "Equal"?
 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's true that String methods which returns a String (like substring, toUppercase, trim, ...) returns a new String object, and that in most case, the returned String is not equals (regarding == operator) to the String from which the method is called.

The exception is when the method's result is the same litteral than the String reference, the result is the String itself.

So s.substring(0) == s is always true id s is not null.

When you look at Javadoc for the trim() method, it is sayed : "Returns:
A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.".

But this thing is not specified for some methods.
 
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Richard..

Have a look at this thread...

http://www.coderanch.com/t/251058/java-programmer-SCJP/certification/String-Confusion


and let me know the result..

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!