Java Tutorial: Defining a Function

, , …,

Here we show how to define your own function in Java.

In Java, everything is defined in a class, and class has methods. So, to define a unit that does your own computation, means defining a class, and a method inside the class. Here's a example.

Save the following code into a file and name it F1.java.

class F2 {
    public int addone (int n) {
        return n+1;
    }
}

public class F1 {
    public static void main(String[] arg) {
        F2 x1 = new F2();
        int m = x1.addone(4);
        System.out.println(m); // prints 5
    }
}

Note the line F2 x1 = new F2();. It tells java that “x1” is of type “F2”, and new F2() creates the object. Then, the addone function (called “method”) inside “F2” can be used like this: x1.addone(4).

It is all quite confusing but here's some outline of what's going on:

  1. Java code comes in unit of classes. (for example, not as blocks of function definitions and blocks of expressions)
  2. Each file can define more than one class. The file's name must be the same to one of the public class's name defined in the file. So, in our case, our file is F1.java and the corresponding class is “F1”.
  3. The main class of a file must have a method called “main”. This is the location the program starts to execute. In our example, class “F1” has the method “main”.
  4. The other classes in a file are meant to serve as supporting role. (normally called auxiliary functions/subroutines)
  5. So, what we did above is that, we have main class “F1”, with “F2” being a supporting class. And, we defined the “addone” method in “F2”. We call this method by first creating a instance of it, the “x1”. Then, call the methods of “x1” to do our computation.

All Java programs follow the above outline.

blog comments powered by Disqus