Skip to main content

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 26

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 25 | Lesson 27 >>

Lesson 26: How to implement User Defined Methods in Java

In the previous lesson, we saw that a method in Java is just a group of instructions that are coded and given a name. When a method is called by its name in a program, the instructions are executed to accomplish an action.

We also learnt that a method has two parts; the method header and the body. The method header contains Method return type, Method name and Values passed to the method as Parameters. The method body contains the actual instructions that will be executed when the method is called.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

Now, let us implement the method we had in Lesson 25. This method is supposed to receive two int type values x and y and sum them.

The total will be stored in another int type value z. It is this int summed value that will be returned to the calling program which, in our case, will be the main method.

Once user define method is complete, we shall create a main method to call our method into action. The main method will be created in another class.

Creating methods separately from the main method gives us flexibility of calling different methods. In this way, a method can be called or be accessed by other different methods. Below is an image from the previous lesson about the structure of methods in Java.

The Structure of a Method in Java

The Structure of a Method in Java

To start with, we are going to create a new class, call it SumMethod, and then inside this class, we shall define the sum method. Type or copy and paste the following code.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

Setting up the main method

If you attempt to run the class as it is now, Java will throw a warning. That is because our class does not have a main method. For us to see our method working, we are going to create another class, call it OwnMethod. Inside this class, we are going to define our main method where we shall call the sum method into action.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

We are going to prompt the user to enter two int values and then use the sum method to return the total sum of the two values. Declare the three int variables as shown below;

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

Now, to make our program even more interactive, we are going to use JOptionPane input and output boxes to receive inputs from the user and display the total sum. We covered JOptionPane input and output boxes intensively in Lesson 6. Add the following line of code just before the class name.

import javax.swing.JOptionPane;

A JOptionPane input box handles string values only, so what we shall do is to convert the string inputs from the user into int type and store them into the int variables Num1 and Num2 we declared earlier. The code so far should look as shown;

package myfirstprogram;

import javax.swing.JOptionPane;
public class OwnMethod {
    public static void main(String[] args) {
     int Num1, Num2, total;
       
   //Get inputs from user and convert them from string to int  
Num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter first number"));
     Num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter second number"));      
   }  
}

Notice in the above icode, we are getting inputs from the user and converting them into int values using Integer.parseInt() method before finally assigning them to Num1 and Num2 variables. Now that we have two int variables to sum up, we are going to call out sum method into action.

How to call a method in Java

Our sum method that we want to call is in another class called SumMethod. To access method sum, we need to create an object of that class. So, include the following line of code in the main method.

Scroll to Continue

SumMethod value = new SumMethod();

To create an object of the class, we name the class and then our object name. In this case, we have called our object value.

After the equal sign, we include the keyword new followed by the class name. Using the new object, we call the method and pass the int variables to be worked on. Notice Java can now recognize our method sum.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

How to pass values (parameters) to a method in Java

When you type the dot just after the object name value a list will popup so that you can select the method to use. Select the sum method and as you can see on the image above, the method require two int parameters. These parameters are passed inside the round bracket of the method and we pass them as follow;

total = value.sum(Num1, Num2);

The two int values, Num1 and Num2, are passed by value to the method, Num1 as x and Num2 as y. Once the sum method has summed up the two values, it returns the sum as z which is captured in the total variable.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

The two values that we are passing over are separated by a comma and they must be of the same int type as the int type expected by the method. The last statement missing in our program is the output statement.

Again, we are going to use JOptionPane output box to display the results but then we have to change the int value into string for JOptionPane. The complete main method code should look as shown below. Run the program and see if it will call the sum method.

User Defined Method in Java

package myfirstprogram;

import javax.swing.JOptionPane;
public class OwnMethod {
    public static void main(String[] args) {
     int Num1, Num2, total;
       
     //Get inputs from user and convert them from string to int
Num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter first number"));
     Num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter second number"));
        
     SumMethod value = new SumMethod(); //Create new object
     total = value.sum(Num1, Num2); //Call sum() method and pass parameters
     JOptionPane.showMessageDialog(null,"Total = "+Integer.toString(total));   
   }  
}
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-26

Summery:

To write User Defined Methods (UDMs) in Java programming language;

1. Define the user defined method and specify the required values and their types if any. Remember not every method takes in values (Parameters).

2. Methods that do not require values are referred to as void methods. The returned value must be of the same type as the method return type in the method header.

3. Create the main method to be used in calling the UDM method.

4. Create an object of the class to access the method.

5. Call the method by passing correct parameters.

Exercise:

1. Write a User Defined Method in Java that returns the average of three int values

2. Write a User Defined Method in Java that receives three int values and returns the biggest

3. Write a User Defined Method in Java that makes use of string parameters

Try to write different methods that require different types of parameters so that you can have a grip on creating your own methods in Java. In the next lesson, we shall look at classes in Java programming languages. See you then.

<< Lesson 25 | Lesson 27 >>

Want to make money online?

Related Articles