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

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

class T1 {
     public static void main(String[] arg) {
         T2 x1 = new T2();
         int m =x1.addone(4);

Note the line T2 x1 = new T2();. It tells java that “x1” is of type “T2”, and new T2() creates the object. Then, the addone function (called “method”) inside “T2” 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 many classes. The file's name must be the same to one of the class's name defined in the file. So, in our case, our file is and the corresponding class is “T1”.
  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 “T1” 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 “T1”, with “T2” being a supporting class. And, we defined the “addone” method in “T2”. 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