0

I am executing below simple main method in Java.

public class Basics {

    public static void main(String[] args) {
        
        String p=new String();
        System.out.println(p);
        int[] a= new int[1];
        System.out.println(a);
    }
}

The output of the Array reference variable is classname@hashcodeinhexadecimal which seems to be ok but the String reference variable gives no output. Isn't that it should return the hashcode of the new String object created in the heap?

Dada
  • 6,313
  • 7
  • 24
  • 43
  • *the String reference variable gives no output* - `String p=new String();` - you do not give it any string value – Scary Wombat Jan 05 '22 at 03:02
  • 3
    @xerx593 that wouldn't change anything. Java is dynamic dispatch, this still gets you the toString impl of the String class. – rzwitserloot Jan 05 '22 at 03:06
  • 2
    Nope. If a method is overridden, only the class that overrides it can call the original method using `super.overridenMethod()`. – Johannes Kuhn Jan 05 '22 at 03:40
  • Also, [`System.identiyHashCode`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/System.html#identityHashCode%28java.lang.Object%29) might be of interest. – Johannes Kuhn Jan 05 '22 at 03:43
  • 1
    Does this answer your question? [String empty constructor in java](https://stackoverflow.com/questions/12430112/string-empty-constructor-in-java) – Joe Feb 13 '22 at 06:49

1 Answers1

0

String is a class and the output of Strings (even literals) are printed as one might expect via the toString override. Arrays are objects but are an inherent part of the language so their presentation is not overridden but internally inherited from the Object class. Section 10.8 of the JLS says.

Although an array type is not a class, the Class object of every array acts as if:

• The direct superclass of every array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.

If you want to see the actual hashCode that results from computations involving "abc" then do the following. Both will give the same result.

String s = new String("abc"); // normally overkill
System.out.println("abc".hashCode());
System.out.println(s.hashCode());

if you want to see the hashCode prior to being overridden (undefined but could be be the memory address of the object), then do the following:

System.out.println(System.identityHashCode("abc"));
System.out.println(System.identityHashCode(s));

For arrays you can also do this. These will be the same since arrays inherit their hashCode from Object without regard to content.

int[] a = {1};
System.out.println(a.hashCode());
System.out.println(System.identityHashCode(a));
a[0] = 12345;
System.out.println(a.hashCode());
System.out.println(System.identityHashCode(a));


WJS
  • 36,363
  • 4
  • 24
  • 39