Using a Reference to an Object

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

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?