Method Definition

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:

  • What two classes are defined in this code?
    • HelloObject and HelloTester
  • What method is in the first class?
    • A HelloObject object has a speak() method.

Method Definition

Method definitions look like this:

returnType methodName( parameterList )
{
  // Java statements

  return returnValue;
}

The returnType is the type of value that the method hands back to the caller of the method. Methods in classes you define can return values just as do methods from library classes. The return statement is used to hand back a value to the caller.

If you want a method that does something, but does not return a value to the caller, use a return type of void and do not use a return value with the return statement. The return statement can be omitted; the method will automatically return to the caller after it executes. Here is the method from the example program:

  // method definition
  void speak()
  {
    System.out.println("Hello from an object!");
  }

QUESTION 8:

Examine the program.

Is a HelloTester object created when the program runs?