COOLBEANS
COOLBEANS

Reputation: 757

Why does my object not need to call the .toString method?

In my test class at the bottom of my code you can see a bunch of system.out.print's. My question is: why doesn't the stack object need to be written as stack.toString() (It's written system.out.print(stack) instead). Does the print statement dynamically call the toString() method because it is the only string method available in the class....or is it something else gong on?

public class Char_Stack {
private char [] array = new char[10];
private int top = 0;

public int size() {
    return top;
}

public boolean isEmpty() {
    return top == 0;
}

public void push(char value) throws StackFullException {
    if (top == array.length)    
    throw new StackFullException("StackFullException");
    array[top++] = value;   
}

public double top() throws StackEmptyException {
    if (top == 0)
    throw new StackEmptyException("StackEmptyException");   
    return array[top-1];        
}

public double pop() throws StackEmptyException {
    if (top == 0)
    throw new StackEmptyException("StackEmptyException");
    return array[--top];

}

public String toString() {
    String out = "[" + top + " / " + array.length + "]";
    for (int i=0;i<array.length; i++) {
        out += " " + array[i];
    }
    return out;
}

public static void main(String[] args) throws StackFullException,StackEmptyException {
    Char_Stack stack = new Char_Stack();

    stack.push('Y');
    System.out.println(stack);

    stack.push('P');
    System.out.println(stack);

    stack.push('P');
    System.out.println(stack);

    stack.push('A');
    System.out.println(stack);

    stack.push('H');
    System.out.println(stack);

    stack.pop();
    System.out.println(stack);

    stack.pop();
    System.out.println(stack);

    stack.pop();
    System.out.println(stack);

    stack.pop();
    System.out.println(stack);

    stack.pop();
    System.out.println(stack);
}

}

Upvotes: 0

Views: 1468

Answers (3)

COOLBEANS
COOLBEANS

Reputation: 757

Found this too: It helped me understand a bit better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

System.out.println() does that for you.

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

String.valueOf()

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Upvotes: 1

Martin Dinov
Martin Dinov

Reputation: 8815

Roughly speaking, yes, it does. It will "try its best" to print it. What happens is that System.out.println(object) calls String.valueOf(object) which in turns calls object.toString().

Upvotes: 2

Related Questions