How to call a variable in another method
in the same class
?
public void example(){
String x=\'name\';
}
public void take()
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.
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);
}
}