1

I am a beginner to Java. I read this recently

The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types) reference https://www.geeksforgeeks.org/arrays-in-java/

int n=scan.nextInt();
int a[]=new int[n];
int a1[]=new int[5];
System.out.println(a);
System.out.println(a1);

Both arrays are giving me a garbled value something like [I@4b67cf4d

Why is this happening?

  • Does this answer your question? [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Arvind Kumar Avinash Apr 07 '20 at 21:54
  • Print the elements by iterating the array e.g. `for(int x:a)System.out.println(x);` or use `System.out.println(Arrays.toString(a));` – Arvind Kumar Avinash Apr 07 '20 at 21:57

3 Answers3

1

You need to define ToString() to get a nice string print out for objects like Arrays. Arrays don't have one defined by default.

Instead, try using

Arrays.toString(a)
Oleksi
  • 12,947
  • 4
  • 56
  • 80
0

You are printing the string representations of the arrays themselves, not of their contents. That particular representation encodes data type and storage address.

One way to get what you're after would be to use java.util.Arrays.toString():

System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(a1));
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

If you want all the values separated by spaces, you can use a for loop to print out the values; this is slower but you can change it to your liking.

    int n = scan.nextInt();
    int a[] = new int[n];
    int a1[] = new int[5];

    // print a
    System.out.println("Array a values:");
    for (int i = 0; i < a.length; i++) {
        System.out.print(a[i] + " ");
    }
    System.out.println(); // new line

    // print a1
    System.out.println("Array a1 values:");
    for (int i = 0; i < a1.length; i++) {
        System.out.print(a1[i] + " ");
    }
    System.out.println();

Good job on your code, keep getting better!

TheXDShrimp
  • 116
  • 13