-2

Please why "a" is printed instead of the address of String object?

Example code:

class Source{

    public static void main(String[] args) {
        Source S1= new Source();
        String a1= new String("a");

        System.out.println(S1);
        System.out.println(a1);
    }
}

Result:

Source@4dd8dc3

a

Shivam Bhatia
  • 62
  • 1
  • 5
  • When printing an object via `System.out.println()` the `toString()` method of said object is implicitly invoked. When the `toString()` method of the object is not overridden, the default [`Object#toString()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--) is invoked, which returns the string representation of the object. However, [`String#toString()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toString--) is specified as _"This object (which is already a string!) is itself returned."_ Hence the actual `String` content is returned and printed. – maloomeister Jun 11 '21 at 07:25
  • add toString(); – Kostandin Vllahu Jun 11 '21 at 07:31
  • 1
    Contrary to a commonly held beginners belief, the hex number you see at the end of that output is **not** an address. It's the identity hash code and how exactly it's computed is implementation-defined. In current OpenJDK it's a random number that each object gets assigned when it's created. – Joachim Sauer Jun 11 '21 at 07:52

1 Answers1

1

That is the standard for classes. If you expected something else, change it and overwrite toString()

For example like this:

class Source {

    public static void main(String[] args) {
        Source S1 = new Source();
        //String a1 = new String("a");
        String a1 = "a";

        System.out.println(S1);
        System.out.println(a1);
    }

    @Override
    public String toString() {
        return "This is an Instance of the Class Source";
    }
}