10. Methods in Java

Let's hope that you by now have some idea what a method in Java is: it's a piece of a program which performs a certain task. Whenever you want your program to do this task, you can call the method.

Java has a great number of built-in methods. Each of these methods belongs to a certain class.

If, for instance, you want to copy a text from a textfield, you can make use of the method
getText(), which must be linked to an object of the TextField class.

And for making random numbers we have the method
random(), which belongs to the Math class.

You may also remember that we can get a single character out of a string with the method
charAt(), which is part of the String class.

But even though Java has hundreds of methods that can perform all sorts of handy tasks, there may come a moment when you want to use a method that Java does not have. In a case like that you may decide to make your own method.


A 'void' method
Before we continue, first a short remark: if you really want to draw triangles, the methods
drawPolygon and fillPolygon are more efficient. They will be discussed in chapter 13. The method triangle presented here is used to illustrate a 'void' method.

Suppose you'd want to to make a method that draws a triangle. We could simply call this method
triangle. The method would need the co-ordinates of the angular points, which we could call (x1,y1), (x2,y2) and (x3,y3). Of course, the method must be able to draw, so it will need an object of the Graphics class.

In order to draw the triangle, the method must be called like this:

triangle (g, x1,y1, x2,y2, x3,y3);
You see: we pass g (an object of Graphics) and three pairs of co-ordinates to the method. But first, Java has to know what it must do when the triangle method is called. Before the compiler can do anything with this method, Java must be informed about the kind of value this method should deliver and the kind of values that must be passed to it. This is done in the so-called header line in the following way:
void triangle (Graphics g, int x1, int y1,int x2, int y2, int x3, int y3) {
That the co-ordinates x1, y1, x2, y2, x3, y3 are of the int type, is rather obvious, isn't it?. And that g is of the Graphics types, is not too hard to understand either.

But what is meant by the term
void? A method can deliver a value. For instance, a method that adds two numbers could be defined as follows:
int add (int number1, number2) {
      // rest of method
You see: the method delivers an integer value, so it must be of the int type. But not all methods deliver a value. Some methods, for instance, only do graphical work. A method that doesn't deliver a value is of the type void (English void: empty, without value).

The rest of our
triangle method is not so hard to understand:
void triangle (Graphics g, int x1, int y1,
                                int x2, int y2, int x3, int y3) {
     g.drawLine (x1, y1, x2, y2);
     g.drawLine (x2, y2, x3, y3);
     g.drawLine (x3, y3, x1, y1);
}
All it does is draw three lines connecting the points determined by the co-ordinates (x1, x2, y1, y2, x3, y3). Using this method we can draw a nice little picture in the following way:
// A green triangle made with the
//   help of the method 'triangle'.
import java.applet.*;
import java.awt.*;
public class FillTriangle extends Applet {
public void paint (Graphics g) {
     g.setColor (Color.green);
     int  x1,  y1,  x2,  y2,  x3,  y3;
     // We start with point (160,120)
     x1 = x2 = x3 = 160;
     y1 = y2 = y3 = 120;
     for (int i=0; i<100; i++)  {
          triangle  (g, x1, y1, x2, y2, x3, y3);
          y1--;  x2--;  y2++;  x3++;  y3++;
     }
     g.setColor (Color.black);
     triangle (g,x1,y1,x2,y2,x3,y3);
}

void triangle (Graphics g, int x1, int y1,
                            int x2, int y2, int x3, int y3)  {
     g.drawLine (x1, y1, x2, y2);
     g.drawLine (x2, y2, x3, y3);
     g.drawLine (x3, y3, x1, y1);
}
}
How does this applet work?

From the method
paint the method triangle is called a hundred times. We start with a small 'triangle', whose three co-ordinates are the same (160, 120), so really one point. Then we put the co-ordinates further and further apart, so what we really draw are larger and larger green triangles. The last triangle is drawn in black, and our result will look like this:

 


At the start of this chapter it was observed that every method belongs to a certain class. But what class does the method
triangle belong to? The answer is quite simple: as you will know, every applet is a class. The method triangle is defined in this applet and consequently belongs to the class FillTriangle .


An 'int' method
If your applet would ask somebody's name, height or year of birth, it would be handy if there was a method that could get a positive integer number from a textfield. 

Such a method should do a number of things, such as:

  • copy a string from the textfield
  • convert the string to a number
  • check if it's a positive integer
  • return the value to the program
The method which can do this doesn't have to be very complicated. A simple way to do it could look like this:
// method to get a positive integer number from textfield 'box'
int getIntFromTextField (TextField box)  {
     int n = -1;
     String tmp = box.getText();
     try  {
          n = Integer.parseInt (tmp);
     } catch (NumberFormatException exc) { }
     return n;
}
Error handling
The method
Integer.parseInt() is a method (belonging to the class Integer) which converts strings into numbers of the type int.

You may, however, wonder about the meaning of the words
try .. catch. This is the way in which Java prevents our program from crashing when something goes wrong, or in this case: if anything else has been typed than a whole number. 

We have agreed that the method should deliver a positive whole number. We make use of this fact by making the number negative (-1) in advance. If anything goes wrong, no new value is assigned to
n and its negative value will tell us that no correct number has been typed.

In our example we did not write anything between the curly brackets. But we could put something there to be performed in the event of an error, for instance something like this:
catch (NumberFormatException exc) { error = true; }
But here this is not really necessary: negative values will already signal  if anything goes wrong.


Exercise10.1
Write an applet with two textfields, into which positive whole numbers can be typed. After clicking a button, the sum, the (absolute) difference and the product of the two numbers will be displayed. Get the numbers out of the texfields using the method shown above. The applet should not accept anything but positive integers.

                

To chapter 11

Menu Java Tutorial

To home page

(c) 2003, Thomas J.H. Luif