Tuesday, February 5, 2019

Java tutorial: Arrays

References/Links: http://pasted.co/5b178ec6

Chapters

Hello everybody! This is brainy ghosts and today we're gonna discuss java arrays. Array is a container object that holds a fixed number of values of a single type. The length of an array is established when it is created. After creation, its length is fixed. Arrays are also objects in java so they can be initialized using the new keyword.

Creating an Array

Create a source file in our workspace folder and name it "JavaArrays" then write the basic code structure.
public class JavaArrays
{
   public static void main(String[]args)
   {
  
  
   }
}
Alright! let's declare an array.
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[5]; 
   }
 
}
When declaring an array variable, Putting the "[]" after the variable name is legal.
int intArr[] = new int[5];

Let's examine the array syntax. first, the data type which is int, then the brackets to indicate that this variable is going to be an array reference variable, variable name, then assignment operator, new keyword and the data type and brackets again, but this time, we put a number between the brackets, this number is the size of our array.

To declare an array and initialize its values, we can use this syntax.
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[]{1,2,3};
     //alternative way
     //int[] intArr = {1,2,3};
     System.out.println(intArr[0]);
     System.out.println(intArr[1]);
     System.out.println(intArr[2]);
   }
 
}
In this code: new int[]{1,2,3} we used braces to group the array values and comma to separate them. The size of intArr now depends on the number of values that we put in braces, separated by commas. This initialization using braces is called array initializer.

The length Attribute

To know the length of an array we can use the length attribute. length attribute returns the length of an array.
syntax: array-name.length;
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[3];
     int[][] intArr2 = new int[5][3];
     System.out.println("intArr length is " + intArr.length);
     System.out.println("intArr2 length is " + intArr2.length);
     System.out.println("intArr2[0] length is " + intArr2[0].length);
   }
}
intArr2 is a two-dimensional array. We will learn two-dimensional array later.

ArrayOutOfBoundsException

Be careful when handling array index, if we access an index that is out of range, it may be greater than the length of an array or less than 0, we will encounter an exception called "ArrayOutOfBoundsException".
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[3];
  
     intArr[3] = 5; //error
     //intArr[-1] = 3; //error
   }
 
}
When we run this code, we will encounter ArrayOutOfBoundsException, but why? In this example this code: intArr[3] exceeds the length of our array. Our array length is 3, so, our array index is ranging from 0 to 2, but we put 3 as our index in intArr that's why the error will occur.

Now we know when we access an index that is greater than the range of an array, ArrayOutOfBoundsException will occur. Now, comment this code: intArr[3] = 5; and uncomment this code: intArr[-1] = 3; then compile it.

As you can see, we encountered ArrayOutOfBoundsException. We got the exception because -1 is less than 0 and it's consider as out of range. Also, ArrayOutOfBoundsException is a runtime exception, it means that this exception happens when our program runs. We will learn more about runtime exception in exception handling topic.

Adding and Accessing Array Elements

To add elements into an array we need to access an array index.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[3];
  
     intArr[0] = 2;
     intArr[1] = 4;
     intArr[2] = 6;
   }
 
}
In this example, this syntax: intArr[0] grants us an access to intArr index. The number in between brackets is the index number. Another fast way to fill an array is to use loop statement like for loop statement.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[] intArr = new int[3];
  
     for(int i = 0; i < intArr.length;i++)
     {
       intArr[i] = i + 2;
       System.out.println(intArr[i]);
     }
   }
 
}
We will learn more about loops in future tutorials. All we need to know for now is this code entirely fills up the array and display the values.

We can transfer an array element to another array element, though there are methods can handle this type of process which we will learn later, It is still better to know how to do it manually.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
       int[] intArr = new int[]{2,4,6};
       int[] intArr2 = new int[]{3,6,9};
       int[] intArr3 = new int[3];
  
       intArr3[0] = intArr[0] * intArr2[0];
       intArr3[1] = intArr[1] * intArr2[1];
       intArr3[2] = intArr[2] * intArr2[2];

       System.out.println(intArr3[0]);
       System.out.println(intArr3[1]);
       System.out.println(intArr3[2]);
   }
 
}
Creating Two-Dimensional Array

