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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!