Objects and Names for Objects

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        

Answer:

No. Just because there is a name for an object does not mean an object exists.

Objects and Names for Objects

A variable that can refer to an object does not always have an object to refer to. For example, in our program the variable str1 refers to an object only after the new operator has created one.


class StringTester
{

  public static void main ( String[] args )
  {
    String str1;   // str1 is a variable that may refer to an object. 
                   // The object does not exist unit the "new" is executed.
    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");
  }
}

Before the new operator did its work, str1 was a "place holder" that did not yet refer to any object. After the new operator created the object, str1 can be used to refer to the object.

QUESTION 8:

What object is referred to in the statement:

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