Creating and Using Methods

Contact Us or call 1-877-932-8228
Creating and Using Methods

Creating and Using Methods

The method is the basic complete unit of code to perform one task within an object:

  • In procedural languages, these are called functions, but in OOP they are usually called methods.
  • Almost all executable code is in some method.
  • Technically, there is one other place an object-oriented program could have executable code, but that is an advanced topic.
  • Examples: calculate a trigonometry function like cosine, print data on the screen, read from a file, open a window.
  • Methods are defined by a name followed by parentheses.
  • Inputs to the method go inside the parentheses; they are called parameters or arguments to the method.

Using a method in your code, causing it to run, is known as calling the method.

A method call is an expression, so it may result in a value (the method call is evaluated like any other expression).

  • this value is called the return value, and the method is said to return a value.
  • the following is an example of a method used as an expression within a larger expression:
z = Math.sin(Math.PI / Math.sqrt(x));

Methods must be called with arguments that matching their specified form, known as the function signature:

  • the signature is the combination of the name of the method with the pattern of its parameters.
  • the documentation for library-supplied methods will tell you the signature for those methods.
  • when you call a method, the name of the method and the parameters you pass to it will determine which method will be called, based on the available signatures.
  • for each argument, Java expects a value - which could be a literal value, a variable, or expression; it must be either the correct type or a value that can be implicitly typecast to the correct type.

All methods in Java must be defined within a class definition. They have complete access to all other elements of the class (fields and other methods, regardless of the access modifier used for that element).

Code Sample:

Java-Basics/Demos/UseMethodsExample.java
public class UseMethodsExample {
  public static void main(String[] args) {
    int x = 16;
    double y = Math.sqrt(x);
    System.out.println("Square root of " + x + " is " + y);

    double z = Math.sin(Math.PI / 2);
    System.out.println("Sine of pi/2 is " + z);
  }
}

This class calls two methods from the Math class: sqrt and sin, both of which expect one parameter which is a double.

When we call sqrt and pass an integer, the compiler converts that to a double to provide the type of data that sqrt expects

Note that even if your program does not call any methods, it has one method that will be called: main(). Things to note:

  • The definition of main() is that it provides a start point and end point for your program.
  • Program execution starts with the first statement in main().
  • If the last statement in main() is executed, the program ends.
  • The main() does have arguments (any other words typed on the command line).

Creating Methods

There are three things you need to decide for any method:

  1. what it does.
  2. what inputs it needs.
  3. what answer it gives back.
[modifiers] dataType methodName(parameterList) {
	methodBody
	return result;
}
  • modifiers include the accessibility of this method from outside the class (public, private, protected, or left blank) as well as other possibilities listed earlier in this section.
  • dataType is a type of data, like int.
  • methodName is the name of your method.
  • parameterList is a comma-separated list of parameters; each parameter is listed with its data type first, then its name.
  • methodBody is the set of statements that perform the task of the method.
  • return is a keyword that says to use the result expression value as the result of calling the method, and send that value back to the code that called the method (as an expression, a call to a method evaluates to the returned value; i.e., calling Math.sqrt(4) evaluates to the value that sqrt returned).
  • if a method declares that it returns a value of a certain type, then it must explicitly return a value of that type.

Method Examples

public void sayHello() {
	System.out.println("Hello");
}
  • public methods are accessible to any other class.
  • void is a keyword for a returned data type that means no data at all - this method does not calculate a result.
  • The name of the method is sayHello.
  • This method could be called as follows:
Code When Used
sayHello(); from within the class
x.sayHello(); from outside the class, for an instance x of this class
public void showNumber(int number) {
 System.out.println("The number is: " + number);
}
  • again, this method does not calculate a result.
  • this method could be called as follows:
Code When Used
showNumber(5); from within the class
x.showNumber(5); from outside the class, for an instance x of this class
>public int calculateSum(int num1, int num2) {
 int answer = num1 + num2;
 return answer;
}
  • This method does calculate a result; the data type it calculates is int.
  • This method must be given two parameters, both of which are int data types.
  • This method could be called as follows:
Code When Used
int value = calculateSum(4, 6); from within the class
int value = x.calculateSum(4, 6); from outside the class, for an instance x of this class

Return Values

Note that the listing of a data type word in front of a name is something we have seen before, in declaring variables. The purpose is the same - to state what type of data this element provides when used in an expression.

The first statement below states that the value of a is an int, so that the compiler knows what memory size to allocate and what type of processing to use with it when it evaluates the second statement.

int a;
int b = a / 2;

The effect is no different using a method; recall the function signature (the first line) of our calculateSum method:

public int calculateSum(int num1, int num2)

It states that the result of evaluating calculateSum is an int, so that the compiler knows what memory size to allocate for the result, and what type of processing to use with it when it evaluates a statement like:

int b = calculateSum(4, 6) / 2;

When this statement gets processed, the calculateSum method will run and return its result (which will be the value 10 as an int).

Thus the statement in effect is reduced to:

int b = 10 / 2;

Method Parameters

Method parameters are also declarations. They declare a type of data received by the method, and also provide a name for each value so it can be used within the method.

Back to our method:

public int calculateSum(int num1, int num2) {
 int answer = num1 + num2;
 return answer;
}
  • The parameter list declares two variables that will exist in this method: num1 and num2.
  • The order is important - num1 will be the first value given to the method, num2 will be the second.
  • The difference between method parameter declarations and the variable declarations we saw before is that the method parameters receive their values when the method is called.
Next