I’m having an issue with scope and I don’t know how to solve it. Here’s a simple program to illustrate my problem:
public class testing {
public static void main(String args[]) {
test(1,2);
System.out.println(answer);
}
public static int test(int x, int y) {
int answer = x + y;
return answer;
}
}
So I pass a couple parameters to the test method and I return answer, so shouldn’t I be able to access the result of answer in my main method? But I can’t, I get an error. What am I doing wrong? Java is telling me that I can’t access answer, that the scope doesn’t extend to the main method even though I put the return statement in the test method. How else can I return answer then (without passing it as a parameter)?
You didn’t store the
return valuein any variable. Also, the variableansweris defined locally intestmethod, and will not be visible inmainmethod. Hence, you would have got the compiler error in your code.You need to have this code in your main method: –
Now, what happens here is, it stores the
return valueoftest(1, 2)in a local variableresult, which has nothing to do with theanswervariable defined intestmethod. And then you simply print theresultback.Furthermore, you can change your
testmethod to: –and your main method can be modified to: –
Note that, this eliminates the need to declare the local variables (either in
mainortestmethod).