-1

Sorry, I just started coding and I'm trying to put an instance of a object into a stack and peek it but when I peek it, I think it's showing me the memory address of the stack item instead of the actual value. The dog class I'm using only one has one variable and it's name.

import java.util.Stack;
public class Driver {
    public static void main(String[] args) {
        Stack myStack = new Stack();
        Dog dog1 = new Dog("jake");
        myStack.push(dog1);
        System.out.println(myStack.peek());
    }
}

This is the output it gives me:

Dog@5eb5c224

I tried messing with the peek function and trying to place it into another variable of object Dog but I couldn't get anything to work.

Enowneb
  • 943
  • 1
  • 2
  • 11
  • If you write `Dog dog2 = myStack.peek();` after you've pushed the `Dog` onto the stack, then `dog1` and `dog2` will both refer to the same `Dog`. Is that what you're trying to achieve? Or are you actually asking how to print a `Dog`? – Dawood ibn Kareem Feb 06 '23 at 05:47

1 Answers1

2

if you print an object in java it will call the toString method on that object to stringify it. The default implementation of toString is inherited from the Object class and will print out the class name and its reference as you see it. In order to obtain some meaningful output, you need to override the toString method on the Dog class. See for example How to use the toString method in Java?

Pavel
  • 785
  • 5
  • 14