Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String

 
Puja S
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The 2nd code is creating a new object.
 
Puja S
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pradeep and Vipin........I got your point.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic