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?

5
  • the String reference variable gives no output - String p=new String(); - you do not give it any string value Commented Jan 5, 2022 at 3:02
  • 3
    @xerx593 that wouldn't change anything. Java is dynamic dispatch, this still gets you the toString impl of the String class. Commented Jan 5, 2022 at 3:06
  • 2
    Nope. If a method is overridden, only the class that overrides it can call the original method using super.overridenMethod(). Commented Jan 5, 2022 at 3:40
  • Also, System.identiyHashCode might be of interest. Commented Jan 5, 2022 at 3:43
  • 1
    Does this answer your question? String empty constructor in java Commented Feb 13, 2022 at 6:49

1 Answer 1

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));


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.