{"id":76600,"date":"2020-02-19T10:05:07","date_gmt":"2020-02-19T04:35:07","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=76600"},"modified":"2020-02-19T10:05:07","modified_gmt":"2020-02-19T04:35:07","slug":"java-array","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-array\/","title":{"rendered":"Java Array &#8211; An Ultimate Guide for a Beginner"},"content":{"rendered":"<p>Till now, you have been working with data in Java programs in a simple manner. But now, one question arises: how would you create classes\/objects for a situation where you have to deal with a collection of similar data items?<\/p>\n<p>For example, suppose you have to handle marks of 20 students. That is, you have to handle 20 marks variables. How would you do so?\u00a0 We will have to declare and initialize 20 marks variables. Similarly, if there are 100 students we will have to do the same for 100 students.<\/p>\n<p>To simplify this, Java offers a reference data type called arrays. An array can hold multiple values of the same type.<\/p>\n<p>In this article, we will discuss the arrays in Java along with their types.<\/p>\n<h3>Java Array<\/h3>\n<p>An Array, one of the data structures in Java, is a collection of variables of the same type that are referenced by a common name. Arrays consist of contiguous memory locations. The first address of the array belongs to the first element and the last address to the last element of the array.<\/p>\n<p>Some points about arrays:<\/p>\n<ul>\n<li>Arrays can have data items of simple types such as int or float, or even user-defined datatypes like structures and objects.<\/li>\n<li>The common data type of array elements is known as the base type of the array.<\/li>\n<li>Arrays are considered as objects in Java.<\/li>\n<li>The indexing of the variable in an array starts from 0.<\/li>\n<li>Like other <em><strong>variables in Java<\/strong><\/em>, an array must be defined before it can be used to store information.<\/li>\n<li>Arrays in Java are stored in the form of dynamic allocation in the heap area.<\/li>\n<li>We can find the length of arrays using the member \u2018length\u2019.<\/li>\n<li>The size of an array must be an int value.<\/li>\n<li>Object class is a superclass of the Array.<\/li>\n<li>Array implements the two interfaces: Serializable and Cloneable.<\/li>\n<\/ul>\n<h3>The need for an Array<\/h3>\n<p>Arrays are very useful in cases where many elements of the same data types need to be stored and processed. It is also useful in real-time projects to collect the same type of objects and send all the values with a single method call.<\/p>\n<h3>Types of Java Arrays<\/h3>\n<p><strong>1. Single dimensional arrays\/one-dimensional array<\/strong> &#8211; comprised of finite homogeneous elements.<\/p>\n<p><strong>2. Multi-dimensional arrays<\/strong> &#8211; comprised of elements, each of which is itself an array.<\/p>\n<p>The simplest of multidimensional arrays is a two-dimensional array. However, Java allows arrays of more than two dimensions. The compiler you use can determine the exact limit of dimensions.<\/p>\n<p>We will discuss in detail about single-dimensional and two-dimensional arrays:<\/p>\n<h4><span style=\"font-size: 18.72px;font-weight: bold\">1. Single Dimensional Arrays<\/span><\/h4>\n<p>The simplest form of an array is a single-dimensional array. It has elements in a single dimension. Such as a variable, method, and class, we can give a name to the array. And, we refer to array elements by their subscripts or indices.<\/p>\n<h5>1.1. Declaring one-dimensional arrays<\/h5>\n<p>Like other definitions, an array definition specifies a variable type and a name along with one more feature size to specify how many items the array will contain.<\/p>\n<p><strong>The valid syntax for array declaration can be &#8211;<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">data-type array_name [ ];\ndata-type [ ] array_name;<\/pre>\n<p><strong>Example &#8211;<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int daysInMonth [ ];\nchar [ ] lettersInSentence;\ndouble salaryOfEmployees [ ];\nString progLanguages[ ];<\/pre>\n<h5>1.2. Initializing one-dimensional arrays<\/h5>\n<p>After declaring an array, we allocate the memory to the array with the help of a new operator and assign the memory to the array variable. So, let us see how we can initialize arrays in different ways. The variable size of the array should be of constant integer type without any sign (+ or -).<\/p>\n<p><strong>The valid syntax for array initialization can be &#8211;<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">array_name = new data-type [size of array];\narray_name = new data-type {elements of array using commas};<\/pre>\n<p><strong>Example &#8211;<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">daysInMonth = new int [100];\nlettersInSentence = new char[5];\nsalaryOfEmployees = new double[ ] {10000, 50000, 30000, 25000 };\nprogLanguages = { \u201cC\u201d, \u201cJava\u201d, \u201cRuby\u201d, \u201cPython\u201d, \u201cPHP\u201d };<\/pre>\n<p>We can also combine declaration and initialization and write as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int daysInMonth[ ] = new int [100];\nchar [ ] lettersInSentence = new char[5];<\/pre>\n<p><em><strong>Note<\/strong> &#8211; Java stores the value of each element with 0 if the elements of an array are not given.<\/em><\/p>\n<p>The below diagram shows the illustration of one-dimensional arrays.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/one-dimensional-array-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76751\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/one-dimensional-array-in-java.jpg\" alt=\"one dimensional array in java\" width=\"864\" height=\"406\" \/><\/a><\/p>\n<h5>1.3. Accessing or using one-dimensional arrays<\/h5>\n<p>An array element may be accessed or used in a place where an ordinary variable of the same type may be used. An array element is addressed or referred using the array name followed by an integer subscript or index in square brackets[ ].<\/p>\n<p>For example, myArray[2]; will give us the third element of the array myArray.<\/p>\n<p>We can access each element of the array using Java <strong>for<\/strong> loop.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">\/\/ accessing all elements of the specified array\nfor (int i = 0; i &lt; myArray.length; i++)\n   System.out.println(\"Element at index \" + i + \" : \"+ myArray[ i ]);<\/pre>\n<p><strong>Code Snippet to illustrate declaring, initializing, and accessing array:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.TechVidvan.JavaArrays;\npublic class OneDimesionalArray\n{\n  \/\/ Java program to illustrate store and print marks of 5 students\n  public static void main (String[] args)\n  {\n    \/\/ declaring an Array of integers.\n    int[] marks;\n\n    \/\/ allocating memory for 5 integers.\n    marks = new int[5];\n    \n    \/\/ initializing the first element of the array\n    marks[0] = 78;\n    \/\/ initializing the second element of the array and so on..\n    marks[1] = 85;\n    marks[2] = 97;\n    marks[3] = 66;\n    marks[4] = 70;\n\n    \/\/ accessing the elements of the specified array\n    for (int iterator = 0; iterator &lt; marks.length; iterator++)\n    System.out.println(\"Marks of Student \" + (iterator+1) +\": \"+ marks[iterator]);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Marks of Student 1: 78<br \/>\nMarks of Student 2: 85<br \/>\nMarks of Student 3: 97<br \/>\nMarks of Student 4: 66<br \/>\nMarks of Student 5: 70<\/div>\n<p>We can also access or use the elements of Java array using a <strong>for-each<\/strong> loop. The for-each loop in Java is used to print the array elements one after the other. It holds an array element in a variable and then executes the loop body.<\/p>\n<p><strong>The syntax of the for-each loop is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">for(data_type variable:array)\n{\n        \/\/body of the loop\n}<\/pre>\n<p><strong>Code Snippet to access an array using a for-each loop:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\npublic class OneDimesionalArray\n{\n  public static void main (String[] args)\n  {\n    \/\/ declaring an Array of integers.\n    int[] marks = new int[5];\n    \/\/ initialize elements of the array\n    marks[0] = 78;\n    marks[1] = 85;\n    marks[2] = 97;\n    marks[3] = 66;\n    marks[4] = 70;\n\n    \/\/ accessing the elements of the specified array\n    System.out.println(\"Marks of 5 Students:\");\n    for (int iterator :marks)\n      System.out.println(iterator);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Marks of 5 Students:<br \/>\n78<br \/>\n85<br \/>\n97<br \/>\n66<br \/>\n70<\/div>\n<h5>Passing an Array to a method or function<\/h5>\n<p>We can also pass the Java array to methods or functions, just like normal variables. Passing an array to method helps us to reuse the same logic on any array.<\/p>\n<p>When we pass an array as an argument to a method, it is actually the address of the first element of the array (base address) which is passed as a reference. Therefore, if we make any changes to this array in the method, it will affect the array.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>When we pass an array to a method, we specify the name of the array without any square brackets within the method call.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int[] num = new int[10]; \t\/\/array declaration\nmethodName (int [] x) \t\t\/\/passing an array to method\n{\n  \/\/method body\n}\nmethodName (num);  \t\t\t\/\/calling the method<\/pre>\n<p><strong>Code to illustrate the passing of an array to a method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package package com.techvidvan.javaarrays;;\npublic class PassingArrayToMethod\n{\n  public static void main (String[] args)\n  {\n    int myArray[] = { 1, 2, 3, 4, 5, 6 }; \/\/creating array\n    System.out.println(\"Array before passing to a method:\");\n    {\n      for(int i=0; i&lt;myArray.length;i++)\n      {\n        System.out.println(myArray[i]);\n      }\n    }\n    System.out.println(\"Array after passing to a method:\");\n    \/\/calling method by passing myArray to them.\n    manipulateArray(myArray);\n    display(myArray);\n  } \/\/main method ends here\n  static void manipulateArray(int a[]) \/\/declaring method\n  {\n    for(int i=0; i&lt;a.length;i++)\n    {\n      a[i] = a[i]*10;\n    }\n  }\n  static void display(int a[]) \/\/declaring method\n  {\n    System.out.println(\"Displaying array elements after \t\t\t\t\tmultiplying each element by 10:\");\n    for(int i=0; i&lt;a.length;i++)\n    {\n      System.out.println( a[i] );\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Array before passing to a method:<br \/>\n1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<br \/>\n6<br \/>\nArray after passing to a method:<br \/>\nDisplaying array elements after multiplying each element by 10:<br \/>\n10<br \/>\n20<br \/>\n30<br \/>\n40<br \/>\n50<br \/>\n60<\/div>\n<h3>Array Members<\/h3>\n<p>Arrays are the object of a class, and the <strong>class \u2018Object\u2019<\/strong> is the direct superclass of arrays. The members of an array are:<\/p>\n<ul>\n<li>The field <strong>public final length<\/strong> which stores the number of elements of the array. length can be either zero or positive, but never be negative.<\/li>\n<li>All the members are inherited from their superclass <strong>\u2018Object<\/strong>\u2019. But, there is a method clone() that is not inherited from Object class.<\/li>\n<li>The public method <strong>clone()<\/strong> overrides the clone method in class Object and does not throw any checked exceptions.<\/li>\n<\/ul>\n<h4>1.4. Memory Representation of single-dimensional arrays<\/h4>\n<p>Single-dimensional arrays are lists of data of the same type and their elements are stored in a contiguous memory location in their index order. For instance, an array age of type int with 5 elements is declared as:<\/p>\n<p>int age[ ] = new int[5 ];<\/p>\n<p>Or as,<\/p>\n<p>int[ ] age = new int[5 ];<\/p>\n<p>This array will have age[0] at the first allocated memory location, age[1] at the next memory location and so on. Since age is an int type array, the size of each element is 4 bytes. If the starting memory location of array age is 5000, then it will be represented in the memory location as follows:<\/p>\n<p><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/memory-representation-of-single-dimensional-array.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76750\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/memory-representation-of-single-dimensional-array.jpg\" alt=\"single dimensional memory representation\" width=\"600\" height=\"240\" \/><\/a><\/strong><\/p>\n<h3>ArrayIndexOutOFBoundExceptions<\/h3>\n<p>We can address or refer to each element of the array using the name of the array with subscripts or indexes 0, 1, 2\u2026.., size-1, where size is the total number of elements of the array. That is if an array is arr[6], then legal array elements would be:<\/p>\n<p>arr[0] , arr[1], arr[2], arr[3], arr[4], arr[5]<\/p>\n<p>Subscripts or index which are less than zero or greater than or equal (&gt;=) to a number of elements are illegal since they do not correspond to real memory locations in the array. For example, the following are some illegal subscripts for above-mentioned array (that is, all other than legal subscripts):<\/p>\n<p>arr[-5], arr[-1], arr[8], arr[7] etc.<\/p>\n<p>These subscripts are said to be<strong> out-of-bounds<\/strong>. Reference to an out-of-bounds indexing produces an <strong>out-of-bounds exception<\/strong>, and the program will crash if the exception is not handled.<\/p>\n<p><em><strong>Note:<\/strong> The subscripts other than 0\u2026..n-1 (both inclusive limits) for an array having n elements, are called out-of-bound subscripts.<\/em><\/p>\n<p><strong>Code to understand OutOfBoundsException:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package package com.techvidvan.javaarrays;;\npublic class OneDimesionalArray\n{\n  public static void main (String[] args)\n  {\n    int[] arr = new int[5];\n    arr[0] = 10;\n    arr[1] = 20;\n    arr[2] = 10;\n    arr[3] = 20;\n    arr[4] = 10;\n    \/\/ trying to access arr[5] will give an exception\n    for (int i = 0; i &lt;= 5; i++)\n      System.out.println(arr[i]);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">10<br \/>\n20<br \/>\n10<br \/>\n20<br \/>\n10<br \/>\nException in thread &#8220;main&#8221; java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5<br \/>\nat project1\/package com.techvidvan.javaarrays;.OneDimesionalArray.main(OneDimesionalArray.java:19)<\/div>\n<h3>Multi-Dimensional Arrays<\/h3>\n<p>Till now, we have worked on arrays with a single dimension. Now we will move to the concept of multi-dimensional arrays that have multiple or more than one dimension.<\/p>\n<p>Multi-dimensional arrays are arrays <strong>of arrays<\/strong> in which each element of the array holds the reference of other arrays. We can also call them Jagged Arrays. The most commonly used multi-dimensional array is a <strong>two-dimensional array.<\/strong><\/p>\n<p><strong>A two-dimensional<\/strong> array is an array in which each element is a one-dimensional array.<\/p>\n<p>For example, a two-dimensional array <strong>myArray [ M ]<\/strong>[ N ] is an M by N table with M rows and N columns containing <strong>M N elements.<\/strong><\/p>\n<p>By multiplying the number of rows with the number of columns we can determine the number of elements in a two-dimensional array. For example, the number of elements in an array arr [7][9] is calculated as 7 9 = 63.<\/p>\n<p>Following diagram illustrates a multi-dimensional array:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/multi-dimensional-array-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76752\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/multi-dimensional-array-in-java.jpg\" alt=\"multi dimensional java array\" width=\"678\" height=\"398\" \/><\/a><\/p>\n<p><strong>Syntax of declaring two-dimensional arrays is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">type array-name [ ][ ]= new type[number of rows] [number of columns];<\/pre>\n<p>or,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">type [ ][ ] array-name = new type[number of rows] [number of columns];<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int myArray [ ] [ ] = new int [5] [12] ;<\/pre>\n<p>or,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int[ ] [ ] myArray = new int[5] [12] ;<\/pre>\n<p>The array <strong>myArray<\/strong> has 5 elements myArray [0], myArray[1], myArray[3], and myArray[4], each of which itself is an <strong>int<\/strong> array with <strong>12 elements<\/strong>.<\/p>\n<p>The elements of myArray can be referred to as myArray[0][0], myArray[0][1], myArray[0][2],\u2026\u2026.., myArray[0][12], myArray [1][0], &#8230;&#8230;. and so forth.<\/p>\n<p><strong>Code to understand two-dimensional arrays:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package package com.techvidvan.javaarrays;\npublic class TwoDimensionalArrays\n{\n  public static void main (String[] args)\n  {\n    \/\/declaring and initializing a two-dimensional array\n    int[][] myArray = new int[3][3];\n\n    myArray[0][0]=1;\n    myArray[0][1]=2;\n    myArray[0][2]=3;\n    myArray[1][0]=4;\n    myArray[1][1]=5;\n    myArray[1][2]=6;\n    myArray[2][0]=7;\n    myArray[2][1]=8;\n    myArray[2][2]=9;\n\n    \/\/printing a two-dimensional array\n    for(int i=0;i&lt;3;i++)\n    {\n      for(int j=0;j&lt;3;j++)\n      {\n        System.out.print(myArray[i][j]+\" \");\n      }\n      System.out.println();\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">1 2 3<br \/>\n4 5 6<br \/>\n7 8 9<\/div>\n<h3>Cloning of arrays<\/h3>\n<p>There are 2 different types of cloning of arrays, they are as follows &#8211;<\/p>\n<h4>1. Cloning single-dimensional arrays<\/h4>\n<p>Cloning a single-dimensional array, such as Object[ ], means performing a \u201cdeep copy\u201d operation in which a new array is created, which contains copies of the elements of the original arrays. We can perform cloning of arrays in Java with the help of the <strong>clone()<\/strong> method:<\/p>\n<p>Cloning is necessary when we want to create an object with a similar state as the original object. In short, with the help of Cloning single-dimension, we can create the copy of the original object.<\/p>\n<p><strong>Code to illustrate cloning of one-dimensional arrays:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class Cloning\n{\n  public static void main(String[] args)\n  {\n    int intArray[] = { 50, 60, 70 };\n    int clonedArray[] = intArray.clone();\n\n    \/\/ will print false as a deep copy is created for a one-dimensional array\n    System.out.println(intArray == clonedArray);\n\n    System.out.print(\"Printing cloned array:\\n\");\n    for (int i = 0; i &lt; clonedArray.length; i++)\n    {\n      System.out.print(clonedArray[i]+\" \");\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">false<br \/>\nPrinting cloned array:<br \/>\n50 60 70<\/div>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/cloning-single-dimensional-array-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76753\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/cloning-single-dimensional-array-in-java.jpg\" alt=\"single dimensional cloning array\" width=\"540\" height=\"456\" \/><\/a><\/p>\n<h4>2. Cloning of multi-dimensional arrays<\/h4>\n<p>Cloning a multi-dimensional array, such as Object[ ][ ], means performing a \u201cshallow copy\u201d. It creates only a single new array with each element of the array as a reference to an element of the original array.<\/p>\n<p>In the cloning of multi-dimensional arrays, subarrays are shared, that is, they are not cloned.<\/p>\n<p><strong>Code to illustrate cloning of multi-dimensional arrays:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class Cloning\n{\n  public static void main(String[] args)\n  {\n    int intArray[][] = {{1,2,3},{4,5,6}};\n    int clonedArray[][] = intArray.clone();\n\n    \/\/ will print false\n    System.out.println(intArray == clonedArray);\n\n    \/\/ it will print true as a shallow copy is created and sub-arrays are \/\/shared\n    System.out.println(intArray[0] == clonedArray[0]);\n    System.out.println(intArray[1] == clonedArray[1]);\n\n    System.out.println(\"\\nPrinting cloned array:\");\n    for (int i = 0; i &lt; 2; i++)\n    {\n      for (int j = 0; j &lt; 3; j++)\n      {\n        System.out.print(clonedArray[i][j]+ \" \");\n      }\n      System.out.println();\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">false<br \/>\ntrue<br \/>\ntrue<br \/>\nPrinting cloned array:<br \/>\n1 2 3<br \/>\n4 5 6<\/div>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/cloning-multi-dimensional-array-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76754\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/cloning-multi-dimensional-array-in-java.jpg\" alt=\"multi dimensional cloning array \" width=\"650\" height=\"356\" \/><\/a><\/p>\n<h3>The Array class in Java<\/h3>\n<p>The package<strong> java.util.Arrays<\/strong> contain the Array class to perform operations on Arrays. It provides many static methods which are helpful in manipulating and analyzing arrays and getting useful results out of them.<\/p>\n<p>With these methods, we can do the searching, sorting on arrays\u2019 elements, filling an array with a particular value, comparing arrays, etc. We will discuss some important methods of Java Arrays class:<\/p>\n<h3>Methods of Java Array Class<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/methods-of-java-array-class.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76755\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/methods-of-java-array-class.jpg\" alt=\"Java Array methods\" width=\"802\" height=\"420\" \/><\/a><\/p>\n<h4>1. int compare(array1, array2)<\/h4>\n<p>This method compares two arrays in lexicographic order. We pass two arrays as parameters to its methods. It returns <strong>1<\/strong> if array1 is greater than array2, <strong>-1<\/strong> if array1 is smaller than array2, and a 0 if both arrays are equal to each other.<\/p>\n<p><strong>Code to illustrate the compare() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class CompareMethod\n{\n  public static void main(String[] args)\n  {\n\n    \/\/ Create the first Array\n    int myArray1[] = { 10, 15, 32, 30 };\n\n    \/\/ Create the second Array\n    int myArray2[] = { 10, 25, 22 ,30};\n\n    \/\/ comparing both arrays\n    System.out.println(\"Comparing two integer arrays: \"\n        + Arrays.compare(myArray1, myArray2));\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Comparing two integer arrays: -1<\/div>\n<h4>2. void fill(originalArray, value)<\/h4>\n<p>This method is used to fill the specific value to each element of the specified array with a specific type. This method can also be used with all the other primitive data types (byte, short, int, etc.).<\/p>\n<p><strong>Code to illustrate the fill() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class FillMethod\n{\n  public static void main(String[] args)\n  {\n    \/\/ Create the Array\n    int myArray1[] = new int[5];\n\n    int fillvalue = 15;\n\n    Arrays.fill(myArray1, fillvalue);\n\n    \/\/ To fill the arrays\n    System.out.println(\"Integer Array on filling: \"\n        + Arrays.toString(myArray1));\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Integer Array on filling: [ 15,15,15,15,15 ]<\/div>\n<h4>3. boolean equals(array1, array2)<\/h4>\n<p>This method checks whether both the arrays are equal or not and gives the result either as true or false.<\/p>\n<p><strong>Code to illustrate the equals() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class EqualsMethod\n{\n  public static void main(String[] args)\n  {\n    \/\/create arrays to be compared\n    int array1[] = { 45, 68, 34, 20, 56 };\n    int array2[] = { 45, 68, 34, 20, 56 };\n    int array3[] = { 55, 78, 44, 10, 56 };\n\n    System.out.println(\"Comparing array1 and array2: \"\n    + Arrays.equals(array1,array2));\n    System.out.println(\"Comparing array2 and array3: \"\n    + Arrays.equals(array2,array3));\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Comparing array1 and array2: true<br \/>\nComparing array2 and array3: false<\/div>\n<h4>4. int binarySearch(array [], value)<\/h4>\n<p>With the help of this method, we can find or search a specified value inside an array which is given as the first argument. As a result, this method returns the index of the element in the array. The array must be sorted for this search. If the element is not found, it returns a negative value.<\/p>\n<p><strong>Code to illustrate the binarySearch() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class BinarySearch\n{\n  public static void main(String[] args)\n  {\n    \/\/create arrays\n    int array1[] = { 20, 34,56,78,97 };\n    int intKey = 56;\n    System.out.println(intKey + \" found at index = \" + Arrays .binarySearch(array1, intKey));\n    System.out.println(20 + \" found at index = \" + Arrays .binarySearch(array1, 20));\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">56 found at index = 2<br \/>\n20 found at index = 0<\/div>\n<h4>5. copyOf(originalArray, newLength)<\/h4>\n<p>We can copy the specified array to a new array with a specified length. The left spaces are assigned to default values in the new array.<\/p>\n<p><strong>Code to illustrate the copyOf() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.javaarrays;\nimport java.util.Arrays;\npublic class CopyOfMethod\n{\n  public static void main(String[] args)\n  {\n    \/\/create arrays\n    int array1[] = { 65, 20, 34, 56, 78, 97 };\n\n    \/\/ To print the elements in one line\n    System.out.println(\"Integer Array: \"+ Arrays.toString(array1));\n\n    System.out.println(\"\\nNew Arrays by copyOf method:\");\n    System.out.println(\"Integer Array: \"+ Arrays.toString( Arrays.copyOf(array1, 10)));\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Integer Array: [65, 20, 34, 56, 78, 97]New Arrays by copyOf method:<br \/>\nInteger Array: [65, 20, 34, 56, 78, 97, 0, 0, 0, 0]<\/div>\n<h3>Summary<\/h3>\n<p>Arrays are important when we need to store multiple values of the same type. They save time and memory required to store a large amount of data. In this tutorial, we covered each aspect of Java Arrays.<\/p>\n<p>We learned the two types of arrays with their declaration and initialization. We also learned how to access an array and also how to pass an array to a method.<\/p>\n<p>After reading this article, you will be able to clone one dimensional or multi-dimensional arrays. Along with this, we covered the Java Array class with its different static methods. This will surely help you to strengthen your concepts in arrays and write complex codes in Java.<\/p>\n<p>Thank you for reading our article. Don&#8217;t forget to share your thoughts on this through the comment box below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Till now, you have been working with data in Java programs in a simple manner. But now, one question arises: how would you create classes\/objects for a situation where you have to deal with&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":76755,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[1794,1795,1796,1797,1798,1799,1800,1801,1802],"class_list":["post-76600","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-array-in-java","tag-array-members","tag-cloning-array","tag-java-array","tag-methods-in-java-array","tag-multi-dimensional-array-in-java","tag-need-of-array-in-java","tag-one-dimensional-array-in-java","tag-types-of-java-array"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Array - An Ultimate Guide for a Beginner - TechVidvan<\/title>\n<meta name=\"description\" content=\"Get to know in detail about Java Array &amp; its 2 types. Also, learn how to access an array &amp; the 5 methods of Array in Java explained with coding examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-array\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Array - An Ultimate Guide for a Beginner - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Get to know in detail about Java Array &amp; its 2 types. Also, learn how to access an array &amp; the 5 methods of Array in Java explained with coding examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-array\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-02-19T04:35:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"16 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Array - An Ultimate Guide for a Beginner - TechVidvan","description":"Get to know in detail about Java Array & its 2 types. Also, learn how to access an array & the 5 methods of Array in Java explained with coding examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-array\/","og_locale":"en_US","og_type":"article","og_title":"Java Array - An Ultimate Guide for a Beginner - TechVidvan","og_description":"Get to know in detail about Java Array & its 2 types. Also, learn how to access an array & the 5 methods of Array in Java explained with coding examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-array\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-02-19T04:35:07+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"16 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Array &#8211; An Ultimate Guide for a Beginner","datePublished":"2020-02-19T04:35:07+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/"},"wordCount":2172,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg","keywords":["array in java","Array Members","Cloning Array","java array","Methods in Java Array","Multi-Dimensional Array in Java","Need Of Array in Java","One-Dimensional Array in java","types of java array"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-array\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/","url":"https:\/\/techvidvan.com\/tutorials\/java-array\/","name":"Java Array - An Ultimate Guide for a Beginner - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg","datePublished":"2020-02-19T04:35:07+00:00","description":"Get to know in detail about Java Array & its 2 types. Also, learn how to access an array & the 5 methods of Array in Java explained with coding examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-array\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/methods-of-java-array-class.jpg","width":802,"height":420,"caption":"Java Array methods"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-array\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Array &#8211; An Ultimate Guide for a Beginner"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76600","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=76600"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76600\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/76755"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=76600"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=76600"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=76600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}