Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we initialise static variable inside constructor?

Tags:

java

I have the following code snippet:

class Constructor {

  static String str;

  public void Constructor() {
      System.out.println("In constructor");
      str = "Hello World";
  }

  public static void main(String[] args) {
      Constructor c=new Constructor();
      System.out.println(str);
  }
}

Its output is null even though the string is initialized inside the constructor.

Why is that so?

like image 836
abhi1489 Avatar asked Mar 09 '16 06:03

abhi1489


2 Answers

public void Constructor() is not a constructor.. it's a void method. If you remove the void, it should work as intended

like image 70
Maljam Avatar answered Sep 30 '22 19:09

Maljam


As I mentioned in the comments public void Constructor(){ is not a constructor because constructors do not have return type.As your Constructor is of void so its not an constructor

Remove the void keyword

class Constructor {

static String str;

public Constructor(){
    System.out.println("In constructor");
    str="Hello World";
}

public static void main(String[] args) {
    Constructor c=new Constructor();

    System.out.println(str);

}


}

output:Hello World

like image 31
SpringLearner Avatar answered Sep 30 '22 20:09

SpringLearner