5 Minutes of Java (4. Java Methods)

In Python, you define function to create a block of re-usable code. In Java, this is done using method. You must create your method within the Java class.   There can be more than one method in each Java class.

The code below shows you the syntax of a Java method:

modifier returnValueDataType methodName(list of parameters) {
  // Method body;
}

The code below shows you how to create a method addNumber with the following attributes in a class MyNumber:

public class MyNumber{
    public double addNumber(double x, double y){
        return x + y;
    }
}
  1. public — Method modifier. It tells the compiler how to call the method. Always use public for now, you will learn more about this later on.
  2. double — The data type of the value returned by the method. In this example, x + y which is of double data type, will be returned.
  3. addNumber — Name of the method.
  4. double x, double y — The parameters that are passed to the method. In this example, there are 2 parameters: x and y. Both x and y have double data type.
  5. return x + y — The method body. The result of (x + y) is the value to be returned by the method. The data type must match those stated at point 2.

Take a look at another method given below:

public class MyName{
    public void sayHello(String name){
        System.out.println("Hello " + name);
    }
}
  1. void — This means that the method will not return any value. Take note that there is no “return …” in the method body.
  2. System.out.println(…) — The method body. It calls a method to print out the value in its parameter for the user to see.

 

Leave a Reply