Confusion in the printing method in Java

Whenever I try to print char arrays on the console, I get the result in integer format, but whenever I try to print whole arrays on the console, I get the result in hashcode format. Can someone tell me why?

char[] arr={'4','5','6'}; System.out.println(arr); //456 int[] arr={4,5,6}; System.out.println(arr) //[ I@3e25a5 ] 
+4
source share
4 answers

java.io.PrintStream ( System.out class) has a special print method for char[] , but not for int[] . Thus, char[] uses this special method, and int[] is printed through the generic version, which prints the hash code (or, more precisely, the result of String.valueOf() , called with the object parameter as a parameter).

+11
source

Just because there is no method for which the int[] descriptors are special. It will be printed by String#valueOf() instead, which implicitly calls Object#toString() . If Object#toString() not redefined in the specified object type, then the following will be printed (according to the specified API).

 getClass().getName() + '@' + Integer.toHexString(hashCode()) 

The class int[] has the name [I

To achieve what you want, you need Arrays#toString() :

 int[] arr = {4, 5, 6}; System.out.println(Arrays.toString(arr)); // [4, 5, 6] 
+3
source

In the first case, an array of characters is used only as a string (in fact, it is also just an array of characters).

In the second, it does not have an overload for the type of an integer array and simply prints a reference to the object.

+1
source

I think the first one is considered as CharSequence ... as a string.

0
source

Source: https://habr.com/ru/post/1301461/


All Articles