Ordinary Methods in Java

We’ve seen the use of methods in our use of the Keyboard class, which we used like this:

int a;

a = Keyboard.readInt();

It’s very fortunate that we don’t have to type out tens of lines of code every time we want to get a number in from the user. That shows just how useful methods are.

Methods, then, are a bundling of several or a great many lines of code into a little package which is then called (or invoked) by another method. The method that does the calling we’ll describe as the calling method, or superordinate method. The one that is called, we’ll describe as the called method or subordinate method.

superordinate method  subordinate method

Sometimes a calling method needs to send data to the called method. At other times there’s nothing to send. Sometimes the method sends data back to the called method; at other times there’s nothing to send. A way of getting data back from a called method to a calling method is to use the return statement. It is worth noting here that there is absolutely no other purpose to the return statement.

If, for example, a method is designed to print five asterisks, and a called method wants to use it, then no data is passed from calling method to called method. In addition no data is passed back. When the five-asterisk method is called it simply prints five asterisks and then the calling method continues.

If, for example, a method is designed to print a number of asterisks, decided on by the calling method, and a called method wants to use it, then a number representing the number of asterisks the calling method wants printed must be passedto the called method. Once again no data is passed back.

Perhaps, however, a calling method owns two numbers and wants the called method to calculate the power of the first of those to the second (for example: 2 to the power of 3 gives 8). Suppose, further than the called method needs to know the result. This means that two numbers go from the calling method to the called method and that one number comes back from the called method.

Returning now to the line of code we started with which we started this discussion, that is:

a = Keyboard.readInt();

Here no data is passed to the method, but one piece of data comes back from the method, namely the integer the user typed in. It’s captured into the variable called a. We can tell that no data is passed to the readInt method, because there’s nothing in the brackets after readInt.

If the method had been one that was designed to place an integer on the computer screen, then an integer would have been sent to the method and no data would have been sent back:

Keyboard.writeInt(a);

Note that there is no attempt made in this call to trap data coming back, because, of course, there’s none. We can see that no attempt is made because the a = preceding the method call has gone. It was there for the readInt, but not for the writeInt.

The software below (in blue, green and brown writing starting towards the bottom of page 4) illustrates almost every permutation possible in regard to method calls. There are methods with return type int, double, boolean or void, (the absence of something returned). There are methods that have arguments passed into parameters, at the point of call, and those that don't.

In particular, it's worth observing that those methods below that have non-void return types are invoked in conjunction with assignment statements, if or System.out.println. This is to make use of whatever is returned. See the listings below.

Those methods that have return type void are called like this:

ClassName.methodName();

i.e. the method call is on a line all on its own, no if, no assignment, no Sop.

Variables of formClassName.methodName(...)in the calling method are filled by return statements in the called method. That's the only way to fill such variables. Further, the return statement has no other purpose, than to fill such variables.

Note that in any Java system of multiple files and multiple classes, there can only be one main method.

Consider now a Java program fragment to add up all the numbers between 1 and 30:

total = 0

i = 1;

while(i < 30)

{

total = total + i;

i = i + 1;

}

System.out.println(total);

We can make this into a method in say a class called MyMethods

public class MyMethods

{

public static int addTo30()

{

total = 0;

i = 1;

while(i < 30)

{

total = total + i;

i = i + 1;

}

return total;

}

}

Note that the System.out.println(total); line has been replaced by

return total;

This sends the result back to the calling method.

You might have a line in the calling method like this one, where in this case, the result sent back is captured into answer:

answer = MyMethods.addTo30();

If the method were to take on the responsibility of reporting directly to the human user it would be called like this:

MyMethod.addTo30();

There is no extra bit to capture the returned value.

Here’s what the addTo30 method will look like now:

public class MyMethods

{

public static void addTo30()

{

total = 0;

i = 1;

while(i < 30)

{

total = total + i;

i = i + 1;

}

System.out.println(total);

}

}

Notice the changes in red. The return type void goes with the fact that there’s nothing returned to the superordinate method.

And now a version that adds to a number decided on by the calling method.

public class MyMethods

{

public static void addToN(int number)

{

total = 0;

i = 1;

while(i < number)

{

total = total + i;

i = i + 1;

}

System.out.println(total);

}

}

This version, with return type void is called using, say:

MyMethods.addToN(n);

Where n is an integer variable already filled with the number to which we want the addToN method to add to.

The value in n, in the superordinate method goes into the variable number in the subordinate method addToN in the MyMethods class.

Exercise:

Convert the last version so that it returns the result. Show how the method would be called in the superordinate method. (Hint: you have to arrange to capture the returned result.)

And now the two files UseMyMethods.java containing method calls and MyMethods.java conataining the method definitions: (You might consider it to be a good idea to use two panes in Microsoft Word so as to see both the call and the definition at the same time)

file UseMyMethods.java:

// class to illustrate the calling,shown in brown, of six methods held in MyMethods.java

// Ian Downey 06September 2008

// Note that in the software below variables have been give prefixes that remind the reader

// of their types, so for example the int variable first has been renamed iFirst. You can if

