JaVa
   

Methods

Methods are used as the building blocks of your program, performing tasks that can be called again and again and using the same code to perform the task each time. The basic but fundamental parts of a method's declaration are its name, its return type, parameter signature, and code segment curly brackets. The following lines of code are an example of a method declaration.

static void doSomething()
{
 // add code here
}


This method is called doSomething and has a return type of void, which simply indicates that the method does not return a value. We have seen the keyword void already, which is the return type of the method main. If the method doSomething were added to your main program class, then in the main method of the class you would call the method doSomething by entering the following code:

doSomething();


Note 

The method doSomething needs to be static at the moment because the method main, from which we are assuming the method doSomething is going to be called, is also static. The method doSomething would not need to be static if we created an instance of the class to which doSomething would belong. We will look at this in more detail in , "Multiple Classes."

If you want a method that returns a value, you must specify the return type of the method, and then you must use the keyword return in the method code block to specify the returned value.

static int getFiveDoubled()
{
 return 10;
}


The following method will simply return the value of 10 to wherever it was called from. The following line of code could be added, for example, in your main method to assign this value to a variable:

int myNumber = getFiveDoubled();


This line of code will assign the value of 10 to the variable myNumber.

Note 

Just because the method getFiveDoubled now has a return type, it does not mean that it cannot be called on its own.

getFiveDoubled();


This method will essentially do nothing, but you may have a method that performs a required task and then returns a value, which you want to ignore.

A method that has a return value (not void) must have a return statement at every possible exit point from the method. The compiler will pick up if a path without a return value is possible. On the other hand, if you have a method with return type void and then want to exit out of the method early, you can use the keyword return on its own. For example, take the following code:

public void doSomething()
{
 if(leaveEarly == true)
 return;
 // else continue with the rest of the code
}


This is similar to how the break statement is used to exit out of certain code blocks, such as switch cases and loops, as we saw earlier. The example we have just seen is a very basic example, but the use of the keyword return in this instance can be very useful for immediately exiting out of complicated code clusters in a given method.

Parameter Passing

The previous method, getFiveDoubled, is pretty pointless and very inconvenient because it will only return one value, 10. However, we could create a method that will take in any number, double it, and then return the doubled value. This can be achieved using parameter passing. Parameter passing allows you to pass values to a method that the method can then manipulate. The following method contains one parameter, which is doubled and the new value is returned.

int doubleNumber(int number)
{
 number *= 2;
 return number;
}


As you can see, the parameter is a variable called number of type int and is specified between the brackets that follow the name of the method. To call this method, you could, for example, use the following code:

// double of 2 equals 4
int myNumber = doubleNumber(2);
// then double its current number of 4 equals 8
myNumber = doubleNumber(myNumber);
// then quadruple its current number to equal 32
myNumber = doubleNumber(doubleNumber(myNumber));


This last line of code will call the method doubleNumber twice, first returning a value that is double the value of myNumber, which in turn is then passed as a parameter to the second call to doubleNumber that eventually returns the final value of 32, assigning it to the variable myNumber. To reiterate what we mentioned earlier, if the value that you pass as a parameter is of a primitive data type variable, the variable itself is not passed to the method. A new variable with that value is created in the method and then used. This means that changes made to this value inside the called method will not affect the value of the original variable. (This is not the case for objects, however, which can also be passed as parameters. This is discussed in .) You can also have more than one parameter, using a comma to separate consecutive parameters. The following simple example, SpidersEyes.java, contains the method multiply, which contains two parameters that are both of type int and returns the value of the two parameters multiplied together. Here is the code:

public class SpidersEyes
{
 public static int multiply(int valueA, int valueB)
 {
 return valueA * valueB;
 }
 public static void main(String args[])
 { int numberOfSpiders = 10;
 int eyesPerSpider = 8;
 int totalEyes = multiply(numberOfSpiders, eyesPerSpider);
 System.out.println("Total Eyes = " + totalEyes);
 }
}


When you run this code, the output should look similar to the following screen shot.

Java Click To expand
Screenshot-13:

There are two things to note from this example. First, we have used the keyword static for the method multiply. This is because there is no instance of the class SpidersEyes currently created, so in order for main, which is static, to be able to access the method multiply, it must be static also. (If this is confusing, do not worry about it for the time being. It will all become clear in when we start looking at using classes fully.) The second thing to notice is that the method main also takes a parameter, which is an array of Strings. We will learn about these in the next chapter.

Method Signatures

It is possible to have two methods that share the same name. However, they must have different signatures because otherwise when you wish to call one of the methods, the compiler has no way of differentiating one from the other, as the invocation of the method is based on the compiler recognizing the signature. Having methods of the same name but with different signatures is known as overloading the method. The name of the method and the parameter signature of that method determine a method's signature. The return type of a method does not influence its signature. Hence you cannot have two methods with the same name with two different return values with the same parameter signature. In the previous example, SpidersEyes.java, we had a method called multiply, which took two parameter values of type int, returning the value of the parameter values multiplied together. If we also included a method that did the same thing but used values of type double instead, we could create another method with the same name but with a different parameter signature.

public static int multiply(int a, int b)
{
 return a * b;
}
public static double multiply(double a, double b)
{
 return a * b;
}


The parameter signature is determined by the data types of the parameters and therefore the number of parameters also. Let's say that we now added the following method together with the previous two methods:

public static long multiply(int a, int b)
{
 return (long)(a * b);
}


The program would no longer compile because this method and the original multiply method share the same signature. They have the same name and also the same parameter signature—two parameters both of type int. The most obvious solution is to change the parameter signature of the latter method to take two parameters of type long.

public static long multiply(long a, long b)
{
 return a * b;
}


This will now work because the parameter signatures are different. If you are unable to alter the parameter signature in a reasonable manner, do not bother; just give the methods different names (e.g., multiplyInt, multiplyDouble, multiplyLong, etc.).

JaVa
   
Comments