Java How to use a variable from a method when imported into the main class

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!

Jon Skeet
people
quotationmark

p is a local variable within the getLower 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:

public int getLower() {
    int p = 12;
    // Do whatever you want here
    return p;
}

Then assign the return value to a local variable in main:

int result = example.getLower();
System.out.println(result);

You should read the Java tutorial on variables for more information about the different kinds of variables.

people

See more on this question at Stackoverflow