Section 4.2. Strings

   

4.2 Strings

A string is a discrete series of adjacent characters. A string is distinct from the primitive types in that it is a standard class. A string literal is a set of zero or more characters surrounded by double quotes:

 String name = new String("JJ"); 

Strings are used very frequently, so Java makes available a shortcut for string creation and initialization, like this:

 String name = "JJ"; 

This longer version, called a constructor , represents the way in which objects are created. The shorter version is called a string literal. String literals are implicitly created as instances of the java.lang.String class, and as such, a variable defined as a string holds a reference to a String object. Because string literals act as if they were references to an instance of the String class, you can do all of the things with strings that you can do with objects, including call methods on them and make copies of them. In general, it is not advisable to create a string using the constructor shown above.

A string is immutable; that is, its value cannot change after it has been created. Strings are stored by the compiler in something called the string constant pool. The constant pool is in the class file produced by the compiler and is a standard part of the Java Class file format. The purpose of this is to give Java programs a performance boost. When the Java Virtual Machine encounters a string variable identifier, it checks the pool to see if it already contains that string. If it does, the JVM can simply return a reference to the current string; this saves it the trouble of having to create a new object, allocate new memory, and garbage collect the string when the program is finished using it.

When you create a string using the new operator (the long version above), this obviates the JVM's search for the string reference in the string constant pool, and will therefore always create a unique object and return a reference to that object.

Note

In ColdFusion, it is perfectly acceptable to write something like this: <cfparam name = "name" default = ""> . In Java, you can similarly write String name = ""; . The thing to note here is that the Java string is not then null. Memory has been allocated for the name String object, and it therefore has an address and is not null. This is called an empty string ”it's just a string with no contents.


The program StringLiterals.java demonstrates the difference with respect to memory that the string literals and String objects instantiation can make. It also shows why you should not use == to test for equality with strings.

