Steps in Program Execution

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:

When run, the program will print:

A Greeting!

to the monitor.

Steps in Program Execution

Here is how the program does this:

class HelloObject                            // 3a.  the class definition is
{                                            //      used to construct the object.
  String greeting;

  HelloObject( String st )                   // 3b.  the constructor is used to 
  {                                          //      initialize the variable.
    greeting = st;
  }

  void speak()                               // 4a.  an object has its own copy
  {                                          //      of this method.
    System.out.println( greeting );          // 4b.  the object's method uses
  }                                          //      the data in its variable
}                                            //      greeting.

class HelloTester
{
  public static void main ( String[] args )   // 1.  main starts running
  {
    HelloObject anObject =                     
        new HelloObject("A Greeting!");       // 2.  the String "A Greeting"
                                              //     is constructed.
                                                    
                                              // 3.  A reference to the String is 
                                              //     passed to the HelloObject
                                              //     constructor.
                                              //     A HelloObject is created.

    anObject.speak();                         // 4.  the object's speak() 
                                              //     method is activated.
  }
}

You usually don't think about what is going on in such detail. But you should be able to do it when you need to.

Notice that a String object containing "A Greeting!" is constructed before the HelloObject constructor is even called. Strings are objects (of course) so they must be made with a constructor. Remember that Strings are special because an object can be constructed without using the new operator. This is what the literal "A Greeting!" does.

QUESTION 20:

(Trick Question:) How many objects exist just before this program stops running? Click here for a