In the previous tutorial, discussed five elements of a java class. Method is one of them. Today we will learn about method of java class. As directly writing business logic are not allowed in java class. So we have to write business logic in a method. Method is used to write the logic of the program. Let's go for details of the method.
1. Method Signature : A method signature is the method name and the number and type of its parameters.
Example:- methodName(parameters);
calculate(int a, double b);
Note: In the above example calculate is the method name and int, double are the type of parameter a and b.
2. Defining Methods : Syntax for a method definition.
access optionalStatic returnType methodName( parameters ){
declarations;
statements;
return expression;
}
Explanation:
- Here, access is one of public, protected, package(default: no keyword used)or private, to indicate what other code may use the method.
optionalStaticis the keywordstaticfor static methods, omitted for non-static methods.returnTypeis the type of value returned by the method, if any. Methods may return any valid type, orvoidif no type is to be returned.- methodName is the name that you can choose but related to functionality is the best.
- parameters describe what information must be given to the method. Each parameter consists a type and a variable.
- The
declarationsandstatementsare just ordinary Java code. Thestatementsmay use any instance variables or static variables of the class, the parameters, or any variables declared within the method. - If the method is declared to return a value, the
expressionin the return statement must be a value of the correct type.
There are two parts of a method. One is Method Header and another is Method body.
Visit this site for next tutorial...

0 comments:
Post a Comment