The arrays that we were creating recently are called a single-dimensional array. In java, arrays can have multiple dimension, we will just discuss the two and three dimensional array in this example because a four dimensional array and above is very rare to be used in real-life system, even three dimensional array is rare to be seen nowadays.Now, let's create a two-dimensional array.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
       int[][] intArr = new int[2][3];
   }
 
}
On the left operand, we used two pairs of brackets. These two pairs of brackets indicate that intArr is a two-dimensional array reference variable. On the right operand we also used two pairs of brackets, these brackets indicate that new will create a two-dimensional array object.

Multi-dimensional array is an array that is stored in another array. Let's take a look at this illustration.

In this illustration, we see that intArr array stored two arrays with a length of 3. We can depict two-dimensional array as rows and columns. Take a look at this illustration.


Initializing and Accessing Two-Dimensional Array Elements

Let's initialize our array elements by using array initializer.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[][]{{1,2,3},{4,5,6}};
   }
 
}
This code here is the similar to the code above but this time our array elements have been initialized. Take a look at this illustration that depicts our array.


Let's try to initialize array elements one-by-one.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
       int[][] intArr = new int[2][3];
       
       intArr[0][0] = 1;
       intArr[0][1] = 2;
       intArr[0][2] = 3;

       intArr[1][0] = 4;
       intArr[1][1] = 5;
       intArr[1][2] = 6;
   }
 
}
You can refer in the illustration above if this kind of initialization confuses you. This code here and the above code have the same result but with different initialization syntax. Fast way to initialize array elements is to use for loops statement, we will learn how to do that in future tutorials.

Let's access and print array elements. We can use for loop for fast printing of elements, Since we didn't yet discuss for loop statement, we will stay with manual array element access for now.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[][]{{1,2,3},{4,5,6}};

     System.out.println(intArr[0][0]);
     System.out.println(intArr[0][1]);
     System.out.println(intArr[0][2]);

     System.out.println(intArr[1][0]);
     System.out.println(intArr[1][1]);
     System.out.println(intArr[1][2]);
   }
 
}
Creating Three-Dimensional Array

Let's create a three-dimensional array. To create three-dimensional array, we need to increase the pair of brackets in our array initialization to three pairs.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
       int[][][] intArr = new int[2][3][3];
   }
 
}
Judging by the syntax, It looks like three-dimensional array is complex. We can look at this illustration to help reduce the complexity of three-dimensional array.


So, the first layer in this illustration represents first bracket pair( [2][3][3] ). Next, in the second layer there are two dimensional arrays that are stored in an array, these two-dimensional arrays have 3 rows and 3 columns. The second layer represents the second and third bracket pairs( [2][3][3] ).

Initializing and Accessing Three-Dimensional Array Elements

Let's initialize three-dimensional array elements by using array initializer.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][][] intArr = new int[][][]
     { 
       { {1,2} , {3,4} , {5,6} } , 
       { {7,8} , {9,10} , {11,12} }
     };
   }
 
}
Take a look at this illustration that depicts our array above.


Let's try to initialize a three-dimensional array by using its index.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
       int[][][] intArr = new int[2][3][2];

       intArr[0][0][0] = 1;
       intArr[0][0][1] = 2;

       intArr[0][1][0] = 3;
       intArr[0][1][1] = 4;

       intArr[0][2][0] = 5;
       intArr[0][2][1] = 6;


       intArr[1][0][0] = 7;
       intArr[1][0][1] = 8;

       intArr[1][1][0] = 9;
       intArr[1][1][1] = 10;

       intArr[1][2][0] = 11;
       intArr[1][2][1] = 12;

   }
 
}
This code here is equivalent to the code above but the initialization is different. Now, let's access the elements and print them on the console. We will learn how to access array elements using for loop in future tutorial, for now, let's access the elements manually.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][][] intArr = new int[][][]
     { 
       { {1,2} , {3,4} , {5,6} } , 
       { {7,8} , {9,10} , {11,12} }
     };

     System.out.println(intArr[0][0][0]);
     System.out.println(intArr[0][0][1]);

     System.out.println(intArr[0][1][0]);
     System.out.println(intArr[0][1][1]);

     System.out.println(intArr[0][2][0]);
     System.out.println(intArr[0][2][1]);


     System.out.println(intArr[1][0][0]);
     System.out.println(intArr[1][0][1]);

     System.out.println(intArr[1][1][0]);
     System.out.println(intArr[1][1][1]);

     System.out.println(intArr[1][2][0]);
     System.out.println(intArr[1][2][1]);
   }
 
}
Creating Jagged Array

