Java println (charArray + String) vs println (charArray)

I have

char c1 = 'S'; // S as a character char c2 = '\u0068'; // h in Unicode char c3 = 0x0065; // e in hexadecimal char c4 = 0154; // l in octal char c5 = (char) 131170; // b, casted (131170-131072=121) char c6 = (char) 131193; // y, casted (131193-131072=121) char c7 = '\''; // ' apostrophe special character char c8 = 's'; // s as a character char[] autoDesignerArray = {c1, c2, c3, c4, c5, c6, c7, c8}; 

and

 System.out.println(autoDesignerArray + "Mustang"); 

Exit: [C @ c17164Mustang

 System.out.println(autoDesignerArray); 

Exit: Shelby

I don't understand why I get weird output when I concatenate a char array with a string. What is the "[C @ c17164"? A place in memory? And why do I get this when I am concatenating with a string, but I get what I expect when I print it alone?

+5
source share
4 answers

The expression System.out.println(X + Y) is equal to the expression System.out.println(X.toString() + Y.toString()) .

When you call System.out.println(autoDesignerArray + "Mustang") autoDesignerArray.toString() (which is "[ C@c17164 " ), combines with "Mustang" and the result is printed.

+7
source

Since everyone has an array with a class, the line that you get is an object representation of its object, i.e. [ C@c17164Mustang where

  • [C is the name of the class ( [ represents a 1d array)
  • @ ends the line
  • c17164 some hash code
  • Mustang string

to check the class name of the array do System.out.println(yourArray.getClass().getName());

For ex, if you do System.out.println(new Object()); , you will get something like java.lang.Object@25154f string representation of the created object.

And to print the actual values โ€‹โ€‹of the array do System.out.println((java.util.Arrays.toString(autoDesignerArray))); which gives

[S, h, e, l, b, y, ', s]

Demo

+2
source

Arrays in java do not overwrite the toString() method , which means:

  • System.out.println(autoDesignerArray + "Mustang");
    • will print by default toString() array and combine it with a string
    • the standard implementation of toString() will print a binary name followed by hashCode() (a char array will print [C followed by its hash code)
  • System.out.println(autoDesignerArray);
    • actually call Arrays.toString () or similar functionality that correctly manages toString() arrays.
0
source

This is due to arrays and why the fact that they do not implicitly inherit Object - For more information, you can check this SO question (there is an answer there).

println(char[] s) bit confusing to me in Oracle Doc - in C you usually repeat every element in the array and print every element follows \n to break the line.

However, the bottom line is that autoDesignerArray.toString() will not work the way you would like (which is why it returns [ C@c17164 ).

0
source

All Articles