Methods - BasicsJ8 Home « Methods - Basics

We have used methods throughout the lessons so far, so its time for a thorough investigation of what we can do with these members. There are two types of methods available in Java static and non-static methods. The general mechanics are the same but static methods apply to the class as a whole, whereas non-static methods generally apply to an instance of the class. We will discuss the vagaries of static methods in the Static Members lesson later in the section.

In the first of three lessons on methods we will look at the basics and for that we will be using a combination of static and non-static methods within our code examples. Lets start by looking at the components of a method:

method parts diagram
Figure 1. Components of a method.

Method declarations can have up to six components but the only required elements are the method's return type, the method name, a pair of parenthesis () and a body between braces {}. Following is the order the components must appear in when used.

  1. Modifiers — such as public as used here are discussed in the Encapsulation lesson along with the other access modifiers and static which we will discuss later in this section in the Static Members lesson. There are also other modifiers which we will learn about later.
  2. The return type — which is the data type of the value returned by the method, or void if the method doesn't return any value.
  3. The method name — which must be a valid identifier as discussed in the Java Variables section of the Primitive Variables lesson. By convention, method names should be a verb in lowercase or multiple words that begin with a verb in lowercase, followed by adjectives, nouns, etc. in camel case.
  4. The parameter list - A comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses. If there are no parameters, you must use empty parentheses. The arguments passed when we call a method are received into the parameter list are within scope as discussed in the Defining A Scope section of the Method Scope lesson.
  5. An exception list — Which will be discussed when we get to look at throwing exceptions in the Using the throws Keyword section of the Declaring Exceptions lesson.
  6. The method body - The method's code, statements, local variable declaration etc, goes in the body which is enclosed between braces.

Passing Arguments To A Method Top

Before we look at this lets clear up some terminology about arguments and parameters. Arguments are what we pass to a method whereas parameters are what we receive the arguments into. We have already seen with our use of the main() method how to pass an argument to a method and we also coded our own printBits method in the Bitwise Operators lesson. Both these methods accept a single argument into their parameter list, but Java has no restriction on the amount of parameters we can code into a method. Lets code a Tiger class with a new method that accepts two parameters:

package info.java8;
  A Tiger Class
public class Tiger {
    String name, colour;
    int age;

    void tigerMannerisms(String action, int times) {  // Our new method with 2 parameters
        System.out.println("Our tiger " + action + " " + times + " times a day.");

Lets write a new test class for our Tiger class.

package info.java8;
  Test Class for Tiger
public class TigerTest {

    public static void main (String[] args) {
        Tiger tony = new Tiger();  // Create a Tiger instance
        tony.tigerMannerisms("eats food", 4);  // Pass values
        String tiggerAction = "runs up trees"; 
        int tiggerTimes = 2; 
        tony.tigerMannerisms(tiggerAction , tiggerTimes );  // Pass types

run tiger
Screenshot 1. Running the TigerTest class.

The above screenshot shows the output of running our TigerTest class. We created a Tiger instance and passed two arguments to the tigerMannerisms method in various ways.

Returning Values From A Method Top

Up until now all our methods have been declared using the void return type which denotes that the method doesn't return any value. We can declare methods with a return type and if we do we must return a value compatible with that type or covariant thereof, using the return keyword. Lets see this in action :

package info.java8;
  Test class for maths stuff
public class MathsStuff {

    public static void main (String[] args) {
        int aSquare = squareNumber(5);   // The return value will go into aSquare
        A method that squares and returns the passed integer
    static int squareNumber(int number) {  
        int square = number * number;  
        return square;  // Here we use the return keyword to pass back a value

run square
Screenshot 2. Running the MathsStuff class.

The above screenshot shows the output of running our MathsStuff class. The return value from the squareNumber() method gets assigned to the aSquare primitive.

Final Parameters Top

There might be a come a time when we want to pass a variable to a method that we want to remain constant during the scope of the method. When we write our parameter lists we can prefix our variables with the final keyword. This makes the passed value a constant in the method, which cannot be changed, in fact trying to do so will cause a compiler error. The following code illustrates this:

package info.java8;
  A Class
public class FinalParam {

    final void usingFinalParam (final int i) {
        i = 0;  

run final param
Screenshot 3. Running the FinalParam class.

The above screenshot shows the result of trying to compile class A.

You can also use the final keyword to create final local variables, final instance variables, java constants and for preventing inheritance/overriding.

Related Quiz

Objects & Classes Quiz 5 - Methods - Basics

Lesson 5 Complete

In this lesson we took our first look at methods with some basic examples.

What's Next?

In the next lesson we take a second look at methods and the concept of pass-by-value.