Another form of array is the jagged array, jagged array contains arrays with unequal length. Jagged array is applicable to multi-dimensional array, it is not applicable in single-dimensional array.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[2][];
   }
 
}
in intArr array, we see that the second brackets(column) don't have length. Initializing jagged array is interesting because you can set your own length(column) in each row.

Initializing and Accessing Jagged Array

Let's initialize jagged array elements by using array initializer.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[][]{ {1,2,3,4,5},{6,7,8} };
   }
 
}
In this example, we see that the first and second row element count are unequal. Now, let's try to initialize intArr by using its index.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[2][];
     
     intArr[0] = new int[5];
     intArr[1] = new int[3];
   }
 
}
In this example, we access a multi-dimensional array like a single dimensional array. As I said earlier, multi-dimensional array is an array that stored another array, what we do here is we get the index of intArr array and store another array in that index, thus, making a multi-dimensional array.

Now, let's initialize intArr elements.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[2][];
     
     intArr[0] = new int[5];
     intArr[1] = new int[3];

     intArr[0][0] = 1;
     intArr[0][1] = 2;
     intArr[0][2] = 3;
     intArr[0][3] = 4;
     intArr[0][4] = 5;

     intArr[1][0] = 6;
     intArr[1][1] = 7;
     intArr[1][2] = 8;
   }
 
}
Let's access jagged array elements.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     int[][] intArr = new int[][]{ {1,2,3,4,5},{6,7,8} };

     System.out.println(intArr[0][0]);
     System.out.println(intArr[0][1]);
     System.out.println(intArr[0][2]);
     System.out.println(intArr[0][3]);
     System.out.println(intArr[0][4]);

     System.out.println(intArr[1][0]);
     System.out.println(intArr[1][1]);
     System.out.println(intArr[1][2]);
   }
 
}
The System.arraycopy() Method

Now, let's discuss some pre-defined methods in java that can help us in our array operations. Let's start with System.arraycopy(), this method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument.
Code:
public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[] sourceArr = new char[]{'B','r','a','i','n','y',
  'G','h','o','s','t','s'};
     char[] destArr = new char[6];
     System.arraycopy(sourceArr,0,destArr,0,6);
     
     for(int i = 0; i < destArr.length;i++) 
        System.out.print(destArr[i] + " ");
   }
 
}
Result
B r a i n y
Let's examine the arraycopy method parameters. Method parameters are values in method definition parentheses. Method definition is a body of a method. Method call is a statement that can be executed.

This syntax: System.arraycopy(sourceArr,0,destArr,0,6); is an example of method call. The values in method call are called method argument. We will learn more about methods in future tutorials, we just need to learn a bit of knowledge about methods for now.

Now, let's examine the arraycopy parameters. These are the parameters of arraycopy according to java documentation.

arraycopy​(Object src, int srcPos, Object dest, int destPos, int length);

So, the first parameter is src or source, this source is an array with elements that we want to copy. Notice that the type of src and dest are Object, that's because array is an Object type.

Next parameter is the srcPos or the source index position. This parameter sets the index position where the method starts copying. I set it to 0 because I want arraycopy() to start copying at index 0 from the source.

Next parameter is the dest or the destination. Elements that we want to copy will be stored to this parameter.

Next parameter is the destPos or destination position. This parameter sets the index position where the method starts allocating copied data. I set it to 0, So, arraycopy() starts allocating elements at index 0 from the destination.

Last parameter is the length. This argument is the length of elements that we want to copy.

Let's try another example.
Code:

public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[] sourceArr = 
     new char[]{'B','r','a','i','n','y',
                'G','h','o','s','t','s'};
     char[] destArr = new char[5];
     System.arraycopy(sourceArr,6,destArr,0,5);
     
     System.out.println(new String(destArr));
   }
 
}
Result
G h o s t
Notice this syntax: System.out.println(new String(destArr)); As you can see we create an instance of String without assigning it to a variable. This kind of instance is called anonymous object instance. Anonymous object instance is an instantiated object that is not assigned to any variable. Anonymous object instance is created and dies after.

Let's try using arraycopy() on a multi-dimensional array.
Code:

