Exploring Java : My Learning Adventure, Part - 7

Exploring Java : My Learning Adventure, Part - 7

Java Arrays Explained

In this blog, we will learn what is array, how to access an array in java and for each loop. Array is a collection of similar data elements. In math, it is often referred as set. Array follows index.

One-Dimensional Array

As array is a collection of similar data type, at first we have to declare the type of array, for example int, str. Then we have to give the array a name. The given name acts as a reference in the memory location.

Creating an array :

In Java, every array is an object. Because whatever comes after the reference name becomes an object. And whenever we write new the object appears in the heap. So, every array object in Java is created in heap.

int A[] = new int[2,2,2,3,4];

The elements are stored in a contagious position so we can find their location by indexing. Also, every array object has a length. System.out.println(A.length); , It is not a method, rather length is a property of the array itself. That's why there's no parenthesis after length.

Accessing the elements :

Following the same array example, we can get an element through its index number. For example, System.out.println(A[0]); it'll print out 2. We can repeatedly print out the elements by using for loop.

for (int i = 0; i<A.length ; i++) // less then 5, that is 4.
{
    System.out.println(A[i]);
}
// for reverse printing 
for (int i = A.length - 1;, i>= 0; i--) // as ength is 4, i should start from 4 onwards
{ 
    System.out.println(A[i]); 
}

for-loop is frequently used in arrays for accessing elements. for-each loop is specially for arrays. Let's see for-each loop :

for (int x: A)
{
    System.out.println(x)
}

Previously, we were using i, but now we will write x here. Then, a colon, it means for each x in A. Then I will print. Only writing x will print all the elements. x means every element of the provided array. But, we can't reverse print here.

The difference is, println(A[i]) here i was working as index of an array. But we want array elements, how to say that? A of 1, A of 2, A of 3 - thus we get elements.

But for-each loop's x is taking only the elements. That's it! So this is more user friendly.

Practice :

public class ArrayPractice 
{
    public static void main(String[] args)
        { 
            int A[] = new int[10]; // 1st method 
            int B[] = {1,2,3,4,5}; // 2nd method

            int C[] = []; // 3rd method
            C = new int[20];

            int[] D = new int[10]; // this is also valid
            int []D = new int[10]; // this is also valid   

// i want to change a value from B of index 2, how to do that? 
            B[2] = 15;
// for display all the elements 
            for (int i = 0; i<A.length; i++)
            {
                System.out.println(A[i]); // it will print all zero
                System.out.println(B[i]);
            }
// for=each loop 
            for (int x: B)
            {
                System.put.println(x);
            }
// modifying usinf counter control for loop
            for (int i = 0; i<B.length; i++)
            {
                System.out.println(B[i++]); // output 2,3,16,5,6
            }

for one dimensional array we use sq. brackets. Here A is the reference and new means the object is created in the heap.

printing A will only give zero. Because we have just declared an array. It is not initialized, so by default it will be default. But B will print all the elements 1,2,15,4,5.

for-each loop is only used for reading the elements. But if we want to modify then we have to use the counter control for loop.

Practice Problems

Question 1: Find sum of all elements.

Hint: Suppose, A = {3,9,7,8,12,6,15,5,4,10}. We have to find the sum of all the elements. Scan/ Traverse through the array.

Question 2: Search an element.

Hint: (Only if there are no duplicates) A = {3,9,7,8,12,6,15,5,4,10}. Traverse the array. Target element is 6.

You should also stop if you find your desired array. Another thing is, you don't have to write else. We cannot say element not found before traversing the whole array first and traversing ends with for loop. So, print else outside of the loop saying element is not found

Question 3: Finding the max element

Hint: Again with the same given array, assign a variable max with the first element of your array. Then traverse and put condition.

Question 4: Finding the 2nd max element

Question 5: Rotation of an array.

Hint: Given, A = {3,9,7,8,12,6,15,5,4,10}. Rotating on the left side means shifting all the elements to the left side by one place. Rotation on the right side means shifting all the elements to the right by one place. First element should be removed, keep it to any variable. The shift all the elements one by one and fill the last vacant location with the first element that you had assigned previously to a variable. You have to traverse through the array. You should start from the 1st index in for loop.

Question 6: Inserting an element

Hint: First of all, the array must have vacant places to be able to insert a new element. Shift the elements from the last index. Create an array with 10 locations and add 6 values in the array. I couldn't take the values directly to the array because it would end up taking length of based on the given values but we don't want this. That's why add them separately, a bit pain yes, I know.

Question 7: Copying an array

Two-Dimensional Array

Structure of two dimensional array looks like a matrix. It consists of rows and columns. Syntax: int A[] []= new int [3][4];

The code int A[][] = new int[3][4]; creates a 2D array named A with 3 rows and 4 columns.

new int[3][4] means that the array will have 3 rows (the first dimension) and 4 columns (the second dimension).

The image shows a grid with 3 rows and 4 columns, where each box can hold an integer value

The variable A points to an array of 3 elements (each element is a reference to another array).

Initializing :

int A[3][4] = {{1,2,3,4}, {2,4,6,8}, {3,5,7,9}}

This is 1st row, 2nd row and 3rd row. Each row having four elements.

This is also created in heap. If you use new or not, it does not matter. Array object will be always created in the heap.

for-each loop:

for (int x[]: A) 
{
    for(int y : x)
    {
            System.out.println(y);
    }
    System.out.println("\n");
}

Here, x[] will be taking the references, not the elements. x will be taking reference from the array, y will be taking the values from the array.

for (int x[] : A) : This loop iterates over each row (which is itself an array) in the 2D array A. x represents each row of A.

The 2nd loop iterates over each element in the current row x. y represents each element of the current row. For each iteration, y is assigned one of the elements of the current row x

Practice Problems

Question 1: Adding 2 matrices

Hint : Ofc we will need two for loops, one for the rows and one for the cols. Whenever you are tasked with two matrices, always remember that you are creating a new matric C , and just think how you will get the values from C, forget about A and B. What measurements should you be taken in order to get the right input from C, put it into the loop .

Question 2: Multiplying 2 matrices

Hint: Before multiplying, check if the number of first metric's column is equal to the number of rows of the second matric.

Question 3: Sorting array of strings

That's it for today. In the next blog I will talk about Methods.

Don't forget to stay hydrated. Be sure to practice the tasks.