Java Program to Return a Value from a Method

This is a Java Program to Return a Value from a Method.

We make a method named input which is used to get input from the user. We also make a method named add which is used to perform addition and return the result back to input method where we finally print the result.

Here is the source code of the Java Program to Return a Value from a Method. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Return_Value
  3. {
  4.     void input()
  5.     {
  6.         int x, y, z;
  7.         Scanner s = new Scanner(;
  8.         System.out.print("Enter first integer:");
  9.         x = s.nextInt();
  10.         System.out.print("Enter second integer:");
  11.         y = s.nextInt();
  12.         z = add(x, y);
  13.         System.out.println("Result:"+z);
  14.     }
  15.     int add(int a, int b)
  16.     {
  17.         int c;
  18.         c = a + b;
  19.         return c;
  20.     }
  21.     public static void main(String[] args) 
  22.     {
  23.         Return_Value obj = new Return_Value();
  24.         obj.input();
  25.     }
  26. }


$ javac
$ java Return_Value
Enter first integer:5
Enter second integer:6

Sanfoundry Global Education & Learning Series – 1000 Java Programs.


Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.