Methods:
A java method is the collection of statements that are grouped together to perform an operation. .Now you will learn how to create your own methods with or without return values,
Syntax:
type methodName(parameterList)
{ /* body of method */ }
type specifies the type of data returned by the method including class types that you create. If method don’t return any value then type must be void. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty.
Method overloading is one of the ways that Java implements isomorphism. Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters.
Example:
class methodOverload
{
void Sum() //No Parameter is defined
{
System.out.println("No Argument is given.");
}
void Sum(int a) //One int Parameter is defined
{
System.out.println("Only One argument is given.");
}
void Sum(int a, int b) //Two int Parameters for sum
{
System.out.println("Sum of two given integers : " + (a+b));
}
void Sum(int a, float b) //One int and one float parameter
{
System.out.println("Sum of int + float :" + (a+b));
}
void Sum(double a,double b) //Two double Parameters
{
System.out.println("Sum of two doubles :" + (a+b));
}
public static void main(String args[]) //Main
{
methodOverload test = new methodOverload();
test.Sum();
test.Sum(5);
test.Sum(5,5);
test.Sum(5,3.5f);
test.Sum(3.5,2.95);
}
}
Post a Comment
Post a Comment
Please do not enter any spam link in the comment box