Introduction to Java: Methods

Introduction to Java: Methods


Methods in Java is a block of statements that must be in a class and can be executed by calling it from other places.

Example:


public class MyMethod {
    public static void main(String[] args) {
        hello();
    }

    public static void hello() {
        System.out.println("hello from hello() method");
    }
}


hello() is a method we defined in our MyMethod class and called it from main() method.
static means that this method belongs to the MyMethod class and not the object MyMethod. static methods can be called without creating an object of class.
void means this method doesn't return any value.

Output:


$ javac MyMethod.java
$ java MyMethod
hello from hello() method


Parameters
Parameters are values that are sent into a method. Parameters are variables inside the method. You can add as many parameters as you want, just separate them with a comma. The following example method take one int parameter called number and when the method is called, we pass an integer number which is used inside the method to print the number.

Example:


public class MyArgMethod {
    public static void main(String[] args) {
        int number = 10;

        displayNumbers(number);
    }

    public static void displayNumbers(int number) {
        System.out.println("The number is: " + number);
    }
}


Output:


$ javac MyParameterMethod.java
$ java MyParameterMethod
The number is: 10


Return values
The void keyword indicates that the method doesn't return anything. If you want the method to return a value, you use the return keyword with primitive data types instead of void.

Example:


public class MyReturnValueMethod {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 10;

        System.out.println(sum(num1, num2));
    }

    public static int sum(int num1, int num2) {
        return num1 + num2;
    }
}


This method return the sum of the methods two parameters.

Output:


$ javac MyReturnValueMethod.java
$ java MyReturnValueMethod
15


Share this: