{"id":1178,"date":"2022-02-24T19:58:35","date_gmt":"2022-02-24T19:58:35","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1178"},"modified":"2022-02-24T19:58:35","modified_gmt":"2022-02-24T19:58:35","slug":"java-copy-arrays","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/24\/java-copy-arrays\/","title":{"rendered":"Java Copy Arrays"},"content":{"rendered":"\n<p>In this tutorial, you will learn about different ways you can use to copy arrays (both one dimensional and two-dimensional) in Java with the help of examples.<\/p>\n\n\n\n<p>In Java, we can copy one array into another. There are several techniques you can use to copy arrays in Java.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"assignment\">1. Copying Arrays Using Assignment Operator<\/h2>\n\n\n\n<p>Let&#8217;s take an example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n    public static void main(String&#91;] args) {\n       \n        int &#91;] numbers = {1, 2, 3, 4, 5, 6};\n        int &#91;] positiveNumbers = numbers;    \/\/ copying arrays\n\n        for (int number: positiveNumbers) {\n            System.out.print(number + \", \");\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>1, 2, 3, 4, 5, 6<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have used the assignment operator (<code>=<\/code>) to copy an array named&nbsp;<var>numbers<\/var>&nbsp;to another array named&nbsp;<var>positiveNumbers<\/var>.<\/p>\n\n\n\n<p>This technique is the easiest one and it works as well. However, there is a problem with this technique. If we change elements of one array, corresponding elements of the other arrays also change. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n    public static void main(String&#91;] args) {\n      \n        int &#91;] numbers = {1, 2, 3, 4, 5, 6};\n        int &#91;] positiveNumbers = numbers;    \/\/ copying arrays\n      \n        \/\/ change value of first array\n        numbers&#91;0] = -1;\n\n        \/\/ printing the second array\n        for (int number: positiveNumbers) {\n            System.out.print(number + \", \");\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>-1, 2, 3, 4, 5, 6<\/samp><\/code><\/pre>\n\n\n\n<p>Here, we can see that we have changed one value of the&nbsp;<var>numbers<\/var>&nbsp;array. When we print the&nbsp;<var>positiveNumbers<\/var>&nbsp;array, we can see that the same value is also changed.<\/p>\n\n\n\n<p>It&#8217;s because both arrays refer to the same array object. This is because of the shallow copy. To learn more about shallow copy, visit\u00a0shallow copy.<\/p>\n\n\n\n<p>Now, to make new array objects while copying the arrays, we need deep copy rather than a shallow copy.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"using-loop\">2. Using Looping Construct to Copy Arrays<\/h2>\n\n\n\n<p>Let&#8217;s take an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\n\nclass Main {\n    public static void main(String&#91;] args) {\n      \n        int &#91;] source = {1, 2, 3, 4, 5, 6};\n        int &#91;] destination = new int&#91;6];\n\n        \/\/ iterate and copy elements from source to destination\n        for (int i = 0; i &lt; source.length; ++i) {\n            destination&#91;i] = source&#91;i];\n        }\n      \n         \/\/ converting array to string\n        System.out.println(Arrays.toString(destination));\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1, 2, 3, 4, 5, 6]<\/code><\/pre>\n\n\n\n<p>In the above example, we have used the&nbsp;<code>for<\/code>&nbsp;loop to iterate through each element of the source array. In each iteration, we are copying elements from the&nbsp;<var>source<\/var>&nbsp;array to the&nbsp;<var>destination<\/var>&nbsp;array.<\/p>\n\n\n\n<p>Here, the source and destination array refer to different objects (deep copy). Hence, if elements of one array are changed, corresponding elements of another array is unchanged.<\/p>\n\n\n\n<p>Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(Arrays.toString(destination));<\/code><\/pre>\n\n\n\n<p>Here, the toString() method is used to convert an array into a string. To learn more, visit the\u00a0toString() method (official Java documentation).<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"arraycopy\">3. Copying Arrays Using arraycopy() method<\/h2>\n\n\n\n<p>In Java, the\u00a0System class\u00a0contains a method named\u00a0<code>arraycopy()<\/code>\u00a0to copy arrays. This method is a better approach to copy arrays than the above two.<\/p>\n\n\n\n<p>The&nbsp;<code>arraycopy()<\/code>&nbsp;method allows you to copy a specified portion of the source array to the destination array. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>arraycopy(Object src, int srcPos,Object dest, int destPos, int length)<\/code><\/pre>\n\n\n\n<p>Here,<\/p>\n\n\n\n<ul><li><var>src<\/var>&nbsp;&#8211; source array you want to copy<\/li><li><var>srcPos<\/var>&nbsp;&#8211; starting position (index) in the source array<\/li><li><var>dest<\/var>&nbsp;&#8211; destination array where elements will be copied from the source<\/li><li><var>destPos<\/var>&nbsp;&#8211; starting position (index) in the destination array<\/li><li><var>length<\/var>&nbsp;&#8211; number of elements to copy<\/li><\/ul>\n\n\n\n<p>Let&#8217;s take an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ To use Arrays.toString() method\nimport java.util.Arrays;\n\nclass Main {\n    public static void main(String&#91;] args) {\n        int&#91;] n1 = {2, 3, 12, 4, 12, -2};\n      \n        int&#91;] n3 = new int&#91;5];\n\n        \/\/ Creating n2 array of having length of n1 array\n        int&#91;] n2 = new int&#91;n1.length];\n      \n        \/\/ copying entire n1 array to n2\n        System.arraycopy(n1, 0, n2, 0, n1.length);\n        System.out.println(\"n2 = \" + Arrays.toString(n2));  \n      \n        \/\/ copying elements from index 2 on n1 array\n        \/\/ copying element to index 1 of n3 array\n        \/\/ 2 elements will be copied\n        System.arraycopy(n1, 2, n3, 1, 2);\n        System.out.println(\"n3 = \" + Arrays.toString(n3));  \n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>n2 = &#91;2, 3, 12, 4, 12, -2]\nn3 = &#91;0, 12, 4, 0, 0]<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have used the&nbsp;<code>arraycopy()<\/code>&nbsp;method,<\/p>\n\n\n\n<ul><li><code>System.arraycopy(n1, 0, n2, 0, n1.length)<\/code>&nbsp;&#8211; entire elements from the&nbsp;<var>n1<\/var>&nbsp;array are copied to&nbsp;<var>n2<\/var>&nbsp;array<\/li><li><code>System.arraycopy(n1, 2, n3, 1, 2)<\/code>&nbsp;&#8211;&nbsp;<var>2<\/var>&nbsp;elements of the&nbsp;<var>n1<\/var>&nbsp;array starting from index&nbsp;<var>2<\/var>&nbsp;are copied to the index starting from&nbsp;<var>1<\/var>&nbsp;of the&nbsp;<var>n3<\/var>&nbsp;array<\/li><\/ul>\n\n\n\n<p>As you can see, the default initial value of elements of an&nbsp;<var>int<\/var>&nbsp;type array is 0.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"copyofrange\">4. Copying Arrays Using copyOfRange() method<\/h2>\n\n\n\n<p>We can also use the copyOfRange() method defined in\u00a0Java Arrays\u00a0class to copy arrays. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ To use toString() and copyOfRange() method\nimport java.util.Arrays;\n\nclass ArraysCopy {\n    public static void main(String&#91;] args) {\n      \n        int&#91;] source = {2, 3, 12, 4, 12, -2};\n      \n        \/\/ copying entire source array to destination\n        int&#91;] destination1 = Arrays.copyOfRange(source, 0, source.length);      \n        System.out.println(\"destination1 = \" + Arrays.toString(destination1)); \n      \n        \/\/ copying from index 2 to 5 (5 is not included) \n        int&#91;] destination2 = Arrays.copyOfRange(source, 2, 5); \n        System.out.println(\"destination2 = \" + Arrays.toString(destination2));   \n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>destination1 = &#91;2, 3, 12, 4, 12, -2]\ndestination2 = &#91;12, 4, 12]<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int&#91;] destination1 = Arrays.copyOfRange(source, 0, source.length);<\/code><\/pre>\n\n\n\n<p>Here, we can see that we are creating the\u00a0<var>destination1<\/var>\u00a0array and copying the\u00a0<var>source<\/var>\u00a0array to it at the same time. We are not creating the\u00a0<var>destination1<\/var>\u00a0array before calling the\u00a0<code>copyOfRange()<\/code>\u00a0method. To learn more about the method, visit\u00a0Java copyOfRange.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"copying-2d\">5. Copying 2d Arrays Using Loop<\/h2>\n\n\n\n<p>Similar to the single-dimensional array, we can also copy the 2-dimensional array using the&nbsp;<code>for<\/code>&nbsp;loop. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\n\nclass Main {\n    public static void main(String&#91;] args) {\n      \n        int&#91;]&#91;] source = {\n              {1, 2, 3, 4}, \n              {5, 6},\n              {0, 2, 42, -4, 5}\n              };\n\n        int&#91;]&#91;] destination = new int&#91;source.length]&#91;];\n\n        for (int i = 0; i &lt; destination.length; ++i) {\n\n            \/\/ allocating space for each row of destination array\n            destination&#91;i] = new int&#91;source&#91;i].length];\n\n            for (int j = 0; j &lt; destination&#91;i].length; ++j) {\n                destination&#91;i]&#91;j] = source&#91;i]&#91;j];\n            }\n        }\n     \n        \/\/ displaying destination array\n        System.out.println(Arrays.deepToString(destination));  \n      \n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><samp>[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]<\/samp><\/pre>\n\n\n\n<p>In the above program, notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(Arrays.deepToString(destination);<\/code><\/pre>\n\n\n\n<p>Here, the\u00a0<code>deepToString()<\/code>\u00a0method is used to provide a better representation of the 2-dimensional array. To learn more, visit\u00a0Java deepToString().<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"arraycopy-2d\">Copying 2d Arrays using arraycopy()<\/h2>\n\n\n\n<p>To make the above code more simpler, we can replace the inner loop with&nbsp;<code>System.arraycopy()<\/code>&nbsp;as in the case of a single-dimensional array. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\n\nclass Main {\n    public static void main(String&#91;] args) {\n      \n        int&#91;]&#91;] source = {\n              {1, 2, 3, 4}, \n              {5, 6},\n              {0, 2, 42, -4, 5}\n              };\n\n        int&#91;]&#91;] destination = new int&#91;source.length]&#91;];\n\n        for (int i = 0; i &lt; source.length; ++i) {\n\n             \/\/ allocating space for each row of destination array\n             destination&#91;i] = new int&#91;source&#91;i].length];\n             System.arraycopy(source&#91;i], 0, destination&#91;i], 0, destination&#91;i].length);\n        }\n     \n        \/\/ displaying destination array\n        System.out.println(Arrays.deepToString(destination));      \n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><samp>[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]<\/samp><\/pre>\n\n\n\n<p>Here, we can see that we get the same output by replacing the inner&nbsp;<code>for<\/code>&nbsp;loop with the&nbsp;<code>arraycopy()<\/code>&nbsp;method.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn about different ways you can use to copy arrays (both one dimensional and two-dimensional) in Java with the help of examples. In Java, we can copy one array into another. There are several techniques you can use to copy arrays in Java. 1. Copying Arrays Using Assignment Operator Let&#8217;s [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[427],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1178"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1178"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1178\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1178"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1178"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1178"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}