Dfgf Hgh Dfgf Hgh - 2 years ago 76
Java Question

How does return value work in java methods

I made this code to learn my self about how return works in java

public class test {

public int sumDouble(int a, int b) {

int k = (a + b);
if (a == b) {
k = k * 2;

} else {
k = (a + b);

return k;


public static void main(String[] args) {

System.out.println("Enter your number");
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();

test t = new test();
t.sumDouble(a, b);


I want to use the
return k
to print out the value of summation
How can use the
return k
to print out the sum value?
I tried to write
in the main method but it did not work ..


Answer Source

The thing to keep in mind here is that k is a local variable in the sumDouble method, so you can't refer to it elsewhere.

You can take the value returned by sumDouble and use it in your main method, however.

For instance, you can create a variable in main and assign its value to be the value that is returned from sumDouble, and you could print that variable, since it's in scope:

// at runtime, this will evaluate "t.sumDouble(a, b)" 
// and assign the value that it returns to the variable "sum"
int sum = t.sumDouble(a, b);

You could even skip the local variable and use the method call directly:

System.out.println(t.sumDouble(a, b));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download