Java Tutorial Part 3

Java : Part 3

You have already learned the different statements in the earlier chapters, where most of the programs have been solved using general techniques.Moreover, those techniques were based on direct approach. Now is is the turn to solve the problems using a different technique, which is described under Method.

Method in Java Programming sets the behavior of a class object.

Let's consider the following program snippet:


[Image: wVGDz.jpg]


As you can see, the above program finds the sum of two integer numbers. First segment finds sum of A and B and the second segment does the same job, but with different variables. Both segments are used for the same purpose containing similar statements. Such programming technique increases the length of the program, takes more memory space and even arises problems in debugging. In order to avoid such problems, one segment of statements may be written outside of the program and can be applied a number of times in the program as and when required. This type of programming module is termed as Method or Function.
Hence, A program module used simultaneously at different instances of the program is known as Method or Function.


Defining A Method


A method may be defined as given below:

Code:
<Access Specifier> <Return Type> <Method name> (Parameter list)
{
// Body of the Function
}
Access Specifier : Access specifier is Public or Private. A method declared without any access specifier is by default treated as Public. Private specifier will be discussed in the next chapter.

Return Type:Type specifies the data type of the value returned from the Method. If the answer is a number like in the snippet, it should be int and likewise.

Function Name:Function name may be any name preferably related to the process. The function will be called whenever it is needed in the program using the name specified.

Parameters:Parameter list are the variables receiving the values, passed from the arguments during the method call.

Now Let's take a look at an example for a method.

Quote:public int example() //Header of the Method
{ // Method Opening
return (value); // Body of the Method
} // Method Ends
Here,the first line is referred as header. It contains return type, Method name and parameter list. In this example, the parameter list is left empty, which means no value is passed to the method during its call. This header is also known as Method Prototype. The list of parameters is called Method Signature.
The function body contains a set of statements for related operation. These statements are enclosed between a pair of curly brackets and known as Method Block.
The statement, which sends back the value from a method to the caller program is known as Return Statement.Basically, return is used at the end of a function, which can also be, referred as function terminator.


Types Of Methods
  • Pure Function Or Accessor Method.
  • Impure Function or Mutator Method.

Pure Function

A function, which returns a value to its caller module, is known as pure function. It is also called accessor method, as it doesn't change the state of an object.

So for the first time, let's check a real life example for a working program that used A Method or Function.


Code:
class operate
{
int sqr(int x)
    {
return(x*x);
    }
int sum(int a,int b)
    {
int c;
int c=a+b;
return(c);
    }
}

The functions sqr and sum both returns Integer type values, hence called Accessor.The return type int indicates that the outcomes of the functions are integer type values, which in turn returned to the caller. The return statement should be last line of a function. It means a statement is meaningless with respect to the functions and does not execute.

Methods With Parameters and Actual Usage of Methods in Program

So now let's look how we can use the methods in a program effectively.First check this piece of code :

Code:
class sum
{
public int sum(int a,int b)
{
int c=a+b;
return(c);
}
public static void main(String args[])
{
sum ob=new sum();
int n=5;m=8;
p=ob.fact(n,m)
System.out.println("The sum of the numbers is"+c);
}
}

So in the above program snippet, we have created a new function which returns the value of 2 numbers entered, which is accepted through the main function. So when the function is called in the program, it accepts the two values and assign it a and b and does the calculation and returns the value as C. This C is displayed as the output. This makes it much more easier to use the same function usable again and again anywhere in the program.

Passing Values To The Method

The values from the caller program are passed to the Method in the following two ways:
  • Pass By Value
  • Pass By Reference
Pass By Value

In this system, the values from the actual arguments are copied to the formal parameters. Hence, any change made in the formal parameters does not reflect the actual arguments. The actual arguments remain intact.

Pass By Value is the process of passing a copy of actual arguments to the Formal Parameters. Any change made in the formal parameters does not reflect on the actual argument.

All primitive type data such as int, float, char, long, double etc. are by default passed to the function by using Pass By Value System.

Illustration to Invoke a function using Pass By Value

Code:
class example
{
void show(int x,int y)
{
x=x+2;
y=y+2;
System.out.println("Formal parameters after function operation"+x+' '+y);
}
public static void main(String args[])
{
example ob=new example();
int a=5;b=6;
ob.show(a,b);
System.out.println("Actual Arguments after function operation"+a+","+b);
}
Vales of the variables after program execution

Formal Parameter after function operation 7,8.
Actual arguments after function operation 5,6.

Pass By Reference

In this system reference of the actual arguments are passed to the formal parameters.In fact, actual arguments and formal parameters both represent the same memory location. As a result, any change made in the formal parameters during function operation will be reflected on the actual arguments and they will be affected accordingly.

Hence, Pass by Reference is the process of passing the reference of actual arguments to the formal parameters and any change made in the formal parameters will be reflected on the actual arguments.

Java system automatically manages the non-primitive data to be passed by the method as Pass By Reference. In general, arrays and object are passed through "pass by reference" operation.

Example to Illustrate Pass By Reference System


Code:
class pass
{
void add(int x[])
{
int i,l=x.length;
for(i=0;i<=l;i++)
x[i]=x[i]+2;
System.out.println("Parameters after change");
for(i=0;i<l;i++)
System.out.println(x[i]+"\t");
System.out.println();
}
public static void main(String args[])
{
int a[]={2,4,8,6,15};
pass ob=new pass();
ob.add(a);
System.out.println("Function arguments after function operation")'
for(int j=0;j<a.length;j++)
System.out.print(a[j]+"\t");
}
}
When function ob.add(a) is invoked the address of variable A, is automatically allotted to X and hence array A of the caller program is treated as X in the called function. On Increasing the elements of array X by 2, brings the same change in the array A itself.
As th program given in the example above is executed, the same values are displayed either through array X or array A respectively.

Function Overloading

Java language facilitates designing a number of functions with the same function names. However, their parametric types must be different. Such functions are called Overloaded functions and the system is said to be Function Overloading

Polymorphism is the process of declaring functions by matching the types and number of arguments to insure which of the function will be called. This phenomenon is known as Early Binding or Static Binding.
System finds the best match of the function arguments and the parameter list during program compilation. This phenomenon is termed as Static Binding.

Hence, Function Overloading is the process of defining functions/methods with the same function names but with different number and types of parameters.

Why To Use Overloaded Functions?

An object contains State and Behavior. Some times, it is intended to perform similar operations with a slight change in the parameters.
A number of Methods are used to implement a single interface in Java i.e, Polymorphism. If different function names ares used for similar operations, then users may have a lot of interactions and they require to remember a number of function names at the same time of invocations.
Hence, it is reliable to use many functions with the same names for similar operations.

Recursive Function

Some times a function is required to be called in the body of the same function in order to encourage repetitive operations a number of times. Such function is said to be recursive function.
A function is designed in such a way that it calls itself in its body is called Recursive Function.


Example of a recursive function :

Code:
class recursive
{
int fact(int n)
{
if(n==0)
     return(1);
     else
     return(n*fact(n-1));
}
public static void main(String args[])
{
int k=5,f;
recursive ob=new recursive();
f=ob.fact(k);
System.out.println("Factorial of the no."+k+"is"+f);
}
}
That's it for this tutorial. I hope you get a basic idea of Functions, how you can use them, the various types of functions and everything related to it. Try it out yourselves. 
Make some functions and play with it .