Reputation: 482
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);
}
}
Upvotes: 1
Views: 97
Reputation: 159754
You have the void
keyword here, making your 'constructor' a method (which is never called), so the String
s
is never initialised. Object references at class level will be null
by default.
public void Bug1() {
to fix, change to:
public Bug1() {
Constructors don't have return types.
Upvotes: 3
Reputation: 6783
Read about constructors in Java.
Here's what you should've done:
public class Bug1 {
private String s;
public Bug1() { //Parameterless constructor
s = "hello";
}
public String toString() {
return s;
}
public static void main(String[] args) {
Bug1 x = new Bug1();
System.out.println(x);
}
}
Upvotes: 0
Reputation: 6051
public class Bug1 {
private String s;
public Bug1() {
s = "hello";
}
public String toString() {
return s;
}
public static void main(String[] args) {
Bug1 x = new Bug1();
System.out.println(x);
}
}
You defined Bug1 as a method instead of a constructor.
Upvotes: 1