March 23, 2012
Basic Java concept
Question by vishesh
Hi I have following code block
public class Driver {
static String x = "x";
static String y = "y";
public static void main(String[] args) throws Exception {
setX(x);
System.out.println("but x is still "+x);
}
static void setX(String x){
x="a";
System.out.println("now x should be = "+x);
}
}
and this prints
now x should be = a
but x is still x
I was hoping to get
now x should be = a
but x is still a
I know there are ways to get what I want,but please answer why this does not work.
Answer by Jigar Joshi
static void setX(String x){
//x="a"; //refers to local variable , from parameter
//make it as follows
Driver.x="a";
System.out.println("now x should be = "+x);
}
Answer by Starx
You have to use Driver.x
to set the value. You cannot update the static variable with just defining x="a"
static void setX(String x){
Driver.x="a";
System.out.println("now x should be = "+Driver.x);
}