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
}

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);
}

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).


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%).

You must be logged in to post a comment.