How to implement method declaration?
A Method is a series of statements that carry out a task. A method declaration include, as we mentioned earlier:
- Declaration
- Optional access modifiers (public, private, protected …)
- The return type of the method (void or returning data type)
- The method name (Ex: main)
- An opening parenthesis
- Optional list of method arguments
- Closing parenthesis
- An Opening curly brace
- A body
- A closing curly brace
Ex: public void calculateMethod() {}
Ex: private void idNumberMethod() {}
SCJP Tip: you can use more-than-one modifier while declaring class or its members. When you do so, the modifiers may appear in any order in that declaration. For example , you can apply the access modifiers either before or after or in between the other modifiers.
Arguments or parameters consist of information that a method requires to perform certain task. You can provide as many as parameters within braces in line with method declaration.
Ex: public void idNumberMethod (int myNumber)
Indicating method name with arguments within parenthesis can make a call to that method. A method in a class can be called from another class.
Ex: calculateMethod(319);
Sample Program:
Case: This program will print a literal string from method named “printSomething”. ‘main’ method call this method in line 5. Check line 5 again. You may find that this calling do not send any arguments as the parenthesis is empty. Also in the method declaration in line 8, you can see empty parenthes is. Save this code as “Caller.java”.
This is the output:
When you write a method declaration for a method that can receive an argument, you must include the type of the argument and a local name for that argument.
Sample Program:
Case: This is an implementation of “Caller.java”. Instead of print something, main method send a text to printSomething method.
This is the output:
A method may require more than one argument. If so, you have to indicate data type of each argument separately and to define a local name. Arguments can be separated by commas.
Ex: public void calculateMethod(int Number1, intNumber2, String operator)
To make a call to this method: calculateMethod(22, 4, “+”);
Sample Program:
Case: You have two numbers to multiply. You can send those numbers to another method as arguments.
This is the output:
SCJP Tip: That’s basic again! Now the real declaration of a method:
[modifiers] returntype methodName([argumentList]) {
[method body]
}
returntype : If you want to return something (As in next sample program) then you want to state its data type here.
methodName : ID of your method (Method Name).
([argumentList]) : Arguments that the method will receive.
Ex: public string find(String wordToFind);
No comments:
Post a Comment