Reputation: 35
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?
Upvotes: 1
Views: 44
Reputation: 116
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!
Upvotes: 0
Reputation: 180181
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));
Upvotes: 0
Reputation: 13097
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)
Upvotes: 1