Returning Values From Methods (Java)

Examples of method returns

As my Java adventure continues I look today at returning values from methods. So far the methods I have discussed have completed a task but have not returned any values to the main method.

The previous methods have been defined as:

public static void methodName(){

method

}

Methods in Java
Methods in Java

I’ve put the word void in bold because this is the key to getting methods to return a value. The word void means “empty” and because it has been used Java is not expecting anything to return from the method.

To change the method from a void to a return the word void should be replaced with int, double, or char – readers of my variables post will notice that these are types of variables Java uses.

public static int returnNumber(){

return(4);

}

Java Return Method
Java Return Method

The above example will return the integer 4 to the main method. The below methods so various examples of the returns including how values can be passed into a method and a new value returned (see addNumbers on the below image).

Examples of method returns
Examples of method returns
method returns in action
method returns in action
public class methodReturn {
    public static void main(String[] args){
        System.out.println(returnNumber());
        System.out.println(returnLetter());
        System.out.println(returnDouble());
        System.out.println(addNumbers(3,3));
    }
    public static int returnNumber(){
        return(4);
    }
    public static char returnLetter(){
        return('g');
    }
    public static double returnDouble(){
        return(10.5);
    }
    public static int addNumbers(int num1, int num2){
        int sum = num1 + num2;
        return(sum);
    }

}

When Java hits the return keyword it exits out of the method and returns back to main void.

Whilst discussing Java, today I completed the “DEV276x: Learn to Program in Java” course offered by edX and Microsoft. I enjoyed the course as it had material to read, videos to watch, practical projects and 3 exams (pass mark is 70%).

edX DEV276x: Learn to Program in Java - complete
edX DEV276x: Learn to Program in Java – complete