Search code examples
javaarraysprimitive

printing array reference variable on console


what does the output means... if we print 'intarray' we get some hash code... & same is with 'floatarray' but if we print 'chararray' we doesn't get anything what does the folowing data means?????

class Test
{
    public static void main(String []aeg)
    {
        int []intarray = new int[5];
        char []chararray = new char[5];
        float []floatarray = new float[5];
        System.out.println(intarray);
        System.out.println(chararray);
        System.out.println(floatarray);
    }
 }

Output starts here

after printing on the console we get following output....

      F:\Mehnat\my sc\By me\ArrayList\2\2>javac Test.java
      F:\Mehnat\my sc\By me\ArrayList\2\2>java Test
      [I@546da8eb

      [F@6b6d079a

Output ends here


Solution

  • You're seeing this behavior because PrintStream.println has an overload that takes a char[]. From that method's documentation:

    Prints an array of characters and then terminate the line.

    Of course, the elements of your array haven't been initialized, so they are all the default char, which is '\u0000', the null character. If you populate the array with visible characters, you'll be able to see a result:

    char[] charArray = new char[] {'a', 'b', 'c', 'd', 'e'};
    System.out.println(charArray); //prints "abcde"
    

    The other method calls are using println(Object), which prints the result of the object's toString. Arrays don't override toString, and so you see the result of the default Object.toString implementation:

    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

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

    As a workaround, the Arrays utility class provides toString helper methods to get String representations of arrays. For example:

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    char[] charArray = new char[] {'a', 'b', 'c', 'e', 'f'};
    float[] floatArray = new float[] {1.0F, 1.1F, 1.2F, 1.3F, 1.4F};
    System.out.println(Arrays.toString(intArray));   // [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(charArray));  // [a, b, c, e, f]
    System.out.println(Arrays.toString(floatArray)); // [1.0, 1.1, 1.2, 1.3, 1.4]