Thursday 16 March 2017

The String Constructors & Special String Operations - Java Tutorials

The String Constructors

The String class supports several constructors. To create an empty String, you call the default constructor. For example,

String s = new String();

will create an instance of String with no characters in it.

Frequently, you will want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here:

      String(char chars[ ])

Here is an example:

  char chars[] = { 'a', 'b', 'c' };
  String s = new String(chars);

This constructor initializes s with the string “abc”.

You can specify a subrange of a character array as an initializer using the following constructor:

      String(char chars[ ], int startIndex, int numChars)

Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example:

  char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
  String s = new String(chars, 2, 3);

This initializes s with the characters cde.

You can construct a String object that contains the same character sequence as another String object using this constructor:

      String(String strObj)

Here, strObj is a String object. Consider this example:

  // Construct one String from another.
  class MakeString {
    public static void main(String args[]) {
      char c[] = {'J', 'a', 'v', 'a'};
      String s1 = new String(c);
      String s2 = new String(s1);

      System.out.println(s1);
      System.out.println(s2);
    }
  }

The output from this program is as follows:

  Java
  Java

As you can see, s1 and s2 contain the same string.

Even though Java’s char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here:

      String(byte asciiChars[ ])
      String(byte asciiChars[ ], int startIndex, int numChars)

Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors:

  // Construct string from subset of char array.
  class SubStringCons {
    public static void main(String args[]) {
      byte ascii[] = {65, 66, 67, 68, 69, 70 };
  
      String s1 = new String(ascii);
      System.out.println(s1);

      String s2 = new String(ascii, 2, 3);
      System.out.println(s2);
    }
  }

This program generates the following output:

  ABCDEF
  CDE

Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding provided by the platform.

The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, the String will be unchanged.


String Length

The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here:

      int length( )

The following fragment prints “3”, since there are three characters in the string s:

  char chars[] = { 'a', 'b', 'c' };
  String s = new String(chars);
  System.out.println(s.length());




Special String Operations


Because strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity.


String Literals

The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For example, the following code fragment creates two equivalent strings:

  char chars[] = { 'a', 'b', 'c' };
  String s1 = new String(chars);

  String s2 = "abc"; // use string literal

Because a String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string “abc”. As expected, it prints “3”.

  System.out.println("abc".length());


String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings:

  String age = "9";
  String s = "He is " + age + " years old.";
  System.out.println(s);

      This displays the string “He is 9 years old.”

One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example:

  // Using concatenation to prevent long lines.
  class ConCat {
    public static void main(String args[]) {
      String longStr = "This could have been " +
        "a very long line that would have " +
        "wrapped around. But string concatenation " +
        "prevents this.";

      System.out.println(longStr);
    }
  }


String Concatenation with Other Data Types

You can concatenate strings with other types of data. For example, consider this
slightly different version of the earlier example:

  int age = 9;
  String s = "He is " + age + " years old.";
  System.out.println(s);

In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String.

Be careful when you mix other types of operations with string concatenation expressions, however. You might get surprising results. Consider the following:

  String s = "four: " + 2 + 2;
  System.out.println(s);

This fragment displays

  four: 22

rather than the

  four: 4

that you probably expected. Here’s why. Operator precedence causes the concatenation of
“four” with the string equivalent of 2 to take place first. This result is then concatenated
with the string equivalent of 2 a second time. To complete the integer addition first, you
must use parentheses, like this:

  String s = "four: " + (2 + 2);

Now s contains the string “four: 4”.


String Conversion and toString( )

When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String. valueOf( ) is overloaded for all the simple types and for type Object. For the simple types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf( ) calls the toString( ) method on the object. We will look more closely at valueOf( ) later in this chapter. Here, let’s examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create.

Every class implements toString( ) because it is defined by Object. However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you will want to override toString( ) and provide your own string representations. Fortunately, this is easy to do. The toString( ) method has this general form:

      String toString( )

To implement toString( ), simply return a String object that contains the humanreadable string that appropriately describes an object of your class.

By overriding toString( ) for classes that you create, you allow them to be fully integrated into Java’s programming environment. For example, they can be used in print( ) and println( ) statements and in concatenation expressions. The following program demonstrates this by overriding toString( ) for the Box class:

  // Override toString() for Box class.
  class Box {
    double width;
    double height;
    double depth;

    Box(double w, double h, double d) {
      width = w;
      height = h;
      depth = d;
    }

    public String toString() {
      return "Dimensions are " + width + " by " +
            depth + " by " + height + ".";
    }
  }

  class toStringDemo {
    public static void main(String args[]) {
      Box b = new Box(10, 12, 14);
      String s = "Box b: " + b; // concatenate Box object

      System.out.println(b); // convert Box to string
      System.out.println(s);
    }
  }

The output of this program is shown here:

  Dimensions are 10.0 by 14.0 by 12.0
  Box b: Dimensions are 10.0 by 14.0 by 12.0

As you can see, Box’s toString( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ).

No comments:

Post a Comment