Table of contents
- Why We Need Arrays
- What is an Array?
- How array Works
- Internal Working of Arrays
- Dynamic Memory Allocation
- Internal Representation of Array
- Continuity of an Array
- Index of an Array
- String Array
- What is null in JAVA
- Array Input
- For-Each Loop
- toString Method
- Array passing in Functions
- Multidimensional Array
- Syntax of 2D Array
- Internal Working of 2D Array
- 2D Array Input
- Dynamic Arrays
- Array Functions
- Let’s Do some Questions
- Conclusion
In programming, we often need to store multiple pieces of data. If you wanted to store a list of numbers, names, or objects, you wouldn’t want to create individual variables for each one. That's where arrays and ArrayList come in handy.
Why We Need Arrays
Example: Imagine you run a grocery store and want to keep track of the prices of five products. You wouldn’t want to create five different variables for each price. Instead, you would use an array to group them together, making it easier to manage.
Example:
// Instead of doing this:
int price1 = 50;
int price2 = 30;
int price3 = 40;
// We can group prices in an array
int[] prices = new int[5]; // Array to store 5 prices
What is an Array?
An array is a collection of elements that are stored together. It’s like a box with compartments where you can store multiple items of the same type (like numbers or words).
Syntax of Array
int[] numbers = new int[5]; // Declare an integer array with 5 elements
String[] names = new String[3]; // Declare a string array with 3 elements
How array Works
Example 1
magine you have to store the grades of 3 students:
- Instead of creating 3 separate variables, you can store them in an array.
int[] grades = new int[3]; // Array to store 3 grades
grades[0] = 85; // First student's grade
grades[1] = 90; // Second student's grade
grades[2] = 75; // Third student's grade
// Accessing the grades
System.out.println(grades[1]); // Output: 90
Example 2
A to-do list is a common example. You might want to store 5 tasks to complete for the day:
String[] tasks = {"Buy groceries", "Do laundry", "Finish project", "Call mom", "Clean room"};
System.out.println(tasks[2]); // Output: Finish project
Internal Working of Arrays
Arrays are stored in contiguous blocks of memory. This means all elements are placed next to each other, making access fast and efficient.
Example:
Think of an array like a row of lockers in a hallway. Each locker (element) is in a continuous line, and you can easily walk to any locker based on its position (index).
Dynamic Memory Allocation
When you declare an array, Java allocates memory based on the size of the array. For example, an array of size 5 will reserve enough memory for five elements.
Internal Representation of Array
Arrays are stored as continuous blocks of data in memory, and the memory is allocated based on the array's type (e.g., an array of integers will have more memory per element than an array of characters).
Continuity of an Array
Since arrays are stored in a sequential manner in memory, each element is placed directly after the previous one. This allows for quick access to any element.
Example
Imagine a parking lot where each car is parked in consecutive slots without gaps. You can easily find a car by looking at its slot number.
Index of an Array
In Java, arrays are zero-indexed, which means the first element is at index 0.
Example
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[3]); // Output: 4
String Array
A string array stores multiple strings (words or sentences).
Example :-
If you need to store the names of all students in a class, you would use a string array.
String[] names = {"Alice", "Bob", "Charlie"};
System.out.println(names[1]); // Output: Bob
What is null in JAVA
null
represents an empty or non-existing value. It’s like having an empty slot in an array.
Example
Imagine a shelf with five slots. If one slot is empty, you could say its value is null
.
null
is Used as Default
When you create an array of objects or strings, each element is initialized to null
until you assign a value.
Example
String[] names = new String[3]; // By default, all values are null
System.out.println(names[0]); // Output: null
Array Input
You can take user input to populate an array.
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[3];
for(int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt(); // User inputs numbers
}
For-Each Loop
A for-each loop simplifies array iteration.
int[] numbers = {10, 20, 30};
for (int number : numbers) {
System.out.println(number);
}
toString Method
The Arrays.toString()
method helps you print an array easily.
int[] numbers = {1, 2, 3, 4};
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 4
Array passing in Functions
You can pass arrays as arguments to methods.
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.println(num);
}
}
Multidimensional Array
A multidimensional array is like a grid or table where you can store elements in rows and columns.
Example
A chessboard can be represented as a 2D array where each position is a square on the board.
int[][] chessBoard = new int[8][8]; // 8x8 chessboar
Syntax of 2D Array
int[][] matrix = new int[2][3]; // 2 rows, 3 columns
Internal Working of 2D Array
In a 2D array, the rows and columns are stored as separate arrays within a single array.
2D Array Input
You can take input for a 2D array like this:
Scanner scanner = new Scanner(System.in);
int[][] matrix = new int[2][3];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
matrix[i][j] = scanner.nextInt();
}
}
Dynamic Arrays
Unlike fixed-size arrays, an ArrayList can grow or shrink dynamically.
Example
Think of it as a stretchable bag where you can add or remove items.
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // Adds 10 to the list
list.add(20); // Adds 20 to the list
Array Functions
Java provides functions like Arrays.sort()
and Arrays.copyOf()
to work with arrays.
Internal Working of ArrayList
Internally, ArrayList
uses arrays. When the array is full, it creates a new larger array and copies the elements over.
Let’s Do some Questions
Q1 :- How to swap Values in an Array
You can swap two elements in an array using a temporary variable.
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
Q2 :- Minimum Value of an Array
To find the minimum value in an array:
int min = arr[0];
for(int i = 1; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i];
}
}
System.out.println("Minimum value: " + min);
Q3 :- Reversing an Array
To reverse an array:
for(int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
Conclusion
Arrays and ArrayList are essential tools for managing data in Java. While arrays offer fixed-size storage, ArrayList provides flexibility. Both are useful depending on the situation. By understanding these concepts, you’ll be able to handle data more efficiently in your Java programs.
Now That’s it for this blog in next one we will talk about Linear Search Algorithm in JAVA with lot’s of examples.
Until then Keep Learning, Keep Sharing, Keep Supporting.