Methods

0
131

Methods

A method is some number of statements written together which can be called at any point by the method’s name.

Defining Methods
[java] public double method_name(double a ,int b)
{
//body
}
[/java]

public:Modifier
double: Return type
double a ,int b:Parameter list

Example:

[java] public double sum(double a ,int b)
{
double s=a+b;
return s;
}
[/java]

Calling a Method:

[java] public class ExamSum
{
public static void main(String[] args)
{
double a = 11.8897;
int b = 1;
int c = sum(a, b);
System.out.println(“Sum = ” + c);
}
public double sum(double a ,int b)
{
double s=a+b;
return s;
}
}

[/java] Output:

Sum=12.8897

The parameters in java can be passed by value or by reference.

Passing parameters by value:
The example stated above for the calling of method is uses pass by value.Passing Parameters by Value means calling a method with a parameter. Through this the argument value is passed to the parameter.

Passing parameter by reference:
A reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.


Method overloading

When a class has two or more methods by same name but different parameters, it is known as method overloading.
Example:

[java] public class ExampleforOverloading
{ public static void main(String[] args)
{ int a = 10;
int b = 68;
double c = 6.37;
double d = 3.4;
int r1 = maxFunc(a, b);
double r2 = maxFunc(c, d);
System.out.println(“Maximum Value = ” + r1);
System.out.println(“Maximum Value = ” + r2); }
public static int maxFunc(int n1, int n2)
{ int max;
if (n1 < n2)
max = n2;
else
max = n1;
return max;
}
public static double maxFunc(double n1, double n2)
{
double min;
if (n1 < n2)
max = n2;
else
max = n1;
return max;
}
}

[/java] Output:
Maximum Value=68
Maximum Value=6.37

CONSTRUCTORS:

A constructor is a special method that is used to initialize an object.Every class has a constructor,if we don’t explicitly declare a constructor for any java class the compiler builds a default constructor for that class.
The main difference between method and constructor is that a constructor does not have any return type.
1.Default constructor
Example:
[java] class Eg
{ public Eg()
{
System.out.println(“This is a default constructor”); }
}
2.Parametrized constructor
Example:
class Eg
{ public Eg(int n, String s)
{
System.out.println(“This is a parameterized constructor”);
}
}
[/java]

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.