| Author |
The progrma gives o/p as "Not Equal" why?
|
Ramesh Shanmugam
Ranch Hand
Joined: Sep 13, 2004
Posts: 132
|
|
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
|
Ramesh Shanmugam - SCJP 1.5
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
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
Joined: Oct 29, 2001
Posts: 8260
|
|
|
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().
|
"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
|
 |
Ramesh Shanmugam
Ranch Hand
Joined: Sep 13, 2004
Posts: 132
|
|
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
Joined: Feb 07, 2005
Posts: 2341
|
|
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
Joined: Sep 13, 2004
Posts: 132
|
|
Thanks Keith Lynn , You explanation is very nice... Understood well Thanks, Ramesh
|
 |
 |
|
|
subject: The progrma gives o/p as "Not Equal" why?
|
|
|