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?
public void Constructor()
is not a constructor.. it's a void method. If you remove the void
, it should work as intended
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With