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

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


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

 

QUESTION 9:

What is printed to the monitor by the above program?