Methods in Java

A method is a group of statements which identified by the name. It is used to define the behavior of an object. Following are the components of a method-

  • Return Type
  • Method parameters
  • return statement
  • Access modifiers
  • Nonaccess modifiers

Syntax

modifier return_Type method_Name(Parameters)
{
	//body of the method
}

Return type of a method

It is a type of value that a method will return. A method may or may not return a value. If a method does not return a value that has void return type. A method can return a primitive value or object of any class.

Method parameters

It is used to specify the type and number of values that a method can accept.

return statement

It is used to exit from a method, with or without value. If a method doesn't return any value, then it is not required to define a return statement.

Access modifiers

It controls the accessibility of a method. There are four access modifiers- public, protected, default, and private.

Nonaccess modifiers

It controls the behavior of a method. Some of the nonaccess modifiers are- static, final, abstract, etc.

Example

class TestEg
{
	public static int addExample(int a, int b)
	{
		return (a+b);		
	}
	public static void main(String args[])
	{
		int a = 10, b = 20;
		int sum;
		sum = add(a,b);
		System.out.println("The sum of a and b is " +sum);		
	}
}

Output

The sum of a and b is 30;