• Post Reply Bookmark Topic Watch Topic
  • New Topic

== 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..

 
How do they get the deer to cross at the signs? Or to read this tiny ad?
ScroogeXHTML 7.1 - RTF to HTML5 / XHTML converter
https://coderanch.com/t/690611/ScroogeXHTML-RTF-HTML-XHTML-converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!