go to previous page   go to home page   go to next page hear noise


The completed program is given below.

Using a Constructor in a Declaration

class StringTester

  public static void main ( String[] args )
    String str1;   // str1 is a reference to a String object.
    String str2;   // str2 is a reference to a second String object.

    int len1, len2 ;    // the length of str1 and the length of str2

    str1 = new String( "Green eggs") ; // create the first String

    str2 = new String( " and ham.")  ; // create the second String

    len1 = str1.length();    // get the length of the first string

    len2 = str2 . length();    // get the length of the second string

    System.out.println("The combined length of both strings is " +
        (len1 + len2) + " characters" );

The above is a wordy version of the program. An object can be created in a variable declaration. For example the following creates a String object containing the designated characters and puts a reference to the new object in the reference variable str1.

String str1 = new String("Green eggs");

Here is an even shorter way, that works only for String objects:

String str1 =  "Green eggs";

This statement ensures that str1 refers to an object containing the designated characters. However, if a "Green eggs" object already exists, no new object is created, but str1 is made to refer to the already existing object.

This is an optimization. Often, the same sequence of characters is needed many places throughout a program, so it is efficient to use only one object.


Inspect the following code. How many objects are there?

String prompt1 = "Press Enter to Continue."
String prompt2 = "Press Enter to Continue."
String prompt3 = "Press Enter to Continue."
String prompt4 = "Press Enter to Continue."