How to return a value in Java

When we are writing a method, most of the time we want to return something from the calling method. This article will help you on how to return a value in java language using the return keyword.

Returning a value means storing the evaluated variable and return its data to the method where it was called. The data type that should be returned should be the same that was defined when creating the method or is a covariant type. For example:

package com.javapointers.javacore;

public class Return {

     public int addNum(int a, int b){
          int answer = a + b;
          return answer;
     }

     public static void main(String args[]){
          Return ret = new Return();
          int ans = ret.addNum(10, 20);
          System.out.println(ans);
     }
}

In our example above, we have created a class named Return. It first created an instance of our Return class. In the second line of the main method, we have called our method addNum(). Inside our addNum method was the adding of the variable a and b and save the answer to the variable answer and eventually return whatever the variable answer hold. This will result in 10 + 20 which is equal to 30 that will be held by our variable answer. When we return the answer, it will go again to the method where it was called, ret.addNum(10, 20), and save the returning value to the variable ans. Giving us an output of 30.

This is the last article for our Java Basic Tutorial. Next, we can now proceed to the new chapter which is creating a Java SE application that includes creating a graphical user interface (GUI) and first in our topic, is how to create a JFrame.

Share this tutorial!