Broad Network


Methods in Java

Java Basics – Part 12

Forward: A Method is a set of statements that perform a specific task. In this article I explain methods (functions) in Java.

By: Chrysanthus Date Published: 2 Sep 2012

Introduction

This is part 12 of my series, Java Basics. A Method is a set of statements that perform a specific task. When you will get to writing programs, you will realize that programs are very long. You will also realize that there are groups of statements that will have to be doing the same task in different parts of the code (program). You do not need to type this group of statements in different parts of the code. You can type it once, and then call it wherever it is needed in the code. In this article I explain methods in Java.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Defining Methods
The group of statements forms the method, but you need to group them in a particular way. By doing this, we say you are defining the method. This process can be split in two phases.

A method definition consists of the following in the order given:

- The data returned type (see below)
- The name (variable) of the method.
- A list of parameters to the method, enclosed in parentheses and separated by commas (see below).
- The statements that define the method are enclosed in curly brackets. The statements in a method can have among them calls to other methods defined in the current program (application).

A Class
Consider the very first code you wrote of Hello World. This is the code:

class Hello
    {
        public static void main(String[] args)
            {
                System.out.println("Hello World!");
            }
    }

In simple terms, a class is a piece of code that can have variable declarations and methods. The above class has just one method. The code for only the class above, extracted is:

class Hello
    {

    }

It begins with the reserved word, class, meaning the beginning of the class code. Next you have the name of the class. It is conventional to begin the name of the class with an upper case letter. Then you have the opening brace, {.  After that you can have variable declarations and methods; then you have the closing brace, }.

In the simple full class above, there is a construct inside, which is:

        public static void main(String[] args)
            {
                System.out.println("Hello World!");
            }

This piece of code is an example of a method. This code is called the main method. In fact if you look at the top line you should see the word, main. I will explain the details of the main method later in the series. For this particular method, there is only one statement in its block. However, there can be many statements in the method’s block as you have seen in the previous parts of the series.

Every Java program (application) must have the main method. Execution of a program starts at the main method. The class having the main method is called, the main class. It is the responsibility of the programmer to give the name for the main class, such as, Hello, above.

Other Methods of the Program
You normally will have more than one class in a program. A class can have more than one method. It is good to have just the main method for the main class. Any other method you want should go into a different class.

A Method Example in a Different Class
In the following example, I define a method that will add two whole numbers, find the square of the sum and then prints (display) the result. The method is in a class called, Calculator.

class Calculator
    {
        void myMthd()
            {
                int num1 = 2;
                int num2 = 3;

                int sum = num1 + num2;
                int square = sum * sum;

                System.out.println(square);
            }
    }

The name of the method is, myMthd for “my Method”. You can clearly see the method in the class, Calculator. I am the one who has given the name of the class, that is, Calculator. The method begins with the word, void (see explanation below), then a space and myMthd(), then a block of statements.

In the block, you have the declaration and assignment of the two integer numbers (whole numbers). The third statement in the block sums the two numbers. The fourth statement squares the sum. The last statement displays (prints) the square.

Calling a Method
Before a method can carry out its task, it has to be called. In Java, apart from the main class, an ordinary class like the Calculator cannot work. In Java it is objects like the primitive objects (int type, double type, etc.) that work. The method of interest here, is in the class, Calculator. In order for an ordinary class to work, you have to create an object from it and give the object a variable name. The creation process is called instantiation. At that time it is not really the class the works, it is the object that works.

The syntax to instantiate an object from a class is:

    ClassName objectName = new ClassName(arguments)

For our example, Classname is Calculator. Let us make the object variable name, squareSum. So for the example, objectName is squareSum. It is conventional to start an object name with a lower case letter. You already know the assignment operator. The operator, new, I introduced to you in one of the previous parts of the series on array, is the same “new” you are seeing here. Here, it means, give me a new object. Then you have the ClassName again and parentheses. I will explain what arguments mean later.

For the example, the object, squareSum will be instantiated as follows:

    Calculator squareSum = new Calculator();

An object created this way is not a primitive object because it is created from a class defined (described) by the coder (programmer); however, it is still an object. The story does not end there. The method still has to be called for it to carry out its task. The syntax to call a method is:

    objectName.methodName(arguments)

I will explain what arguments mean later. So you have the object name, then a dot (period) and then the method name. For our example, the code is,

    squareSum.myMthd()

Simple Calculating Program
All the above pieces of code for the example, are now retyped, combined, into a small program. Read the program and try it:

class Calculator
    {
        void myMthd()
            {
                int num1 = 2;
                int num2 = 3;

                int sum = num1 + num2;
                int square = sum * sum;

                System.out.println(square);
            }
    }

class CalculatorExample
    {
        public static void main(String[] args)
            {
                Calculator squareSum = new Calculator();
                squareSum.myMthd();
            }
    }

There are two classes here. For more than one class, you have only one main class with one main method in the program. The name of the file should be the name of the main class, for the javac compiler and the Java Virtual Machine.

For the class, Calculator, I have explained everything above. The class, CalculatorExample is the main class. Execution of any java program always begins from the main method in the main class. All the statements in the main method are executed in the order typed. So, any method that is not in the main method has to be called from the main method.

In the main method here, the first statement is the instantiation of the Calculator class into the object, squareSum. The second statement uses the squareSum object to call the myMthd() method.

When an object is instantiated from a class, the object has all the methods of the class. So, when the method is called through the object, it is the method of the object that goes into operation and not the method of the class; more on this later.

