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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date