Tuesday, October 16, 2012

Methods & parameters

Methods & parameters


Topics : MethodsIdentifiers

Types of methods

Parameters (arguments)

Overloading methods

Methods


In Java, a method is a block of code that performs a certain task. This is *almost* the same as a C++ function. There are some small differences.

A method can be private, protected, or public and static or non static. The return types can be anything primitive (int, float etc...) or user defined.

Here is how to define a Java method:

identifier type Name( argument(s) ){
//code here
}


where identifier is either public, private or protected; type is the return type of the function; Name is a useful name of the method and arguments is the parameters to pass to the function ( if any).

Identifiers


As stated, a method can be public, private or protected.

A public method can be seen by any class, anywhere. There are no restrictions regarding public.

A private method can be seen only within the class itself. It cannot be accessed elsewhere.

A protected method is not commonly used but it means that it can be accessed within the class or any of its subclasses.

Types of methods


A method that uses instance variables of that class is called an instance method. This is the default for a method.

A method that uses NO instances variables can be declared static. It must NOT use any of them otherwise there will be a compiler warning. The static methods tend to compute something from arguments of that method instead of using the variables.

Here is a valid static method:

public static double mean(int n1, int n2, int n3){
int sum = 0;
double ans = 0.0;

sum += n1 + n2 + n3;

ans = sum / 3.0;

return ans;
}


The above will compute the average of the three integer parameters (see below for description of parameters). Notice that it only uses local variables to the method and only the parameters. If it tried to use any instance variables there will be a warning.

Method parameters (arguments)


A parameter (or argument as we know already), is a variable given to a method. A parameter to a method is also called a formal parameter.

PLEASE NOTE: all parameters that are not of object types are PASSED BY VALUE! All others are PASSED BY REFERENCE (including arrays). This is a common mistake made by Java newcomers.

Let's see a simple class and a simple instance method:

Example 1:
Simple method



public class SimpleStatic{
private static int s=3, t=7;

public static void main(String args[]){
System.out.println("sum: " + sum(s,t));
}

private static int sum(int a, int b){
return a+b;
}
}


The above program will be compute the sum of the 2 instance variables. The reason the method is static is because the instance variables are static as well as the method is being called from the static main() method.


Since we know that object types are passed by reference, let's use an array as an example.

Example 2:
Simple array method



public class SimpleArrayMethod{
public static void main(String args[]){
int s[] = new int[5];

for(int i = 0; i < 5; i++)
s[i] = i*3;

int sum = sumArray(s);

System.out.println("sumArray: " + sum);
}

private static int sumArray(int arr[]){
int sum = 0;

for(int i = 0; i < arr.length; i++)
sum += arr[i];

return sum;
}
}


Here, we declare an array of size 5 and with the use of a for loop, we assign values to each cell. Then we call the static method sumArray() and pass the entire array to the method. What is returned is the sum of the values in the array.


Now let's see an example with a String to see, if we change something in the method, if it will also change in the main() or wherever we called it from.

Example 3:
Simple String method



public class SimpleStringMethod{
static String word1 = "Cats";
static String word2 = "Dogs";

public static void main(String args[]){

System.out.println("Before call:nword1: " +
word1 + "nword2: " + word2);

switches(word1,word2);

System.out.println("nAfter call:nword1: " +
word1 + "nword2: " + word2);
}

private static void switches(String w1, String w2){
w1 = w2;
w2 = "Changed!";
}
}


Here, we wrote a method called switches that takes two String arguments. It is seen that we are changing the values of the words in the method. The words in the main method DO NOT change. Once we attempt to change a variable in a method, we lose the reference to it from the place we called it. Therefore, although it is passed by reference, we do not change the values of the variables.

Here is the output of the following program:

Before call:
word1: Cats
word2: Dogs

After call:
word1: Cats
word2: Dogs



Overloading methods


In Java, many methods are already written for you, such as the equals() method in the String class as an example. If you wish to create your own version of a method that may take different data types as parameters, you can by what’s called overloading.

Say we have a short program as follows:

public class OverloadExample{
public static void main(String args[]){
talk("Hey there!");
talk("Hey there my name is John", "John");
} //main

public static void talk(String t){
System.out.println(t);
}

public static void talk(String t, String name){
System.out.println(name + " said this: " + t);
}
} //class


Here, we see that there are two methods called talk, both of which return void and are named the same. The only difference is the arguments of these methods. This is allowed in Java. We have now overloaded the talk() method.

BE CAREFUL: It is NOT okay to have two methods with the same name and DIFFERENT return types. This will produce an error in Java. Specifically, it will say “Duplicate method [name(type)] in [class name]”.

No comments:

Post a Comment