Declaring a Reference Variable

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   hear noise   go to next page

Answer:

No. The example program called the method like this:

str.length();

No parameters are supplied.

Declaring a Reference Variable

There are several ways to declare a reference variable:

ClassName variableName;
  • This declares a reference variable and declares the class of the object it will later refer to. No object is created.
ClassName variableName  =  new ClassName( parameter, parameter, ... ) ;
  • This declares a reference variable and declares the class of the object. But now, at run time, a new object is created and a reference to that object is put in the variable. Sometimes parameters are needed when the object is constructed.
ClassName   variableNameOne, variableNameTwo ;
  • This declares two reference variables, both potentially referring to objects of the same class. No objects are created. You can do this with more than two variables, if you want.
ClassName   variableNameOne  =  new ClassName( parameter, parameter, ... ), 
            variableNameTwo  =  new ClassName( parameter, parameter, ... ) ;
  • This declares two reference variables. At run time, two objects are created and their references are assigned to the variables. Again, you can do this for more than two as long as you follow the pattern.

QUESTION 10:

Is the following correct?

String stringG = new String("You know my methods, Watson.");