Methods in Java Programming

A method is strucure t group statements together to form function. You can define the a method just once and reuse it in  other programs. The syntax for defining a method in java is:

modifier returnValueType methodName(list of parameters ){
method body
}

The returnValueType is is the data type of the value that the method returns. Methods may perform certain operations without returning the value. In this case the
returnValueType is void. The return statement using the keyword return is required for a value-returning method  to return the result. The method ends when the return statement is executed.

When a programmer calls a method the program control is transferred to the called method. A called method returns control to the caller when it’s return statement is executed or when method-ending closing brace is reached.

Let us do an example that asks user to input two numbers and calculates the maximum among them.


import javax.swing.*;

public class MethodsInJava {
public static void main(String[] args){ //void main method

String datastring = JOptionPane.showInputDialog("Enter the first number:");
int firstnumber = Integer.parseInt(datastring);
String datastring1 = JOptionPane.showInputDialog("Enter the second number:");
int secondnumber = Integer.parseInt(datastring1);

int maximumnumber = max(firstnumber, secondnumber);

JOptionPane.showMessageDialog(null, "The maximum among "+firstnumber+" and "+secondnumber+" is "+maximumnumber);

}
public static int max(int num1, int num2){ //value-returning method that returns integer
int result;

if(num1 > num2)
result=num1;
else
result = num2;

return result; //returns result of datatype integer
}
}

Result:

Enter the first number: 6

Enter the second number: 8

The maximum among 6 and 8 is 8

There are mainly three types of methods in java according to their functionality: Accessor, Mutator and Factory. The main advantage of using Accessor and Mutator method in java is The role of return and set the values of an object’s state.

Accessor Methods:

Accessor method is used to return value of a private field like in the example givan below.

class Student{
private int id;
public Student(int id){
this.id=id;
}
public int getId()
{
return id;
}
}

Mutator Methods:

Mutator method is used to set the values of private field like in the example given below:


class Student{
private int id;
public Student(int id){
this.id=id;
}
public int getId()
{
return id;
}
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s