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

What object is referred to in the statement:

                                                          
len  = str1.length();  // invoke the object's method length()

Answer:

This statement occurs in the program after the object has been created, so str1 refers to that object.


Using a Reference to an Object


class StringTester
{

  public static void main ( String[] args )
  {
    String str1;   // str1 is a variable that refers to an object, 
                   // but the object does not exist yet.
    int    len;    // len is a primitive variable of type int

    str1 = new String("Random Jottings");  // create an object of type String
                                                           
    len  = str1.length();  // invoke the object's method length()

    System.out.println("The string is " + len + " characters long");
  }
}

Once the object has been created (with the new operator), the variable str1 refers to an actual object. That object has several methods, one of them the length() method. A String object's length() method counts the characters in the string.


QUESTION 9:

What is printed to the monitor by the above program?

The string is characters long