Obtaining String Objects


Obtaining String Objects

There are three basic ways to obtain a String object. You can create one with a String class constructor, you can create one using a String literal, or you can acquire one from a method that returns a String . The constructors defined in the String class are shown in Table 15.6.

Table 15.6. String Class Constructors

public String()

public String(byte[] bytes)

public String(byte[] bytes, int offset, int length)

public String(byte[] bytes, int offset, int length, String charSetName)

public String(byte[] bytes, String charSetName)

public String(char[] chars)

public String(char[] chars, int offset, int length)

public String(String original)

public String(StringBuffer stringBuffer)

As you can see, most of the String constructors define byte or character arrays as their input arguments. Creating these arrays can be a bit inconvenient. The more commonly used method of creating a String object is to assign a String literal to a String reference. A String literal is a series of characters surrounded by double quotes. For example, you could create a String object named model using the syntax

 String model = "Mars Pathfinder"; 

You can also acquire a String from a method that returns a String . One commonly used method that does this is toString() , defined in the Object class (and typically overridden in subclasses). This method returns a String representation of the object on which it is invoked.

Example: Creating Strings

The CreateString class shows the three primary ways to obtain a String object. A String object is created using a String constructor. The character sequence stored by the String is obtained from a char array. An easier way to get a String object is by using a String literal. The String variable string2 is initialized in this way. You can also get a String object from a method that returns a String . A Date object is created, and the toString() method is called on it to return a String representation of the object on which it is invoked.

 import java.util.Date; public class CreateString {   public static void main(String args[]) {     //  There are three ways to obtain a String     //  object. Using a constructor     char array[] = { 'R', 'i', 'g', 'h', 't',                      ' ', 'n', 'o', 'w' };     String string1 = new String(array);     //  Using a String literal     String string2 = "the time is\n";     //  From a method that returns a String     Date date = new Date();     String string3 = date.toString();     System.out.println(string1+string2+string3);   } } 

Output (will vary) ”

 Right now the time is Tue Aug 27 22:14:31 GMT-07:00 2002 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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