Note that here, it is the method of the instantiated object that displays the output and not the main method.

Called Method and Calling Method
The method inside the object is the called method. The statement in the main method that calls the called method is the calling method.

The return value and return type
A method can return a value. If a method returns a value, the calling expression e.g. squareSum.myMthd(), can be assigned to some variable. You can then do whatever you want to do with the variable. Consider the following program:

class Calculator
    {
        int myMthd()
            {
                int num1 = 2;
                int num2 = 3;

                int sum = num1 + num2;
                int square = sum * sum;

                return square;
            }
    }

class CalculatorExampleR
    {
        public static void main(String[] args)
            {
                Calculator squareSum = new Calculator();
                int result = squareSum.myMthd();
                System.out.println(result);
            }
    }

In the myMthd() method definition this time, instead of having the System.out.println() expression we have the return statement which is:

            return square;

This statement returns the value of square. A return statement begins with the reserved word, return, followed optionally by an expression. This expression can be a variable, e.g. square, as in the above case or just a value like 25. All statements must end with a semicolon.

We know that in the myMthd() method, square is a variable of type, int. Now, look inside the block of the main method. The right operand of the second statement is a method call (calling method) that calls the method (definition), myMthd(). This method call returns what was returned by the return statement in the method definition. It is the value of the variable named square that was returned. In the block of the main method, this return value is assigned as value to the variable, newly declared with the name, result. You can then use result in any way you want. The print statement in the block of the main method prints the value of result, which is the same value as that of square. This time, the print statement is not in the myMthd() method; it is in the main method.

Now, if a method definition (description) would return a value, then you have to indicate that at the beginning of the method definition. In the first program above, the method, myMthd() does not return anything, and because of that it does not have a return statement. So the method definition is begun with, void, which means in this case, nothing. In the second program, the method, myMthd(), returns a value from an int variable (value), so its definition is begun with int. You begin a method definition with the type of value it will return. That is, you begin a method definition with the object (data) type it will return. A method returns the "value" of an object, not the object itself.

Parameters and Arguments
Now, in the above method we can only deal with two particular numbers, which are 2 and 3. This is a disadvantage. The method can be written is such a way that when it is called, any pair of numbers, say (4, 5) or (6, 7) or (3, 9) or (12, 15), etc. can be sent to it for addition and squaring. Consider the following program:

class Calculator
    {

        int myMthd(int no1, int no2)
            {
                int sum = no1 + no2;
                int square = sum * sum;
            
                return square;
            }
    }

class CalculatorExampleArg
    {
        public static void main(String[] args)
            {
                Calculator squareSum = new Calculator();
                int result = squareSum.myMthd(4,5);
                System.out.println(result);
            }
    }

Notice in the class, Calculator that the method now does not have the int variables.

As said above any Java program must have a main method. If you want to have any code segment outside the main method executed, then the code segment has to be called from the block of the main method.

In the definition (description) of the method in Calculator, the parentheses now have two object declarations. Each of these declarations begins with the type of object and then the variable of the object. The variables are for the two objects we need (for addition and squaring). These declarations in this position, in the parentheses of the method definition, are called Parameters. The parameters are separated by commas. The variables of these parameters are used within the method definition.

In the main method, where the Calculator method is called; the parentheses have two integers. These values in this position are called Arguments. The arguments, corresponding to the parameters of the method definition, are separated by commas.

Read the above code sample again and try it.

Arguments as Variables
In the above program, the arguments are written as values (numbers). The arguments can be written as variables, but it is still the numbers that will be sent.

As said, the arguments to a method call, can also be variables, something like in:

    int result = squareSum.myMthd(num1, num2);

Note that the arguments, (num1, num2) are not each preceded by an object (data) type.

Read and try the following program:

class Calculator
    {

        int myMthd(int no1, int no2)
            {
                int sum = no1 + no2;
                int square = sum * sum;
            
                return square;
            }
    }


class CalculatorExampleVar
    {
        public static void main(String[] args)
            {
                Calculator squareSum = new Calculator();
                int num1 = 6;
                int num2 = 7;
                int result = squareSum.myMthd(num1,num2);
                System.out.println(result);
            }
    }

It is advisable to always make the variables for the parameters different from the corresponding variables for the arguments.

Passing Strings to a Method
A string is sent to a method in the same way that an int is sent to a method. However, always remember to type the string in double quotes where applicable. In the following program, the string is sent as a variable argument (str1):

class AClass
    {
        void strM(String str)
            {
                System.out.println(str);
            }
    }

class String1
    {
        public static void main(String[] args)
            {
                AClass anObj = new AClass();
                String str1 = "this is it.";
                anObj.strM(str1);
            }
    }

Do not forget to read and try the code, if you have not already done so. In the following program, the string is sent as a literal argument.

class AClass
    {
        void strM(String str)
            {
                System.out.println(str);
            }
    }

class String2
    {
        public static void main(String[] args)
            {
                AClass anObj = new AClass();
                anObj.strM("this is it.");
            }
    }

Do not forget to read and try the code.

To send a character, place the char in single quotes.

Naming Convention
It is conventional to begin the name of a class with an uppercase letter; the name of an object (primitive or instantiated) with a lower case letter; the name of a method with a lowercase letter. Remember, Java is case sensitive. Apart from what goes into a pair of quotes (i.e. a string) everything else in Java is case sensitive for practical intent and purpose.

You have seen a lot. We have to take a break. We continue in the next part of the series.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message