0

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 4

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I can't agree that it is "not a good choice." The OP is already faced with a situation where "x is already being set up," and which would not be thread-safe (if more than one thread was trying to access it). This is the design that he has, and he makes no mention of threads in his post. Instance variables would solve the problem he described.
6

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 ); }
}

Comments

3

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
}

Comments

-1
public class Test
{

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

public static void method2
{

System.out.println(+x);

}

}

1 Comment

Rather than just posting a code snippet, can you explain (in words) why this answers the OPs question? This would improve your answer a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.