Topics Index

Methods - Importance >
Siva Nookala - 12 Apr 2016
Every method declared contains a method name, input parameters and return type. These 3 things comprise the method signature. The definition includes the body along with the method name, input parameters and return type.

The syntax for a method is

    type methodname1(input-parameter-list)
Here methodname1 specifies the method name, input-parameter-list specifies the list of parameters and there data types, type specifies the return type of the method. The method-body includes the body or set of instructions which needs to be executed as part of the method.
  • There could multiple input parameters for a method. Also, method can exist with out any parameters as well. i.e. method can have 0 or 1 or more parameters.
  • The return type can be any of the data types like int, short, double etc., If there is nothing to be returned from a method, then the return type is void. Which means no value will be returned from this method.
  • For a method with return type not as void, it should definitely have a return statement at the end of the method to return the value.
  • A method can be called to initialize a variable, assign to an existing variable or called as part of an expression.
  • There is no dependency between input parameters and return type. They could exist with out the other. So when we have input parameters, it is not necessary to have a return type and similarly when we have return type, it is not necessary to have parameters.
int add(int a, int b)
    int result = a + b;
    return result;
The method defined above adds two integer values and returns the sum as an integer. Here add is the methodname, the parameters are int a and int b and the int in the beginning of the method declaration is the return type.
A method which does not take any parameters and does not return any value will look like this.
void printHello()
Since the return type is void, we need not return any value, so the return statement is not required here.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.