Home > other >  Why the String reference variable does not return the reference hashcode when printed
Why the String reference variable does not return the reference hashcode when printed

Time:01-05

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?

Thanks in advance

CodePudding user response:

Because String overrides Object#toString(). If you want to print out the String object's hash code, simply call String#hashCode().

CodePudding user response:

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 then do the following

System.out.println("abc".hashCode());

You can also try the following

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

CodePudding user response:

The String constructor when called without parameters returns a String object that it represents an empty character sequence. So System.out.println it prints an empty character sequence, which displays as nothing in standard out.

  •  Tags:  
  • Related