Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Nov 2, 2005

Comparing Strings Properly in Java

The semantics of ==, with regards to string comparison in Java and C#, are totally different from each other. Suppose you have two strings—s1 and s2—and the following statment:

// valid Java and C# code
if (s1 == s2) 
{
   // A
}
else 
{
   // B
}
In Java, you would not always reach point A when the strings are identical. This is because the comparison here is of references; == checks if the strings have the same memory location—not whether they contain the same characters in the same order.

In C#, == does check for the same characters in the same order. In order to compare strings this way in Java, you must use the equals method:


// valid Java only
if (s1.equals(s2)) 
{
   // A
}
else 
{
   // B
}
Note: C# also has an equals method which can be used to compare strings in the same way that Java's equals methods compares them and C#'s == compares them.

Sachin Kainth
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap