OutFall
OutFall

Reputation: 482

Why does object with a string prints as null?

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

Answers (5)

Drogba
Drogba

Reputation: 4346

constructor has no return type all the times in java.

Upvotes: 0

Reimeus
Reimeus

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

Sujay
Sujay

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

Lior
Lior

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

Saleh Omar
Saleh Omar

Reputation: 759

Because you have defined a method and not a constructor.

Upvotes: 0

Related Questions