Thursday, December 15, 2011

Java's character and assorted string classes support text-processing - 15


For another String method demonstration, see Listing 3, which shows how the intern() method and the == operator enable a rapid search of a partial list of country names for a specific country:
Listing 3: CS.java
// CS.java
// Country search
import java.io.*;
class CS
{
   static String [] countries =
   {
      "Argentina",
      "Australia",
      "Bolivia",
      "Brazil",
      "Canada",
      "Chile",
      "China",
      "Denmark",
      "Egypt",
      "England",
      "France",
      "India",
      "Iran",
      "Ireland",
      "Iraq",
      "Israel",
      "Japan",
      "Jordan",
      "Pakistan",
      "Russia",
      "Scotland",
      "South Africa",
      "Sweden",
      "Syria",
      "United States"
   };
   public static void main (String [] args)
   {
      int i;
      if (args.length != 1)
      {
          System.err.println ("usage: java CS country-name");
          return;
      }
      String country = args [0];
      // First search attempt using == operator
      for (i = 0; i < countries.length; i++)
           if (country == countries [i])
           {
               System.out.println (country + " found");
               break;
           }
      if (i == countries.length)
          System.out.println (country + " not found");
      // Intern country string
      country = country.intern ();
      // Second search attempt using == operator
      for (i = 0; i < countries.length; i++)
           if (country == countries [i])
           {
               System.out.println (country + " found");
               break;
           }
      if (i == countries.length)
          System.out.println (country + " not found");
   }      
}

CS attempts twice to locate a specific country name in an array of country names with the == operator. The first attempt fails because the country name string literals end up as Strings in the common string memory pool, and the String containing the name being searched is not in that pool. After the first search attempt, country = country.intern (); interns that String in the pool; this second search most likely succeeds, depending on the name being searched. For example, java CS Argentina produces the following output:

Argentina not found
Argentina found

No comments: