0

Why does printing a char[] in the following program not print any output, whereas the same program prints output for when the char[] is replaced with other array types int[] or float[] or String[] etc

public class Test5 {
    public static void main(String[] args) {
        char arr[] = new char[5];
        System.out.println(arr);
        System.out.println(arr[0]);
    }
}

whereas the following prints output with int[]

public class Test5 {
    public static void main(String[] args) {
        int arr[] = new int[5];
        System.out.println(arr);
        System.out.println(arr[0]);
    }
}

OutPut : [I@4cc77c2e

0

matt
  • 10,892
  • 3
  • 22
  • 34
MrNolan
  • 154
  • 1
  • 4
  • 13
  • @Jens My question is not related to the question that was linked and closed. Kindly have a look. – MrNolan Jul 20 '20 at 15:12

1 Answers1

1

Your first program does produce output. The output just happens to take the form of an invisible control character.

When you create an array of char, it is filled with "NUL" characters (don't confuse with the Java null reference value) which have the Unicode code point 0. This character is an invisible control character and the terminal does not display it. If you printed to a different output device, like to a file and then opened the file, you would see it.

The second program produces different output because the println method has a special overload for char arrays but not for other arrays. This means the second program prints a string representation of the int array, which takes the form [I@ followed by number in hex.

If you want the first program to give similar output, you need to use a different version of the println method. Any of these would work:

System.out.println((Object) arr);
System.out.println(arr.toString())
Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thanks for a detailed explanation, so this behaviour is only specific to char[] or any other array type also has similar behaviour? – MrNolan Jul 20 '20 at 15:08
  • Correct, `println(char[])` is the only version that takes an array of anything – Joni Jul 20 '20 at 15:11