{"id":1347,"date":"2015-06-14T10:17:39","date_gmt":"2015-06-14T04:47:39","guid":{"rendered":"https:\/\/theoryofprogramming.wordpress.com\/?p=1347"},"modified":"2015-06-14T10:17:39","modified_gmt":"2015-06-14T04:47:39","slug":"java-tutorials-arrays-in-java","status":"publish","type":"post","link":"https:\/\/theoryofcoding.com\/index.php\/2015\/06\/14\/java-tutorials-arrays-in-java\/","title":{"rendered":"Java Tutorials \u2013 Arrays in Java"},"content":{"rendered":"<p>Hello people..! This is a new post in Java Tutorials \u2013 Arrays in Java. In this post I will talk about about using arrays in Java. Arrays in Java are different from arrays in C. Arrays in Java are actually objects. But understanding arrays as being-an-object point-of-view is not something beginners feel comfortable with. So this discussion will introduce new terms and concepts. So, let&#8217;s get started&#8230;!<\/p>\n<h3>Arrays in Java<\/h3>\n<p>Creating an array in Java has 3 steps &#8211;<\/p>\n<ul>\n<li><strong>Declaration<\/strong> &#8211; In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don&#8217;t mention the sizes of dimensions yet. They are left empty.<\/li>\n<li><strong>Instantiation<\/strong> &#8211; In this step, we create the array, or allocate memory for the array, using the <b><span style=\"font-family:Consolas;color:blue;\">new<\/span><\/b> keyword. It is in this step that we mention the sizes of the array dimensions.<\/li>\n<li><strong>Initialization<\/strong> &#8211; The array is always initialized to the data type&#8217;s default value. But we can make our own initializations.<\/li>\n<\/ul>\n<p>Now, let&#8217;s look at the individual steps in a little more detail.<\/p>\n<h3>Declaration<\/h3>\n<p>This is how we declare a one-dimensional array in Java &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] array;\n<\/pre>\n<p>Well, you should have guesses it because we&#8217;ve been declaring arrays right from our first program&#8230;! Really..? Yeah..! In the <b><span style=\"font-family:Consolas;\">main()<\/span><\/b> method&#8217;s declaration..!<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic static void main(String&#x5B;] args) {\n    \/\/ code\n}\n<\/pre>\n<p>The formal parameter of the <b><span style=\"font-family:Consolas;\">main()<\/span><\/b> method is a one-dimensional array of <b><span style=\"font-family:Consolas;\">String<\/span><\/b>s. Well, for C programmers, it might look like we are almost done with creating an array&#8230; But no..! We have just merely declared it, we have not allocated any memory yet.<br \/>\nThere is another syntax by which we can declare arrays &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint array&#x5B;];\n<\/pre>\n<p>This is looks almost like the C&#8217;s array declaration. But here, we don&#8217;t specify the size&#8230; Not yet..! But this style of declaration is considered to be ugly..! Oracle recommends that you use the previously discussed declaration syntax for declaring arrays.<br \/>\nHere are some other examples of legal declarations &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\/\/ One Dimensional Arrays\nint&#x5B;] intArray;             \/\/ Good\ndouble&#x5B;] doubleArray;\n\n\/\/ One Dimensional Arrays\nbyte byteArray&#x5B;];           \/\/ Ugly!\nlong longArray&#x5B;];\n\n\/\/ Two Dimensional Arrays\nint&#x5B;]&#x5B;] int2DArray;         \/\/ Good\ndouble&#x5B;]&#x5B;] double2DArray;\n\n\/\/ Two Dimensional Arrays\nbyte&#x5B;] byte2DArray&#x5B;];       \/\/ Ugly\nlong&#x5B;] long2DArray&#x5B;];\n<\/pre>\n<p>And these are some examples of illegal declarations &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;5] intArray;       \/\/ Don't mention size!\ndouble{} doubleArray;  \/\/ Square Brackets please!\n<\/pre>\n<h3>Instantiation<\/h3>\n<p>This is how we &#8220;instantiate&#8221;, or allocate memory for an array &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] array = new int&#x5B;5];\n<\/pre>\n<p>When the JVM encounters the <b><span style=\"font-family:Consolas;color:blue;\">new<\/span><\/b> keyword, it understands that it must allocate memory for something. And by specifying <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[5]<\/span><\/b>, we mean that we want an array of <b><span style=\"font-family:Consolas;color:blue;\">int<\/span><\/b>s, of size 5.<br \/>\nSo, the JVM creates the memory and assigns the reference of the newly allocated memory to <b><span style=\"font-family:Consolas;\">array<\/span><\/b> which a &#8220;reference&#8221; of type <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b>. Bit confusing isn&#8217;t it..? We can understand it better if we put the JVM&#8217;s job in a step-by-step process, but you&#8217;ll have to get used to the terminology &#8211;<\/p>\n<ol>\n<li>We create a <strong>reference<\/strong> of type <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b>, or, vaguely, we create a reference to an array of integers. The syntax is &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] array;\n<\/pre>\n<\/li>\n<li>Then, we allocate the memory, or, create an <strong>object<\/strong> of type <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b>, or, we create an object of an array. In this step, we mention the size of the dimensions &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] array = new int&#x5B;5];\nint&#x5B;]&#x5B;] bigArray = new int&#x5B;5]&#x5B;5];\n<\/pre>\n<\/li>\n<li>Now, the JVM allocates the required memory an assigns the address of the newly allocated memory to the reference variable, or, <strong>object reference<\/strong>, the array variable. The array is initialized to the default value of the data type.<\/li>\n<\/ol>\n<p>Let&#8217;s write a super simple code to practise the things we learnt so far. This program computes and stores the first 100 Fibonacci numbers &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class SimpleFib {\n\n    public static void main(String&#x5B;] args) {\n        int&#x5B;] fib;              \/\/ Declaration\n        fib = new int&#x5B;100];     \/\/ Instantiation\n\n        fib&#x5B;0] = 1;\n        fib&#x5B;1] = 1;\n\n        for (int i = 2; i &lt; 100; ++i) {\n            fib&#x5B;i] = fib&#x5B;i - 1] + fib&#x5B;i - 2];\n        }\n    }\n\n}\n<\/pre>\n<h4><strong>Note<\/strong><\/h4>\n<p>Arrays in Java always know their sizes. The size of an array is available to you as the length property. You can use the dot operator &#8216;.&#8217; on the object reference to access the <strong><span style=\"font-family:Consolas;\">length<\/span><\/strong> property. So, we can re-write the <span style=\"font-family:Consolas;\"><strong>SimpleFib<\/strong><\/span> class using this feature &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class SimpleFib {\n\n    public static void main(String&#x5B;] args) {\n        int&#x5B;] fib;              \/\/ Declaration\n        fib = new int&#x5B;100];     \/\/ Instantiation\n\n        fib&#x5B;0] = 1;\n        fib&#x5B;1] = 1;\n\n        for (int i = 2; i &lt; fib.length; ++i) {\n            fib&#x5B;i] = fib&#x5B;i - 1] + fib&#x5B;i - 2];\n        }\n    }\n\n}\n<\/pre>\n<p>This is a more robust and maintenance free way of writing arrays with loops. This is a good practice and is recommended by many experienced programmers.<\/p>\n<h3>Initialization<\/h3>\n<ol>\n<li><strong>Using a Loop<\/strong> &#8211; Using a for loop to initialize elements of an array is the most common way to get the array going. There&#8217;s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.<\/li>\n<li><strong>All in One..!<\/strong> &#8211; We can Declare, Instantiate and Initialize our array in one go. Here&#8217;s the syntax &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = {1, 2, 3, 4, 5};\n<\/pre>\n<p>C programmers shouldn&#8217;t feel too weird about this syntax. Here, we don&#8217;t mention the size, because JVM can see that we are giving 5 values, so it says, &#8220;I&#8217;m not that dumb..!! \ud83d\ude1b &#8221; &#8230; So the JVM does these bunch of things when it encounters such a statement &#8211;<\/p>\n<ul>\n<li>Creates a variable named <b><span style=\"font-family:Consolas;\">arr<\/span><\/b> of type <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b>, that is, it becomes an array object reference variable.<\/li>\n<li>Constructs an array object, or Instantiates, an <b><span style=\"font-family:Consolas;color:blue;\">int<\/span><\/b> array of size 5.<\/li>\n<li>Fills the newly constructed array with 1, 2, 3, 4, 5.<\/li>\n<li>Assigns this array object to the array object reference variable, <b><span style=\"font-family:Consolas;\">arr<\/span><\/b>. A low level note&#8230;. It assigns the bit pattern corresponding to the memory allocated to the array. Well, you needn&#8217;t be too concerned about it. \ud83d\ude09<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<h3>Anonymous Array<\/h3>\n<p>There is another &#8220;All in one..!&#8221; syntax to create arrays which is often called as an <strong>Anonymous Array<\/strong>. The syntax is &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = new int&#x5B;] {1, 2, 3, 4, 5};\n<\/pre>\n<p>Uh&#8230; What is this thing..? It looks like we added an additional &#8220;<b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">new int<\/span>[]<\/span><\/b>&#8221; to our previous version of &#8220;All in one..!&#8221; syntax. And we also know that the statement works fine even without that additional decoration.<br \/>\nThen why bother about this syntax at all..? This is handy in creating just-in-time arrays. Such requirement commonly arises when we are supposed to pass ever-changing values to a very frequently used function. Let&#8217;s assume you have a function that searches for some names in your phonebook and returns true if all the names were present. It would look like this &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class AnonymousArray {\n\n    public static void main(String&#x5B;] args) {\n       IsThere(new String&#x5B;] {&quot;Bill Gates&quot;, &quot;Steve Jobs&quot;});\n       IsThere(new String&#x5B;] {&quot;James Gosling&quot;, &quot;Ritchie&quot;});\n       IsThere(new String&#x5B;] {&quot;Emma Watson&quot;, &quot;Emma Stone&quot;});\n    }\n\n    static boolean IsThere(String&#x5B;] names) {\n        \/\/ Do some searching on something\n        return true;    \/\/ if found, else false\n    }\n\n}\n<\/pre>\n<p>As you can see, you are frequently searching for names in your phonebook. Sometimes millionaires, or fathers of programming languages, or sometimes gorgeous actresses..! And based on whether the method returns true or false, you would like to take some action.<br \/>\nSo, why exactly is Anonymous Arrays handy here..? Imagine you used the regular array syntax for the program &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class RegularArray {\n\n    public static void main(String&#x5B;] args) {\n        String&#x5B;] millnrs = {&quot;Bill Gates&quot;, &quot;Steve Jobs&quot;};\n        String&#x5B;] fathers = {&quot;James Gosling&quot;, &quot;Ritchie&quot;};\n        String&#x5B;] actresses = {&quot;Emma Watson&quot;, &quot;Emma Stone&quot;};\n\n        IsThere(millnrs);\n        IsThere(fathers);\n        IsThere(actresses);\n    }\n\n    static boolean IsThere(String&#x5B;] names) {\n        \/\/ Do some searching on something\n        return true;    \/\/ if found, else false\n    }\n\n}\n<\/pre>\n<p>Notice anything..? Well, it was just 3 arrays, so you may not notice anything. But imagine if you are creating a hundred such arrays..! They would all be lying in the memory with no purpose at all..! Plus&#8230; You&#8217;ll simply run out of names for the variables to create..! So, these two are the advantages of Anonymous Arrays in Java &#8211;<\/p>\n<ul>\n<li>They don&#8217;t lie in the memory&#8230; Well, there are a special cases where they can. But generally using Anonymous Arrays for just-in-time requirements is a tidy business.<\/li>\n<li>You don&#8217;t have to remember a lot names..! That is why they are called &#8220;anonymous&#8221;..!<\/li>\n<\/ul>\n<h3>Multidimensional Arrays in Java<\/h3>\n<p>Java treats multidimensional arrays literally as an &#8220;Array of Arrays&#8221;. You may not know what&#8217;s the little surprise behind that statement&#8230; So watch closely..!<br \/>\nThese are some regular legal declarations for 2D arrays in Java &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;]&#x5B;] arr2by2 = new int&#x5B;2]&#x5B;2];\nbyte&#x5B;]&#x5B;] arr2by3 = new byte&#x5B;2]&#x5B;3];\nshort&#x5B;]&#x5B;] arr0by2 = new short&#x5B;0]&#x5B;2];\n<\/pre>\n<p>We all know how those arrays would look in the memory. Now, have a look at this two-dimensional array &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;]&#x5B;] arr = new int&#x5B;2]&#x5B;];\n\narr&#x5B;0] = new int&#x5B;2];\narr&#x5B;1] = new int&#x5B;3];\n<\/pre>\n<p>Well&#8230; You didn&#8217;t expect this did you..? \ud83d\ude1b &#8230; This is a really different way of creating a 2D array. In the memory, it would look like &#8211;<br \/>\n<a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1369\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?resize=676%2C468&#038;ssl=1\" alt=\"two-dimensional-array-in-java\" width=\"676\" height=\"468\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?w=670&amp;ssl=1 670w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?resize=300%2C208&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?resize=230%2C159&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?resize=350%2C242&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2015\/06\/two-dimensional-array-in-java-e1437328955885.png?resize=480%2C332&amp;ssl=1 480w\" sizes=\"auto, (max-width: 676px) 100vw, 676px\" data-recalc-dims=\"1\" \/><\/a><br \/>\nYou see how the array reference thing works..? The data types of the variables are shown by dotted arrows. The elements <span style=\"font-family:Consolas;\"><strong>arr[0]<\/strong><\/span> and <span style=\"font-family:Consolas;\"><strong>arr[1]<\/strong><\/span> become independent array references which can point to an array of any size. Hence, they point to different array objects which have arrays of different sizes. Important points to take away from the diagram are &#8211;<\/p>\n<ul>\n<li>Array Objects (the oval shapes on the Heap) are created on the heap.<\/li>\n<li>Array Object references of a particular dimension can point to an array object of the same dimension.Hence the following code is invalid &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;]&#x5B;] arr = new int&#x5B;2]&#x5B;];\n\narr&#x5B;0] = new int&#x5B;2]&#x5B;3];\narr&#x5B;1] = new int&#x5B;3]&#x5B;4]&#x5B;5];\n<\/pre>\n<\/li>\n<\/ul>\n<h3>Methods in Arrays Class<\/h3>\n<p>There are a lot of predefined methods in the <span style=\"font-family:Consolas;\">Arrays<\/span> class absolutely ready to use..! In most of these methods, we must make sure that the objects are <span style=\"font-family:Consolas;\">Comparable<\/span>. A word of caution..! It is the &#8220;<span style=\"font-family:Consolas;\">Arrays<\/span>&#8221; Class, not &#8220;<span style=\"font-family:Consolas;\">Array<\/span>&#8221; Class&#8230; Be careful because there is an &#8220;<span style=\"font-family:Consolas;\">Array<\/span>&#8221; Class.<\/p>\n<table style=\"height:1309px;\" width=\"845\">\n<colgroup>\n<col style=\"width:150px;\" \/>\n<col style=\"width:225px;\" \/><\/colgroup>\n<tbody>\n<tr>\n<th>Method Signature<\/th>\n<th>Short Description<\/th>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.sort(<span style=\"color:blue;\">int<\/span>[] array)<\/span><\/td>\n<td>Sorts the elements of the array in ascending order using Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. Has an good performance of O(N log N).<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.sort(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> fromIndex, <span style=\"color:blue;\">int<\/span> toIndex)<\/span><\/td>\n<td>Sorts the elements of the array in the range [fromIndex, toIndex) into ascending order. Uses \u00a0the same Dual-Pivot Quicksort algorithm.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.binarySearch(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> key)<\/span><\/td>\n<td>Uses Binary Search algorithm to search for a key in the given array. Returns the index of the element if found, otherwise returns the index of the first element greater than the key. The array must be sorted in ascending order.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.binarySearch(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> fromIndex, <span style=\"color:blue;\">int<\/span> toIndex, <span style=\"color:blue;\">int<\/span> key)<\/span><\/td>\n<td>Uses Binary Search algorithm to search for a <em>key<\/em> in the given array in the range [<em>fromIndex<\/em>, <em>toIndex<\/em>). Has the same exact return values and requirements as the above version.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.copyOf(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> newLength)<\/span><\/td>\n<td>Returns a new Array which has the same elements as in the actual parameter array up to where the index is <em>newLength<\/em>. If <em>newlength<\/em> &gt; array.<em>length<\/em>, then the extra elements are set to the default value of the respective data type.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.copyOfRange(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> fromIndex, <span style=\"color:blue;\">int<\/span> toIndex)<\/span><\/td>\n<td>Returns a new Array which has the same elements as in the actual parameter array, where index of the element in the parameter array is in the range [<em>fromIndex<\/em>, <em>toIndex<\/em>).<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.equals(<span style=\"color:blue;\">int<\/span>[] array1, <span style=\"color:blue;\">int<\/span>[] array2)<\/span><\/td>\n<td>Returns true if both the arrays have the same elements in the same order.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.fill(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> value)<\/span><\/td>\n<td>Assigns <em>value<\/em> to all the elements of <em>array<\/em>.<\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-family:Consolas;\">Arrays.fill(<span style=\"color:blue;\">int<\/span>[] array, <span style=\"color:blue;\">int<\/span> fromIndex, <span style=\"color:blue;\">int<\/span> toIndex, <span style=\"color:blue;\">int<\/span> value)<\/span><\/td>\n<td>Assigns <em>value<\/em> to all the elements of <em>array<\/em> in the range [<em>fromIndex<\/em>, <em>toIndex<\/em>).<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>All these methods have overloaded versions to support all the primitive data types. To all those who don&#8217;t know overloading.. It means that you can use arrays of other data types with these functions&#8230; We will discuss overloading very soon..!<\/p>\n<h3>Some Pitfalls when using Arrays in Java<\/h3>\n<ol>\n<li><strong>Assigning One-Dimensional Arrays<\/strong> &#8211; We all know that JVM does a lot of automatic type conversion for us in the case of expressions involving variables of different numeric data types. Just a brief reminder that Java employs widening type conversion. Now, how about assigning a <b><span style=\"font-family:Consolas;color:blue;\">short<\/span><\/b> array object to an <b><span style=\"font-family:Consolas;color:blue;\">int<\/span><\/b> array object..?\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nshort&#x5B;] shortArray = new short&#x5B;10];\nint&#x5B;] intArray = new int&#x5B;5];\n\nintArray = shortArray;\n<\/pre>\n<p>Well it seems to be fine.. But this gives a compilation error of &#8220;Incompatible Types&#8221;. The problem here isn&#8217;t that the sizes are different, but the issue is that a reference of type <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b> can point to an object of <b><span style=\"font-family:Consolas;\"><span style=\"color:blue;\">int<\/span>[]<\/span><\/b>, that is, an integer array, not any other.<\/li>\n<li><strong>Assigning Two-Dimensional Arrays<\/strong> &#8211; The dimension of array, an array object reference can point to is fixed at the time of declaration and we cannot violate it. So, this code gives a compilation error &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;]&#x5B;] arr1 = new int&#x5B;2]&#x5B;];\nint&#x5B;]&#x5B;] arr2 = new int&#x5B;3]&#x5B;2];\n\narr1&#x5B;0] = arr2;\n<\/pre>\n<\/li>\n<li><strong>Array Size<\/strong> &#8211; There&#8217;s a small tricky thing with the array size. We generally don&#8217;t mess up this area, but it never harms to know. These are some legal array declarations &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = new int&#x5B;0];\nint&#x5B;]&#x5B;] arr = new int&#x5B;0]&#x5B;2];\n<\/pre>\n<p>Well, there&#8217;s nothing new&#8230; Even the GCC compiler wouldn&#8217;t bother about these pointless arrays. But, this is a legal array declaration in Java &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nshort&#x5B;] shortArray = new short&#x5B;-1];\n<\/pre>\n<p>Yes, it is legal&#8230; Legal, in the sense that the compiler won&#8217;t complaint&#8230; But you do get a runtime error saying, &#8220;NegativeArraySizeException&#8221;. The same thing in C would give a compilation error..!<\/li>\n<\/ol>\n<h3>Summary<\/h3>\n<ul>\n<li>This is how we declare and allocate memory (instantiate) for an array in Java &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] array = new int&#x5B;5];\nint&#x5B;]&#x5B;] bigArray = new int&#x5B;5]&#x5B;5];\n<\/pre>\n<\/li>\n<li>The array elements are always initialized to the data type&#8217;s default value.<\/li>\n<li>We can give our own initialization by &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = new int&#x5B;] {1, 2, 3, 4, 5};\n<\/pre>\n<\/li>\n<li>Arrays in Java always know their sizes. Every array object has a <em>length<\/em> attribute which is accessed by the dot operator &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = new int&#x5B;5];\nSystem.out.println(arr.length);    \/\/ 5\n<\/pre>\n<\/li>\n<li>We can create an anonymous array to implement some just-in-time logic by the syntax &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nfunction(new int&#x5B;] {1, 2, 3, 4, 5});\n<\/pre>\n<\/li>\n<li>Each element of a multidimensional array is an independant array reference. So, they can hold arrays of different sizes &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;]&#x5B;] arr = new int&#x5B;2]&#x5B;];\n\narr&#x5B;0] = new int&#x5B;2];\narr&#x5B;1] = new int&#x5B;3];\n<\/pre>\n<\/li>\n<li>The Arrays Class provides many useful methods to perform the regular operations on arrays easily and efficiently.<\/li>\n<li>Even though Java employs widening type conversion between compatible data types, the following gives a compilation error &#8211;\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nshort&#x5B;] shortArray = new short&#x5B;10];\nint&#x5B;] intArray = new int&#x5B;5];\n\nintArray = shortArray;\n<\/pre>\n<\/li>\n<\/ul>\n<h3>Practise<\/h3>\n<ul>\n<li>Can you guess the output of this program..?\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class ArraySizes {\n\n    public static void main(String&#x5B;] args) {\n        int&#x5B;]&#x5B;]&#x5B;] array1 = new int&#x5B;1]&#x5B;3]&#x5B;5];\n        int&#x5B;]&#x5B;]&#x5B;]&#x5B;] array2 = new int&#x5B;2]&#x5B;1]&#x5B;0]&#x5B;1];\n\n        System.out.println(array1.length);\n        System.out.println(array1&#x5B;0].length);\n        System.out.println(array1&#x5B;0]&#x5B;1].length);\n\n        System.out.println();\n\n        System.out.println(array2.length);\n        System.out.println(array2&#x5B;1].length);\n        System.out.println(array2&#x5B;1]&#x5B;0].length);\n\n        System.out.println();\n\n        String&#x5B;]&#x5B;]&#x5B;] str = new String&#x5B;2]&#x5B;]&#x5B;];\n\n        System.out.println(str.length);\n        System.out.println(str&#x5B;1]);\n    }\n\n}\n<\/pre>\n<p>Don&#8217;t run it&#8230;! \ud83d\ude1b<\/li>\n<\/ul>\n<p>This is all you need to know about arrays in Java to start writing programs of fairly good amount of complexity. I hope it helped you. If you have anything to ask about this topic, feel free to comment..! Keep practising..! Happy Coding..! \ud83d\ude00<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello people..! This is a new post in Java Tutorials \u2013 Arrays in Java. In this post I will talk about about [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[9],"tags":[21,67],"class_list":["post-1347","post","type-post","status-publish","format-standard","hentry","category-java","tag-arrays-in-java","tag-java-tutorials"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/1347","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/comments?post=1347"}],"version-history":[{"count":0,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/1347\/revisions"}],"wp:attachment":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/media?parent=1347"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/categories?post=1347"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/tags?post=1347"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}