-2

public String toString() { // this is in anther class

    String Cubes = "+";

    for(int i = 0; i < CubesStack.length;) {
        Cubes = Cubes + CubesStack[i].toString();
    }

    return "maxCubes = " + this.maxCubes + "\n" +

            "currentCubes = " + this.currentCubes + "\n" + 

            "CubesStack = " + Cubes; 

}

public class MainMain { // this is main

public static void main(String[] args) {
    // TODO Auto-generated method stub
    cubesTower tower1 = new cubesTower(20);
    System.out.println(tower1.toString());
}

}

why i cant print using 'tostring' ? how can i print arry that includes classes in it ? thank you very much .

1 Answers1

1

Your object should implement toString() method other wise it will take default implementation of toString() from java.lang.Object.

java.lang.Object default implementation is

public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So you have to override the toString() to get your own values

For Example: Here I have Name class which will have two properties

class Name {
    private String firstName;
    private String lastName;
    public Name(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
    @Override
    public String toString() {
        return "Name [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

}
public static void main(String[] args) {
    Name[] names = new Name[]{new Name("john","doe"),new Name("john1","doe1")};
    System.out.println(names[0]);
}

If I don't override toString() then output: com.stackovflow.problems.Name@33909752

After implementing toString() output: Name [firstName=john, lastName=doe]

gprasadr8
  • 789
  • 1
  • 8
  • 12