Probably a noob question but why this code prints null?
public class Bug1 {
private String s;
public void Bug1() {
s = "hello";
}
public String toString() {
return s;
}
public static void main(String[] args) {
Bug1 x = new Bug1();
System.out.println(x);
}
}
You have the
voidkeyword here, making your ‘constructor’ a method (which is never called), so theStringsis never initialised. Object references at class level will benullby default.to fix, change to:
Constructors don’t have return types.