Java 07: Method

As we know class is a blueprint for an object. Class is a description for JVM on how it should create an object based on the class. Every object that belongs to a class might have different instance variable value. Should this be same for method as well?

Every object has same method but may produce different outcome because it has different instance variable value. So what does this means? Say Phone class has a instance variable, dialNumber. The call() method makes phone calls, but the object will make a call to receiver whose number represented by dialNumber value of that object. Even though their action is same which making a call but each object makes call to different person. The method looks something like this.

void call(){
    myPhone.makeCall(dialNumber);
}

A method is a collection of statements grouped together to perform an operation. Build in methods from java library that we become familiar with are like System.out.println(), Math.random(), Integer.parseInt() and JOptionPane.showMessageDialog().

This note will discuss how you can write your own method for solving programming problem. This is syntax for defining a method.

modifier returnType methodName(Parameter_list){
        //method body
}

Method header is the first line of the method definition which includes modifier, return value type, method name, and parameter list enclosed in parentheses.

Modifier is public, private or protected and static. Depending on this modifier the method will behave differently.

Return type specifies what type of data the method will return at the end of the method execution. Some methods don’t return value after performing desired action. In this situation we write the keyword void as its return type. Non void method is a method that returns a value, so the return type could be int, float, double or object. For a non void method a return statement is a must.

Parameter looks like variable declaration. When we call a method, values that you pass will be placed into parameters. The value that you pass when you call method is known as actual parameter or argument. It is natural so pass more than one argument to method.

In this situation we need a list of parameters or parameter list. This tells us type, sequence and number of parameters a method have. In some situation method don’t take any argument this is known as no-arg method. For example, sayHello() is a method that don’t have parameters.

Method body is where a collection of statement that describe how the method do it job. for example a method called max uses if statement to determines which number is larger and returns the larger number. A return keyword is used to return value. A method is terminated when return statement is executed.

After defining a method, what the method does a so on, now we can use the method to perform these action by calling the method. These are known as method call or invoke method. Depending on the method whether it is returning a value or not, we call the method a little bit differently.

When a method is returning a value a method call is treated as a value, and we assign this value to a variable. Lets look again how we assign a value to variable:

int a = 11;

now instead of assigning a literal value, assign a value that is returned by a method in this case the method we use in max().

int a = max(11,6);
Another way of calling this type of method (reminding think it as a value).
System.out.println("Max value is " + max(11,6));

If the method is not returning a value, the method is treated as statement. Example of void method is System.out.println() method

System.out.println("Having fun learning Java");

We are not allowed to call non returning method like non void method. But call non void method like calling void method is allowed. In this case the value returned by the method will be ignored.

When passing an argument, the order of the argument must be in same order as the respective parameter in method signature.

void printMessage(String message, int times){
    int counter = 0;
    while(counter < times){
        System.out.println(message);
        counter++;
    }  
}

This method prints a message for number times given by user. Say the user call this method like this printMessage(“Hi”, 5), the method will print the “Hi” message 5 times, but trying to do same like this printMessage(5, “Hi”) will be compilation error. This is because the first parameter of this method is type of string but we pass an integer value. This type mismatch alone will fire the compilation error. The second parameter is integer but the argument we pass is a string, this is another mismatch.

Another type of error is caused when not enough argument is being passed to the method. For example, if we just pass message but not how many times to display like this printMessage(“Hi”), this will cause not enough parameter error.

When we pass a value to a method, we are only giving a copy of the original value to the method. The parameters are separate independent memory space all together from the argument’s memory space. That means the original values are not modified. Let’s take a look at his program

public class PassByVal{
    public static void main(String[] args) {      
        int num = 5;
        System.out.println("Main: Num value before adding "+ num);             
        System.out.println("Main: Returned num " + addNum(num, 3));            
        System.out.println("Main: Num value after adding "+ num);
    }

    public static int addNum(int num, int b){
        System.out.println(" Inside method: received "+ num);
        num = num + b;
        System.out.println(" Inside method: after add "+ num);
        return num;
    }   
}
Main: Num value before adding 5
 Inside method: received 5
 Inside method: after add 8
Main: Returned num 8
Main: Num value after adding 5

Method Overloading

Variable names must be unique in a single program. Two or more variable cannot have same name. The same principle applies to methods as well. In a single program not more than one method must have same name. However if the method signature is different than repeating method name is allowed.

This is because sometime repeating same name for method cannot be avoided. If you are going to do same operation, only difference is the data that we are doing operation on is different.

For example, max(int,int) and max(double,double) has two different method signature so using same name is allowed. The first method takes two integer value as parameter and second method takes two double values for determining largest values between two. When JVM see this it will automatically choose appropriate method to use.

class MethodOverloadingExample{
    public static void main(String[] args){
        System.out.println(max(6, 2));
        System.out.println(max(1.2, 5.78));
    }
    public static int max(int a, int b){
        if(a > b)
            return a;
        else
            return b;
    }

    public static double max(double a, double b){
        if(a > b)
            return a;
        else
            return b;
    }
}

Output

6
5.78

If we look closely at these two methods, the operations are same if statements but differ in sense of its parameters. So if we call max(1,2), JVM will automatically execute the first method, and if we call max(1.2, 4.3), JVM will execute the second method.

What will happen if we call max(1, 4.3) or max(3.1, 3), JVM will issue an error saying that the method that we are trying to call is not defined. In fact this is one of common mistake, thinking that JVM should however figure out how to solve this problem. It does not work that way.

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net