How to Call a Variable in Another Method?

How to Call a Variable in Another Method?

How to call a variable in another method in the same class?

public void example(){    
    String x='name';
}

public void take(){
    /*how to call x variable*/
}

4 Answers

First declare your method to accept a parameter:

public void take(String s){
    // 
}

Then pass it:

public void example(){
    String x = "name";
    take(x);
}

Using an instance variable is not a good choice, because it would require calling some code to set up the value before take() is called, and take() have no control over that, which could lead to bugs. Also it wouldn't be threadsafe.

1

You make it an instance variable of the class:

public class MyClass
{
    String x;

    public void example(){ x = "name"; } // note the double quotes
    public void take(){ System.out.println( x ); }
}

Since they are in different scopes you can't.

One way to get around this is to make x a member variable like so:

String x;

public void example(){
    this.x = "name";
}

public void take(){
    // Do stuff to this.x
}
public class Test
{

static String x;
public static void method1
{
x="name";
}

public static void method2
{

System.out.println(+x);

}

}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.