Introduction to Arrays

Understanding Arrays through a Story

What is an Array?

In the bustling town of Mysore, there was a famous grocery shop owned by Mr. Verma. Mr. Verma was known for his perfect organization. One day, he decided to teach his young apprentice, Shanav, the secret of his well-organized shop.

Mr. Verma explained to Shanav that an array is like a special shelf where you can store multiple items of the same type in an organized manner. Think of it as a line of baskets, where each basket can hold one item. In Java, arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

How to Declare an Array

To create an array in Java, you need to specify the type of data it will hold and the number of elements it can store. Here’s how you do it:


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = new int[5];
    }
}

This line creates an array that can hold 5 prices of type integer.

Initializing an Array

Once the array is declared, you can initialize it by assigning values to each element using the index positions. The index starts from 0, so the first element is at position 0, the second at position 1, and so on. Let’s put some prices:


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = new int[5];
        
        vegetablePrices[0] = 20;  // Price of the first vegetable
        vegetablePrices[1] = 30;  // Price of the second vegetable
        vegetablePrices[2] = 15;  // Price of the third vegetable
        vegetablePrices[3] = 25;  // Price of the fourth vegetable
        vegetablePrices[4] = 10;  // Price of the fifth vegetable
    }
}

Now, our array is full!

Accessing Array Elements

To see what’s inside each basket (array element), you can access the array by its index:


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        
        System.out.println(vegetablePrices[0]);  // Outputs: 20
        System.out.println(vegetablePrices[1]);  // Outputs: 30
        System.out.println(vegetablePrices[2]);  // Outputs: 15
        System.out.println(vegetablePrices[3]);  // Outputs: 25
        System.out.println(vegetablePrices[4]);  // Outputs: 10
    }
}
Output:

20
30
15
25
10

Benefits of Using Arrays

Arrays help us manage multiple pieces of data efficiently. Instead of declaring multiple variables, you can use a single array to store all related data. This makes your code cleaner and easier to manage.

Operation Performed in Array

In the vibrant town of Mysore, Mr. Verma's grocery shop was always buzzing with activity. Mr. Verma, the wise shop owner, decided to teach Shanav, his dedicated apprentice, the essential operations that can be performed on arrays. Just like organizing his shop, Shanav would learn how to handle arrays efficiently.

Array Insertion

Mr. Verma explained, "Imagine we need to add a new vegetable price to our list of prices. This is called insertion."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int newPrice = 35;
        int[] newVegetablePrices = new int[vegetablePrices.length + 1];
        
        for (int i = 0; i < vegetablePrices.length; i++) {
            newVegetablePrices[i] = vegetablePrices[i];
        }
        newVegetablePrices[vegetablePrices.length] = newPrice;

        for (int price : newVegetablePrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

20 30 15 25 10 35

Array Deletion

"Next," Mr. Verma continued, "sometimes we need to remove a price from our list. This is called deletion."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int indexToRemove = 2;
        int[] newVegetablePrices = new int[vegetablePrices.length - 1];
        
        for (int i = 0, k = 0; i < vegetablePrices.length; i++) {
            if (i == indexToRemove) {
                continue;
            }
            newVegetablePrices[k++] = vegetablePrices[i];
        }

        for (int price : newVegetablePrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

20 30 25 10

Array Search

Mr. Verma smiled and said, "Now, let's say you need to find the price of a particular vegetable. This is called searching."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int searchPrice = 25;
        boolean found = false;
        
        for (int price : vegetablePrices) {
            if (price == searchPrice) {
                found = true;
                break;
            }
        }

        if (found) {
            System.out.println("Price found: " + searchPrice);
        } else {
            System.out.println("Price not found.");
        }
    }
}
Output:

Price found: 25

Array Update

Mr. Verma then said, "Sometimes, we need to update the price of a vegetable. This is called updating."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int indexToUpdate = 3;
        int newPrice = 35;
        
        vegetablePrices[indexToUpdate] = newPrice;

        for (int price : vegetablePrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

20 30 15 35 10

Array Traversal

Mr. Verma concluded, "Finally, sometimes we need to go through all the prices one by one. This is called traversal."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        
        for (int price : vegetablePrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

20 30 15 25 10

Array Merging

Mr. Verma then shared a trick with Shanav, "Sometimes we have two arrays and we need to combine them into one. This is called merging."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] prices1 = {20, 30, 15};
        int[] prices2 = {25, 10, 35};
        
        int[] mergedPrices = new int[prices1.length + prices2.length];
        
        for (int i = 0; i < prices1.length; i++) {
            mergedPrices[i] = prices1[i];
        }
        
        for (int i = 0; i < prices2.length; i++) {
            mergedPrices[prices1.length + i] = prices2[i];
        }

        for (int price : mergedPrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

20 30 15 25 10 35

Finding Maximum Value

"Now," Mr. Verma continued, "let's find the highest price in our list. This is called finding the maximum value."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int maxPrice = vegetablePrices[0];
        
        for (int price : vegetablePrices) {
            if (price > maxPrice) {
                maxPrice = price;
            }
        }

        System.out.println("Maximum price: " + maxPrice);
    }
}
Output:

Maximum price: 30

Finding Minimum Value

"Similarly," Mr. Verma added, "we can find the lowest price. This is called finding the minimum value."


package codeKatha;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        int minPrice = vegetablePrices[0];
        
        for (int price : vegetablePrices) {
            if (price < minPrice) {
                minPrice = price;
            }
        }

        System.out.println("Minimum price: " + minPrice);
    }
}
Output:

Minimum price: 10

Finding Duplicates

Mr. Verma also taught, "Sometimes, we might have duplicate prices in our list. Here's how to find duplicates."


package codeKatha;

import java.util.HashSet;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10, 30, 20};
        HashSet<Integer> seenPrices = new HashSet<>();
        HashSet<Integer> duplicatePrices = new HashSet<>();
        
        for (int price : vegetablePrices) {
            if (!seenPrices.add(price)) {
                duplicatePrices.add(price);
            }
        }

        System.out.println("Duplicate prices: " + duplicatePrices);
    }
}
Output:

Duplicate prices: [20, 30]

Array Sorting

Finally, Mr. Verma said, "Let's learn how to sort our prices in ascending order."


package codeKatha;

import java.util.Arrays;

public class GroceryShop {
    public static void main(String[] args) {
        int[] vegetablePrices = {20, 30, 15, 25, 10};
        
        Arrays.sort(vegetablePrices);

        for (int price : vegetablePrices) {
            System.out.print(price + " ");
        }
    }
}
Output:

10 15 20 25 30

Conclusion

With these advanced lessons from Mr. Verma, Shanav became a master in handling arrays. Arrays are a fundamental concept in Java, and understanding these operations is crucial for managing and manipulating data efficiently. With these skills, you can perform various tasks on arrays in your own programs, just like Shanav in the grocery shop.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring AI with Ollama

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts