go to previous page   go to home page   go to next page        

Answer:

The completed program is given below.

Using a Constructor in a Declaration

Here is the complete program with the blanks filled in as suggested.

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" );
  }
}

This 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:

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

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

String str1 =  "Green eggs";

The above 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.

QUESTION 17:

Which of the following are correct?

String ant = "It was a dark and stormy night."
String bat = new( "A shot rang out in the dark." );
int    cat = "123";
double dog = 45.69;