Friday, October 17, 2014

How to Comapre Strings In Java


While Surfing on Internet we got to Know that a Beginner is Facing the Following Problem :

"I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.Is == bad? When should it and should it not be used? What's the difference? "
 Well  In Our Basic Operator and Expression Topic we Get to Know that == is comparison operator but it is valid for Only Integer,Float,Array, Char.



== is a Reference Equality.

To Compare Two String we need to check each character of that String. So We get a Inbuilt method equals() or equalsIgnorecase()

For Example 


// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" // --> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false

// interned strings can also be recalled by calling .intern()
"test" == "!test".substring(1).intern() // --> true

So it is Clear that == is a Referential Equality Checker. It usually check that whether the two String are from Same Object and having Same Value so thats why when we use == operator then it show false.

To Understand the String Handling Concept Better Go through Our String Handling Tutorial.
 


For Further Reading,
JAVA

0 comments:

Post a Comment