Defining a method in Java
Methods are
considered as behavior in a Java Program.
Any changes to variables or any other objects in class are
done using methods.
Structure of a method.
access-specifier return-type method-name(parameters)
{
}
Simple example of a method:
public void sayHello()
{
System.out.println("Hello Tom !!");
}
A method can have one or more parameters.
Example consider a method to add two numbers
public void add(int num1,int num2)
{
int sum=num1+num2;
}
A method with return type void means that the method will
not return anything, but if a method requires to return back something it will
have return type other than void.
And a point to remember here is that it will require to
include a return statement at the end of the method.
Or in simple words. IF A METHOD RETURN SOMETHING, LAST
STATEMENT IN THE METHOD WILL be the return statement.
Example of a method
with return statement
public int square(int num)
{
int i=num*num;
return i;
}
Asterix Solution Provides Core And Advanced Java Training
for Beginners. 35 Days Java Training Program is a Job oriented Java Training
Program to be completed in 35 training days. This Java
Training encompass all the modules required for a candidate to be a
Professional Java Developer.
[Source : http://www.javawithz.in/2013/10/methods.html ]
No comments:
Post a Comment