-3

I'm trying to write some code in Java revolving around a Char Array and have some questions, starting with the 1st one below. If possible anywhere in the code, I prefer to use Java 8 and avoid using loops. Please help and thank you.

Question 1: Print out the max capacity for a character array.

// Create a character array that can hold a max of 10 elements and copy 
over the contents from another character array.

char[] charArr1 = {'A','B','C'};
char[] charArr2 = new char[10];
charArr2 = charArr1.clone();

// I wanted the result below to be 10, but the output was 3.

System.out.println(charArr2.length);
2

1 Answer 1

0

Here:

char[] charArr2 = new char[10];
charArr2 = charArr1.clone();

You assume:

I wanted the result below to be 10, but the output was 3.

Your problem is that clone() doesn't do what you think it does. You think that it copies the content of one array into another. But that is not what happens. Instead:

When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.

(from this answer).

If you want to keep the array that you created using new char[10]; you will have to use System.arraycopy() for example. That call keeps the target array, copies in values from some source array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.