novicePrgrmr
novicePrgrmr

Reputation: 19395

How to change my toString() output

Right now the default toString() method displays the internal identifier for the object.

How do I make the toString() method display object variables instead?

thanks!

Upvotes: 0

Views: 3792

Answers (4)

msarchet
msarchet

Reputation: 15242

@Override
public String toString()
{
  String yourString = "";

  //Do things to get what you want

  return yourString;
}

Upvotes: 1

Tayyab
Tayyab

Reputation: 10641

Inherit the class and override its toString() method to display whatever you want.

Upvotes: 0

Rob Hruska
Rob Hruska

Reputation: 120376

You need to override toString() on the class you want the information about.

For example:

class Foo {
    private String myProperty = "bar";

    @Override
    public String toString() {
        return myProperty;
    }
}

In the above example, you would see the following:

new Foo().toString(); // outputs "bar"

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120268

you need to override the toString method on your class. In it you return a String that you will construct based on the class properties.

So if you class was

class Person {
    String firstName;
    String lastName;
}

you would add

public String toString() {
    return firstName + " " + lastName;
}

thats just a basic example. In real code I would use String.format() method, or possibly the apache StringBuilder tool, which will automatically generate a String for any object.

Upvotes: 1

Related Questions