wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String" Watch "String" New topic
Author

String

Puja S
Ranch Hand

Joined: Jan 06, 2005
Posts: 51
Hi,

public class Test {
public static void main ( String args [ ] ) {
if("String".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

}
}

The output of this code is Equal but when I change the code to

public class Test {
public static void main ( String args [ ] ) {
if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

}
}

Why is this code giving an output of Not Equal . ( In the second code I'm giving spaces in the " String " ) .

Thanks.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

The 2nd code is creating a new object.


Groovy
Puja S
Ranch Hand

Joined: Jan 06, 2005
Posts: 51
There is another code where I'm having doubt :

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


The output of this code is Equal and when the code is changed to
" String ".trim( ) == " String ".trim( ).......the output is Not Equal.


Why ?
Vipin Das
Ranch Hand

Joined: Jul 05, 2004
Posts: 47
Hi puja,
The new string objects will be returned only if there is anything to trim. If u give without any spaces at the ends, the same string will be returned, and therefore the strings will be equal. But if there are anything to trim a different string will be returned and they will become different objects. To understand this u must be aware of the string pool also.
-vipin
Puja S
Ranch Hand

Joined: Jan 06, 2005
Posts: 51
Thanks Pradeep and Vipin........I got your point.
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
in other words: NEVER use == to compare Strings unless you explicitly intend to check whether two reference variables refer to the same memory location rather then whether they refer to memory with the same content.


42
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String
 
Similar Threads
Strings
Strings,trim
Question abt Strings
Gone Mad!!
String Confusion