A method is a programmed procedure
that is defined as part of a class. A class (and thus an object) can have more than one method.
Syntax
of method definition
modifier returnType
methodName(parameters) Exception List{
Method Body
}
Method definition composed of six
components :
modifiers : like private,
public, protected or default. We have already seen private, public
and default. Will discuss more about these in the packages section.
ReturnType : The type of the
value written by the method. If you don't want to return any value
make the return type as void. Return type will be any primitive type
or reference type.
MethodName : The name given
to the method
parameters: Method is defined
with parameters or with out parameters. A method can be defined with
any number of parameters.
Exception List: A Method can
throw any number of exceptions, will discuss about this on ExceptionHandling section
Method Body: The actual
implementation of the method goes here
Example
1. public int sum(int a, int b){
return (a+b);
}
modifier :
public
returnType : int
methodName : sum
parameters : a,b
Exception List : none
Method body :
calculates the sum of the two parameters and return the sum.
2. void sayHello(){
System.out.println(“Hello”);
}
modifier :
default
returnType : void
methodName : sayHello
parameters :none
Exception List : none
Method body : simply
prints the message “Hello” to the console.
If no access specifier
(modifier) specified to a variable or method, it assumes default
access specifier(modifier).
Naming
a Method
By convention method names
starts with a small character and starting character of subsequent
words is capitalized.
Example:
walk()
sleep()
setColor(String s)
getHeight()
Local
Variables
Variables declared inside a
method are called local variables. These are not accessible out side
of the method. You must initialize local variables before using.
Some
Points to remember
Trying to use local variables
before initializing causes compile time error
Example
class LocalVariable{ int sum(int a, int b){ int c; System.out.println(c); return (a+b); } }
Since “c” is a local variable,
when your program tries to access local variable, before
initialization, compiler will throw the error.
For the above program, you will get below error
LocalVariable.java:5: error: variable c might not have been initialized
System.out.println(c);
^
1 error
No comments:
Post a Comment