-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);
qccaprospect
  • 141
  • 1
  • 5
  • 14
  • 1
    [Why is β€œCan someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – Johannes Kuhn Sep 09 '19 at 02:39
  • `charArr2 = ...` is an assignment (see https://stackoverflow.com/questions/3858510/assigning-in-java), so `new char[10]` disappears – njzk2 Sep 09 '19 at 02:42

1 Answers1

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248