4.2.1 StringLiterals.java

 /* File: chp4.StringLiterals.java  Purpose: demo mgmt of string objects and literals Author: E Hewitt */ public class StringLiterals {     public static void main(String[] args){     // create a new string literal     String name1 = "Jedimaster";     // create a new string, assign it the value of name1     String name2 = new String(name1);     // test for equality     System.out.println(name1.equals(name2)); // true. okay.     System.out.println(name1 == name2); // false. hmmm...     } } // eof 

What exactly is happening here? Using the equals() method compares the contents of strings; that is, the data stored in them. Using the == comparison operator compares the memory addresses of the two Strings to determine if they refer to the same object. Because name2 was created using the constructor, a new object was created, which is stored in a new place in memory; hence, the == operator returns false.

The following program illustrates a number of methods that are available for use with strings:

4.2.2 StringMethods.java

 /* File: StringMethods.java  Purpose: demo methods available for working with strings Author: E Hewitt */ public class StringMethods {     public static void main(String[] args){         // create a new string         String phrase = "Java for ColdFusion";         // set to uppercase, like CF function         System.out.println(phrase.toUpperCase());         // set to lowercase, like CF function         System.out.println(phrase.toLowerCase());         // use \ to escape double quotes         System.out.println("Does the phrase end with "+             "\",baby!\"? " + phrase.endsWith(",baby!"));         // get string length in characters         System.out.println("How long is that string? " +             phrase.length() + " characters");         // add 5 spaces to the end:         phrase += "     ";         // get new length:         System.out.println("new length: " + phrase.length());         // prints 24         // trim works like the CF trim functions:         System.out.println("trimmed length: " +            phrase.trim().length());            // prints 19 // try it with a tab escape sequence phrase += "\t"; System.out.println("with tab: " + phrase.length()); //prints 25 // trim the tab System.out.println("trim tab: " + phrase.trim().length()); // prints 19     } } 

Let's do a little more with strings by looking at how we can replace different characters.

4.2.3 StringReplace.java

 public class StringReplaceAndIndex {     public static void main(String [] args) {         // concatenate strings another way         // using +=         String greeting = "Hello ";         String person = "Sally";         greeting += person;         System.out.println(greeting); // prints Hello Sally         // notice that length() is a method with Strings         // not so with arrays, in which it is a field:         System.out.println("There are " + greeting.length() +             " characters in the greeting String");         // find the ordinal occurence of char in String         // use where you would write Find() in CF         System.out.println(greeting.indexOf("o"));         // find last occurrence of char in String         System.out.println(greeting.lastIndexOf("l"));         // note that this works a bit like the replace         // function in CF         greeting.replace('l', 'x');         // here's the difference: in CF, the original         // string would have been modified. not so in Java:         System.out.println(greeting);         // we can pretend, though: (see Buffers)         System.out.println(greeting.replace('l', 'x'));     } } 

This gives us the following output:

 There are 11 characters in the greeting String  4 9 Hello Sally Hexxo Saxxy 

4.2.4 Substrings

Substrings are rather easy to work with if you have some experience handling them in ColdFusion. Substrings.java shows how to use the pertinent methods:

4.2.5 Substrings.java

 public class Substrings {     public static void main (String[] args){         // create a new string         String name = "dude";         // print the first 3 characters         System.out.println("Hello, " +             name.substring(0,3));         // prints Hello, dud         // try it a different way         name = "Tony Danza";         System.out.println("Hello, " +             name.substring(3,7));         // prints y Da         // get first occurrence of T         // remember it starts at 0         System.out.println(name.indexOf("D"));         // prints 5         // is it case-sensitive?         System.out.println(name.indexOf("d"));         // yes. prints -1, meaning "not found"     } } 

The program's output is

 Hello, dud  Hello, y Da 5 -1 

4.2.6 Concatenation

A string can be combined with another string with the + operator, like this:

 String firstName = "JJ";  String lastName = "Allaire"; String fullName1 = "JJ" + ""Allaire"; // literal String fullName2 =  firstName + " " + lastName; // new object 

fullname1 now holds a literal. This is because it was formed exclusively with literals and is therefore a constant string expression. On the other hand, if one of the values in the expression had been a string variable, as with fullname2 , then that would form a new String object.

4.2.7 intern()

There is a final way to create string literals. intern() is a method of String that tells the virtual machine to look in the string constant pool for a matching object. If one is found, the intern() method returns a canonical representation of that object. If the method does not find a matching object, then it creates a new String object and places it in the memory pool. Using the intern() method works like this:

4.2.8 Intern.java

 /* File: Intern.java  Purpose: demo intern() method Author: E Hewitt */ public class Intern { public static void main(String[] args){     String name1 = "JJ";     String name2 = new String ("JJ").intern();     System.out.println(name1.equals(name2)); // true     System.out.println(name1 == name2); // true!     } } // eof 

The reason to use the intern method is because you can use the comparison operator == to test for equality.

Strings are part of the java.lang package, so you can read more about their methods in the API at Sun.com. If you installed the documentation, which is highly recommended, then you can read it locally at JAVA_HOME\docs\index.html . Click on the java.lang package in the top-left frame, and then click on String in the bottom-left frame.

Note

To really look at the items we're going to discuss in this chapter, we will sometimes need to import classes defined in packages other than java.lang (which is available by default). We will look at importing and packages in the chapter on classes; for now, it just seemed polite to let you know why those import statements are sometimes at the top of the following code listings, and that the basic principle is the driving force behind the <cfimport> tag with which you may be familiar.


4.2.9 StringBuffer s

It was mentioned in the previous section that strings are immutable. We have seen string concatenations in action, however. When you modify the value of a string, the compiler constructs a StringBuffer and uses its append() method to concatenate the values. A new String object is returned with the modified value. That means that, despite appearances , someString = someString.toLowerCase() does not modify the same object in memory that it seems to. Therefore, if you think you'll need to modify your string, you may want to create a StringBuffer . Once you have performed the manipulations on it, use the toString() method to bring it back to life as a String object.

4.2.10 StringTokenizer s

A StringTokenizer takes a string and breaks it apart, assigning one token for each word boundary. That is, the string is read as whitespace-delimited.

4.2.11 myStringTokenizer.java

 /* File: StringTokenizer.java  Purpose: Demos using string tokens to get at individual items in a string */ import java.util.StringTokenizer; public class myStringTokenizer {     public static void main(String[] args) { String text = "You clean that fish, Vardaman."; StringTokenizer st = new StringTokenizer(text); while (st.hasMoreTokens())     System.out.println("this token: " + st.nextToken());     } } 

You can also set your own delimiter by passing it into the method that constructs the StringTokenizer object (called a constructor ). This is shown in the next listing, which also demonstrates another method of the StringTokenizer class:

4.2.12 TokenizerChangeDelim.java

 /*  File: TokenizerChangeDelim.java  Purpose: Demos using string tokens with defined delim Author: E Hewitt */ import java.util.StringTokenizer; public class TokenizerChangeDelim {     public static void main(String[] args) { String text = "\"You clean that fish, Vardaman,\"said Pa."; // the third arg tells whether to return the delimiter StringTokenizer st = new StringTokenizer(text, "", false); while (st.hasMoreTokens())    System.out.println(st.nextToken());    System.out.println("tokens now left: " + st.countTokens());    } } 

While these aren't really lists, you might quickly see that elements can be treated in this way, as you might treat a delimited list in ColdFusion. I'm thinking of ListGetAt() and ListChangeDelims() . Here is the output:

 "You clean that fish, Vardaman,"  said Pa. tokens now left: 0 

Tokenizers are useful for interpreting lists of data. You may have to work with CSV or other like data.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net