• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The progrma gives o/p as "Not Equal" why?

 
Ramesh Shanmugam
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if( "string".toUpperCase() == "STRING")
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}

the O/p is "Not Equal". How is that?? can anyone explain me???

Thanks in advance
Ramesh
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method is creating a new String object containing STRING which is not the same object as "STRING".

Notice that this prints Equal.

 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Strings are not primitive values which can be compared with "==". Strings are objects and in order to compare the contents of the object rather than the references to the object (which is what "==" does), one must use a method like equals() or compareTo().
 
Ramesh Shanmugam
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies

But this code gives an o/p as "equals"

if( "STRING".toUpperCase() == "STRING")
System.out.println("Equal");
else
System.out.println("Not Equal");

in this case, whether two objects refer to the same reference??
if so, how is that o/p??

Thanks in advance,
Ramesh
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is part of the implementation of toUpperCase(Locale).



So basically the toUpperCase method checks first to see if there are any lowercase characters in the String. If there are, then it will create a new String. Otherwise, the method returns the same String.

The method toUpperCase() calls toUpperCase(Locale).
[ April 04, 2006: Message edited by: Keith Lynn ]
 
Ramesh Shanmugam
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Keith Lynn ,

You explanation is very nice... Understood well

Thanks,
Ramesh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic