Search code examples
javaoutputbluej

What is the output?


What is displayed by Line 1 Below? BlueJ prints out A@18fea98, but I don't think this is correct. Please help, thank you.

class A{
  private int x;
  public A(){
    x=0;
  }
}

//test code in client program
A test = new A();
out.println(test);//LINE 1

Solution

  • By default, out.println(obj) will invoke the toString method on object test, which by default will return the HashBased memory location of the object on which toString is invoked.

    In your scenario: A@18fea98

    Which is expected output. If you need to print the value of the x attribute, you have following two options

    1. Call the getter to get the value of the attribute
    2. Override the toString method on A class to return the representation you want

    For example:

        class A{
           private int x;
           public A() { 
             x = 0;
           }
    
           public String toString() {
              return "A:"+x;
           }
       }