Skip to main content Skip to docs navigation
TechSpiderTutorials

Java Methods

The code that operates on the data is referred to as member methods or just methods. (If you are familiar with C/C++, it may help to know that what a Java programmer calls a method, a C/C++ programmer calls a function.)

The general form of a method:

type name(parameter-list) 
{
// body of method
}

Here, type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void.

The name of the method is specified by name.

The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty.

Simple Syntax

[modifiers] return_type/void method_name([arguments])
{
--------
---------
[return value/variable;]
}

Detailed Syntax

[private| public| protected] 
[static| final | abstract | strictfp|native|synchronized] 
return_type/void method_name([arguments])
{
statements1;
statement2;
[return value/variable;]
}

Types of Methods:

1. A method without return type & without arguments.

Example:
public void print()
{
System.out.println("Number is..1000");
}
Calling:
print() ; (or) obj.print();

2. A method without return type & with arguments.

Example:
public void print(int sno)
{
System.out.println("Number is.."+sno);
}
Calling:
print(500); (or) obj.print(500);
print(3400); (or) obj.print(3400);
                

3. A method with return type & without arguments.

Example:
 public int getNumber()
{
int sno=500;
return sno; (or) return 500;
}
Calling:
int tno=getNumber();
int tno=obj.getNumber();

4. A method with return type & with arguments.

Example:
public int square(int no)
{
int res=no*no;
return res;
}
Calling:
int tno=square(5);
int tno=obj.square(25);

Now, square( ) will return the square of whatever value it is called with.
That is, square( ) is now a general-purpose method that can compute the square of any integer value.

As these examples show, square( ) is able to return the square of whatever data it is passed.