0

how do i initialize a new array out of known arrays?

e.g.

char[] word1 = new char[]{'H', 'e', 'l', 'l', 'o'};
char[] word2 = new char[]{'W', 'o', 'r', 'l', 'd'};
char[] newArray;

so how do i initialize newArray out of word1 and word2?

thanks.

  • 2
    Assuming you want to join the two into a single array, take a look here - http://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java – Steve Jul 10 '16 at 14:03

2 Answers2

2

Create the new array and copy the values using System.arraycopy().

char[] word1 = new char[]{'H', 'e', 'l', 'l', 'o'};
char[] word2 = new char[]{'W', 'o', 'r', 'l', 'd'};
char[] newArray = new char[word1.length + word2.length];
System.arraycopy(word1, 0, newArray, 0, word1.length);
System.arraycopy(word2, 0, newArray, word1.length, word2.length);
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

Use this code to initialize newArray:

char[] newArray = ArrayUtils.addAll(word1, word2);

This should do it.

VatsalSura
  • 926
  • 1
  • 11
  • 27
  • i tried it this way but i need to type it in in my university's website and it tells me its wrong. are there any other solutions? it should be a newbie solution. – Engin Topuzoglu Jul 10 '16 at 14:18
  • If there is another way then I don't know it. But you can store it in `List` if you want. – VatsalSura Jul 10 '16 at 14:31