Java Methods

by Gabriela C. Perez.

Share
|
Homepage | Submit your article | Contact | TOS
More articles on java  

You are here: Categories » » JAVA

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.

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.

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);
   }
   }

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. The second thing to notice is that the method main also takes a parameter, which is an array of Strings.

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.).

Leave a comment or ask a question
Total comments: 0

JAVA Disclaimer

  • The e-articles directory is not responsible for any and all copyright infringements by writers and authors. If you suspect the information contained by this page for any copyright infringements, please contact us to investigate the issue
What should you know before you ship your Java applet ~ The perfectly finished applet - Stop! Before you let the whole world know about your applet, make sure the answer to all of the following questions is yes: 1. Have you removed or disabled debugging output? (more...)
Deploying Java Applets in a Mixed Browser Environment - You can deploy applets for users of both Internet Explorer and the Mozilla family of browsers in one of two ways: Through pure HTML Through JavaScript Using Pure HTML (more...)
General Java Applet Deployment Considerations - How you deploy an applet depends on whether users access the Web page through the Internet or an Intranet, and the type of browser they use. Note this information about your users, then follow (more...)
Why Java programmers are taking one step ahead in software development industry - Various high quality programming languages are used in the Software Industry. Some of them are expensive, while some are affordable by nature, however all of these are vastly used according to the (more...)
SELECTION STATEMENTS IN JAVA - Like other programming languages java offers the control statements to control the execution of a program. The control statements in java are the selection statements, loop constructs and the jump (more...)
JAVA and its Advantages - In today's highly competitive world, JAVA has become one of the most secure technologies for website and software development. Prime benefits of JAVA are platform independency and easy availability (more...)
Java Tactics: Earn A Fortune With Java - Get the right Knowledge Get the right Papers Get the right Direction Get the Money Hi, my name's (more...)
Introduction to Object Oriented Programming (OOP) - The transition from a procedural programming (non-OOP) language to an object-oriented programming language is a large step for many programmers. It is true that both methods of programming can ulti (more...)
Operator Precedence in programming languages - Operator precedence deciphers the order in which calculations in an expression occur. Looking at the calculation example 3 + 4 * 6, the answer could be calculated by adding 3 and 4, which gives (more...)
Arithmetic Assignment Operators - The following assignment operators are similar to the increment and decrement operators that we have just seen. They are used so that you do not need to enter the source variable twice when ass (more...)

 
free content
    Copyright © 2006 - 2012 e-articles.info.
The texts, articles and tutorials in the directory are property of their respective owners and authors.