I am trying to use a variable from a method I created in another class in the main section.
For example:
public class test {
public static int n;
public void getLower(){
int p = 12;
}
public static void main(String[] args) {
test example = new test();
example.getLower();
System.out.println(p);
}
}
However, I get the error message 'p cannot be resolved to a variable'.
Is what I'm trying to do possible?
Thanks in advance!
No, unless you declare
p
the same way you are declaringn
.In your example, the
n
variable exists only in thegetLower()
method, it's not accessible by other methods, so you have to declare it at class-level:or
Read more about variable scope
p
is a local variable within thegetLower
method. You're not "importing" the method - you're just calling it. When the method has returned, the variable no longer even exists.You could consider returning the value of
p
from the method:Then assign the return value to a local variable in
main
:You should read the Java tutorial on variables for more information about the different kinds of variables.
varaiable P is defined in the method getLower so it is local variable which cant be accessed in main method.You need to define the variable globally so that both the method can access it.So can make it static or simple variable
p is a method variable, that means, it is garbage collected as soon as the method returns, so you can't get it, you can just return it's value and assign it to a local variable in the caller function