ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on February 17, 2020
dwachira profile image

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

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.

Source

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 | Source

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.

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.

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;

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.

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.

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.

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));   
   }  
}

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 >>

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)