Review of Object References

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:

It declares a variable str that can hold a reference to a String object. No object has been created.

Review of Object References

An object exists only after it has been constructed. Objects are constructed only as a program is running, when an object constructor is invoked.

Once it has been constructed, an object is accessed by going through a reference to it. Often, the reference is held in a reference variable such as str. In the the following example, a reference variable is declared, and then an object is constructed. A reference to the object is then put in the reference variable:


String str;             // declare a reference variable
str = "Hello World" ;   // construct the object and 
                        // save its reference

Of course, it is OK to declare an object reference variable and not place a reference in it (it might only sometimes be needed.) And it is OK to use the same reference variable for different objects at different times:

String str; 
str = "Hello World" ;

. . . .

str = "Good-by" ;                     

QUESTION 2:

(Thought Question: ) What could you do if your program needed to keep track of 1000 different strings?