public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[][] sourceArr = 
     new char[][]{{'B','r','a','i','n','y'},
                  {'G','h','o','s','t','s'}};
     char[][] destArr = new char[2][];
     System.arraycopy(sourceArr,0,destArr,0,2);
     
     System.out.print("Source");
     System.out.println();
     System.out.print(new String(sourceArr[0]));
     System.out.print(" ");
     System.out.print(new String(sourceArr[1]));
     System.out.println();
     System.out.println();
     System.out.print("Destination");
     System.out.println();
     System.out.print(new String(destArr[0]));
     System.out.print(" ");
     System.out.print(new String(destArr[1]));
   }
 
}
Result
Source
Brainy Ghosts

Destination
Brainy Ghosts
In this example, we used arraycopy() to copy an array object to another array. We see here that arraycopy() can also be used in array type.

The Arrays.copyOfRange() Method

copyOfRange() method is located at java.util.Arrays class. This method is like the arraycopy() method but this time we don't need to initialize the destination array because copyOfRange() returns an array containing the specified elements from the original array.

These are the parameters of copyOfRange() according to java documentation.

copyOfRange​(char[] original, int from, int to);

Parameters:

original - the array from which a range is to be copied

from - the initial index of the range to be copied, inclusive

to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)

Take note of the terms inclusive and exclusive. These terms are going to be significant in our discussion later. copyOfRange() method has many forms and since I'll use char in later example, I chose the form of copyOfRange() with char[] data type in first parameter. We will learn method overloading in future topics.

Let's create an example using copyOfRange() method
Code:

public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[] sourceArr = 
     new char[]{'B','r','a','i','n','y',
                'G','h','o','s','t','s'};
     char[] destArr = 
     java.util.Arrays.copyOfRange(sourceArr,1,6);
     
     System.out.println(new String(destArr));
     
     //Legal syntax of accessing array object
     //while it's being returned by a method
     System.out.println(
     java.util.Arrays.copyOfRange(sourceArr,1,6)[0]);
   }
 
}
Result
r a i n y
In this example, we assigned copyOfRange() in destArr then we put the sourceArr in the first argument. Then, we put 1 as our initial index position then put 6 as our final index position. Now, let's talk about the inclusive and exclusive.

Inclusive simply means "included", in this case, we say that index "1" is included in copyOfRange() range so our initial index position is 1.

Exclusive simply means "excluded", in this case, we say that index "6" is excluded in copyOfRange() range so our final index position is the index that precedes 6 which is 5.

So, In this example, the copyOfRange() range is from index 1 to index 5.

Let's try to use copyOfRange() on multi-dimensional array.
Code:

public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[][] sourceArr = 
     new char[][]{{'B','r','a','i','n','y'},
                  {'G','h','o','s','t','s'}};
     char[][] destArr = 
     java.util.Arrays.copyOfRange(sourceArr,0,2);
     
     System.out.print("Source");
     System.out.println();
     System.out.print(new String(sourceArr[0]));
     System.out.print(" ");
     System.out.print(new String(sourceArr[1]));
     System.out.println();
     System.out.println();
     System.out.print("Destination");
     System.out.println();
     System.out.print(new String(destArr[0]));
     System.out.print(" ");
     System.out.print(new String(destArr[1]));
     
   }
}
In this example, we used copyOfRange() to copy an array object to another array. We see here that copyOfRange() can also be used in array type.

The Arrays.sort() Method

Next is the Arrays.sort(), to sort an array we can use the sort() method in java.util.Arrays class.
Code:

public class JavaArrays
{
 
   public static void main(String[]args)
   {
     char[] charArr = 
     new char[]{'g','b','e','l','i','c',
                'j','d','f','h','k','a'};
     java.util.Arrays.sort(charArr);
     
     System.out.println(new String(charArr));
   }
 
}
Result
abcdefghijkl
Why Should We Use Java Pre-Defined Methods

All of the pre-defined methods that we discussed here can be manually created. But, it's better to use the pre-defined methods instead of creating your own version of pre-defined methods, because first, it's already there, second, pre-defined methods are optimized for the task they can do and lastly, reinventing the method or mostly called "reinventing the wheel" is a tedious task if you ask me. It's good to create own version of pre-defined methods if you are doing it for additional knowledge, for fun or you're an expert that wants to improve the language.

Multi-Dimensional Array Performance Overhead

multidimensional arrays have performance overhead than the one dimensional array so if one dimensional array is enough for your program use one dimensional array if not then use a multidimensional or use some alternative like using different data structures like using arraylist in conjunction with hashmap to achieve 2d array like structure.

No comments:

Post a Comment