-2

I want to print the address of the char array. When I try to do it I am getting a string output as "ABC" instead of getting address of the char array.

class P
{
    public static void main(String [] args)
    {
        char [] ch = {'A','B','C'};
        System.out.println(ch);
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Akshay
  • 19
  • 4
  • 3
    Because there is an override specifically to do that for a char array: [`println(char[])`](https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#println(char[])) – khelwood Aug 14 '20 at 09:05
  • will you please explain it in depth as i am a beginner and want to know in detail. – Akshay Aug 14 '20 at 09:09
  • the explaination is right on the link from khelwood's comment – jhamon Aug 14 '20 at 09:12
  • I suggest learning what [overloading](https://stackoverflow.com/questions/13123180/what-is-overloading-in-java) is and have a look at the javadoc of the method you just invoked: [println\(char\[\]\)](https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(char[])) – Lino Aug 14 '20 at 09:18
  • 2
    The output of the `toString` method never gives the "address" of the object. What you are probably referring to as the address is the hashCode. – TiiJ7 Aug 14 '20 at 09:19
  • 2
    I suspect you are one of the few people ever who actually *wants* the nonsensical output of calling `toString()` on an array :) – Andy Turner Aug 14 '20 at 09:20

2 Answers2

2

For most objects, if you pass them to println, you get the normal toString() representation of the object. For arrays, it looks something like [C@6d4b1c02.

However, there is a version of println written specifically to accept a char array. So if you call that, you don't get the toString() representation of the array; you get the contents of the array, in this case ABC.

If you were to call the ordinary (non-char[]) version of println

System.out.println((Object) ch);

you would get the impenetrable [C@6d4b1c02 output.

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

You can look into println(char[] ch) implementation for char[] it finally calls below method

 public void write(char cbuf[]) throws IOException {
        write(cbuf, 0, cbuf.length);
    }

This method write array element from 0 to array length that why you are getting ABC.

If you want hash code kind of value you can change your method

 System.out.println(ch.toString());
talex
  • 17,973
  • 3
  • 29
  • 66
vivekdubey
  • 484
  • 2
  • 7