// you wish work your way through all the software here and delete that notation.

// all method calls shown in brown for easy reading.

public class UseMyMethods

{

public static void main(String [] args)

{

int iFirst, iSecond, iThird;

// method calls below to Keyboard.readInt() each wrapped up in an

// assignment statement; the method returns an int each time it’s called:

iFirst = Keyboard.readInt(); // see method source code in Keyboard.java

iSecond = Keyboard.readInt();

// method call (3 lines below)to MyMethods.pow wrapped in a System.out.println:

System.out.print("The power of the first ");

System.out.print("to the second ");

System.out.prtint("is "+ MyMethods.pow(iFirst, iSecond)); // method 1 below

// shown below alternative way of writing the 3 lines above,

// which makes them into 4 lines

iAnswer = MyMethods.pow(iFirst, iSecond);

System.out.print("The power of the first ");

System.out.print("to the second ");

System.out.prtint("is "+ iAnswer)); // method 1 below

// the First layout is probably the best if all you want to do is get some output

// on the screen. The Second layout introduces a new variable iAnswer and it’s

// rather indirect. It’s useful in some circumstances.

// Shown below is the call of a version of the pow method with return type void.

// I’ve called this one power. The power method does the reporting to the user.

MyMethods.power(iFirst, iSecond);

// now a call to a method to find the larger of two numbers

iFirst = Keyboard.readInt();

iSecond = Keyboard.readInt();

iThird = MyMethods.larger(iFirst, iSecond);

//iThird will contain the larger of iFirst’s contents and iSecond’s contents, for example

// if iFirst had 2 in it and iSecond had 3 in it, then iThird would end up with 3 in it.

System.out.println(“The larger of “ + iFirst + “and “ + iSecond + is “ + iThird);

iThird = Keyboard.readInt();

// now a method call below wrapped in a if statement; return type boolean if(MyMethods.betweenFiveAndFifteen(iThird)) *** // see method 3 below

System.out.println("Your number is between five and fifteen.");

double iRadius = 2.3;

System.out.print("The circle of radius" + iRadius);

System.out.println("is " + MyMethods.circArea(iRadius)); // method 4 below

// method calls below appear starkly on their own since their return type is void:

MyMethods.asteriskSix(); // see method 5 below

MyMethods.asteriskVar(8); //method 6: argument 8 is plugged into parameter iA;

int iNumber OfAsterisks = 8;

MyMethods.asteriskVar(iNumberOfAsterisks); // alternative call of method 6

}

}

file MyMethods.java

// class with many methods of different sorts, to be invoked by the accompanying class

// Ian Downey 06September 2008

public class MyMethods

{

// METHOD 1. method with two int parameters and an int returned:

public static int pow(int iA, int iB)

{

int iPowerResult;

iPowerResult = 1;

while(iB > 0) // notice that down-counting to 0 is probably the best solution

{

p = p * iA;

--iB; // down-counting takes place here

}

return iPowerResult;

}

// A variant on the pow method, that I’ve called power, that prints its own result. It

// has return type void.

public static void power(int iA, int iB)

{

int iPowerResult;

iPowerResult = 1;

while(iB > 0) // notice that down-counting to 0 is probably the best solution

{

p = p * iA;

--iB; // down-counting takes place here

}

System.out.println(iPowerResult);

}

// METHOD 2. another method with two int parameters and an int returned:

public static int larger(int iA, int iB)

{

int iBigger;

if(iA > iB)

iBigger = iA;

else

iBigger = iB;

return iBigger;

}

// METHOD 3. method with one int parameter and a boolean returned:

public static boolean betweenFiveAndFifteen(int iA)

{

return(iA >= 5 & iA <= 15);

}

// Consider the notes below in connection with, not only the

// method definition, above, but the if statement in the main

// method that calls it:

// The theory behind the method above is that an if statement

// expects to see a true/false expression in the brackets

// following if. In other words it expects to see a boolean

// expression. Note that the return type of the above

// method isboolean(highlighted in red). Do you see that

// a boolean is indeed returned? iA>= 5 & iA <= 15

// is something that is either true or false. So either true

// or false is sent back to appear between the brackets of

// the if statement. See line with *** after it.

// Note also that the body of the method could be written out

// in a more long-winded, but unnecessary manner:

/*

boolean b;

b = iA >= 5 & iA <= 15;

return b;

*/

// Note also that one might write: b = (iA >= 5) &( iA <= 15); instead of

// b = iA >= 5 & iA <= 15;

// This may be thought to be clearer, a good thing. However it’s unnecessary

// from the compiler’s point of view since & is done after >= and <= , and last

// of all = is done. Thus the brackets aren’t necessary.

//METHOD 4. method with one double parameter and a double returned:

public static double circArea(double iR)

{

return 3.14159 * iR * iR;

}

//METHOD 5. method with no parameters and nothing returned:

public static void asteriskSix()

{

System.out.println("******");

}

// METHOD 6. method with an int parameter and nothing returned:

public static void asteriskVar(int iA)

{

while(iA > 0)

{

System.out.print("*");

--iA;

}

}

}

1.