Jtest logo




Contents  Previous  Next  Index

INTER.SCT


The 'compareTo()' method of strings should not be used in an internationalized environment

Description

This rule flags code that uses the `compareTo()' method of strings.

If code uses the `compareTo()' method of strings, it will not run in an internationalized environment. This is because it performs binary comparisons of the Unicode characters within the two strings, which are ineffective when sorting in most languages. String variables with 'compareTo()' cannot be relied on to sort strings because the Unicode values of the characters in the strings do not correspond to the relative order of the characters for most languages.

Example

 package INTER;
 package INTER;
 public class SCT{
   public boolean compstr(){
   String s1= new String("hello");
   String s2 = new String("bye");
   if (s1.compareTo(s2) < 0 )   // violation 
      return true;
   return false;
   }
 }

Repair

The predefined collation rules provided by the "Collator" class should be used instead to sort strings in a locale-independent manner. To instantiate the "Collator" class, invoke the getInstance method. Usually, you create a Collator for the default Locale, as in the following example:

 Collator myCollator = Collator.getInstance();

You can also specify a particular Locale when you create a Collator, as follows:

 Collator myFrenchCollator = Collator.getInstance(Locale.FRENCH);

Then you invoke the Collator.compare method to perform a locale-independent string comparison as follows:

 myCollator.compare(s1,s2); 

Reference

http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html

http://java.sun.com/docs/books/tutorial/i18n/text/locale.html


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft