Mandy
Mandy

Reputation: 513

Weird return value of copyOf method in Java

I was trying to copy an array in Java and I used the method copyOf. Here's my code and the weird return value. I was expecting {10,50,40}, but it returns [I@35960f05. What exactly is this? Thanks!!enter image description here

Upvotes: 0

Views: 411

Answers (4)

Peter Paul Kiefer
Peter Paul Kiefer

Reputation: 2134

This is the default output of the Array.toString() method, which is automatically called by Sytem.out.println(obj). This out starts with a '[' indicating, that it is an Array, followed by the type 'I' for integer. There are also other types 'B' for Byte, S for String and so on. Then it is follwed by in internal address of you array.

There is a convenience method in the Arrays Class, which is also called toString, that iterates over the array and prints out the elements.

System.out.println(Arrays.toString(arr2));

This can also be done in an explicit for loop.

System.out.print("{");
for ( int val : arr2 )
{
   System.out.print("" + val + ",");
}
System.out.print("}");

Upvotes: 0

Naman Gala
Naman Gala

Reputation: 4692

The problem is not with copyOf method, you have to iterate your int array (arr2) while printing.


Or you can use Arrays.toString(int[] a) method.

System.out.println(Arrays.toString(arr2));

Upvotes: 1

Estimate
Estimate

Reputation: 1461

Instead of iterating Array elements, you may print the copy of array. So it will return the toString() and it may print accordingly.

Upvotes: 0

Shriram
Shriram

Reputation: 4411

int arr2[] is an array of integers. You have to iterate.

Upvotes: 1

Related Questions