15 Java Fundamentals | Arrays in Java | By Dummy for Dummies
INTRODUCTION
Imagine you have money, you put the money in a wallet. It is like putting data in a variable. Now if you have a lot of wallets (definitely not stolen), and you put them all in a bag. That will be like putting all variables in another variable. That is exactly what Arrays are, variable of variables
ARRAYS
In array the all the data you store must have same datatype. Here is the magical spell to create an array:
int[] numbers = new int[5];
Let's break down the java spell into our human language...
int → It tells the program about the datatype of array we want to create. Just like we did in making of simple variables.
[] → It tells the program that the datatype is actually Array of Integers rather than just variable of integer.
new int[5] → Think of it as just another magical spell you don't need to explore more right now. Just the datatype must match with what we want to create. The important thing here is the number inside square brackets [5] . It tells the program number of data the array will keep. It is also called length of the array.
The array is now created but it is actually empty. It's length is 5 which means it can store 5 variables or data inside itself. Each data has a specific index, think of index as roll number. But instead of 1, roll numbers in Arrays start from 0.
Therefore this array we created can store 5 variables, and their roll numbers will be 0,1,2,3 and 4. We cannot print the whole array at once like other variables, we must access each data specifically through their index(roll no). It will be like numbers[index] . Replace the index with roll number you want to access.
Let's write a small code in which we will be creating Array and filling it with data, and accessing each step by step
CODE:
OUTPUT:
DIRECT INITIALIZATION & PRINTING USING LOOP
Instead of creating empty array and then putting data we can put data directly into the array. Here is the java magical spell for that:
int[] numbers = {10, 20, 30, 40, 50};
Here we just write the data directly without telling any size for it. But it isn't that much useful since most of the time we require flexible code rather hard coded data. Still you should know about their existence.
We can print the data inside Array using a for loop rather than printing data on each index manually. In that case we will start from the first index and reach last index using for loop. For this program you can just start from 1 and end it before 6, but we have a more flexible method.
Why not we somehow know the exact length of any array and stop at the last index (length - 1). Fortunately we can know the length through arrayName.length and make use of it. Here is a demonstraton:
OUTPUT:
UPDATING DATA IN ARRAYS
We can even update the data inside arrays just like we replace in variables. You can either access each data using a for loop and update them or change data on just a specific index.
CODE:
OUTPUT:
INPUT IN ARRAYS
Just like simple variables we can take input from user inside an array. It can be either on specific index, or on all indexes using for loop.
Let's ask user for length of the array, then start from index 0 and take input in all of them using a for loop.
CODE:
Imagine you have money, you put the money in a wallet. It is like putting data in a variable. Now if you have a lot of wallets (definitely not stolen), and you put them all in a bag. That will be like putting all variables in another variable. That is exactly what Arrays are, variable of variables
ARRAYS
In array the all the data you store must have same datatype. Here is the magical spell to create an array:
int[] numbers = new int[5];
Let's break down the java spell into our human language...
int → It tells the program about the datatype of array we want to create. Just like we did in making of simple variables.
[] → It tells the program that the datatype is actually Array of Integers rather than just variable of integer.
new int[5] → Think of it as just another magical spell you don't need to explore more right now. Just the datatype must match with what we want to create. The important thing here is the number inside square brackets [5] . It tells the program number of data the array will keep. It is also called length of the array.
The array is now created but it is actually empty. It's length is 5 which means it can store 5 variables or data inside itself. Each data has a specific index, think of index as roll number. But instead of 1, roll numbers in Arrays start from 0.
Therefore this array we created can store 5 variables, and their roll numbers will be 0,1,2,3 and 4. We cannot print the whole array at once like other variables, we must access each data specifically through their index(roll no). It will be like numbers[index] . Replace the index with roll number you want to access.
Let's write a small code in which we will be creating Array and filling it with data, and accessing each step by step
CODE:
public class Main {
public static void main(String[] args) {
// 1) Create an array that can store 5 integers (5 wallets in the bag)
int[] numbers = new int[5];
// length tells how many "wallets" we have (roll numbers 0..4)
System.out.println("Array length (roll count): " + numbers.length);
System.out.println();
// 2) Fill the array (put money in each wallet)
numbers[0] = 10; // roll no 0
numbers[1] = 20; // roll no 1
numbers[2] = 30; // roll no 2
numbers[3] = 40; // roll no 3
numbers[4] = 50; // roll no 4
// 3) Access a single element using its index (roll no)
System.out.println("First wallet (index 0) has: " + numbers[0]);
System.out.println("Second wallet (index 1) has: " + numbers[1]);
System.out.println("Third wallet (index 2) has: " + numbers[2]);
System.out.println("Fourth wallet (index 3) has: " + numbers[3]);
System.out.println("Fifth wallet (index 4) has: " + numbers[4]);
}
}
Array length (roll count): 5
First wallet (index 0) has: 10
Second wallet (index 1) has: 20
Third wallet (index 2) has: 30
Fourth wallet (index 3) has: 40
Fifth wallet (index 4) has: 50
DIRECT INITIALIZATION & PRINTING USING LOOP
Instead of creating empty array and then putting data we can put data directly into the array. Here is the java magical spell for that:
int[] numbers = {10, 20, 30, 40, 50};
Here we just write the data directly without telling any size for it. But it isn't that much useful since most of the time we require flexible code rather hard coded data. Still you should know about their existence.
We can print the data inside Array using a for loop rather than printing data on each index manually. In that case we will start from the first index and reach last index using for loop. For this program you can just start from 1 and end it before 6, but we have a more flexible method.
Why not we somehow know the exact length of any array and stop at the last index (length - 1). Fortunately we can know the length through arrayName.length and make use of it. Here is a demonstraton:
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // initialized directly
System.out.println("Printing array using loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + " has: " + numbers[i]);
}
}
}
OUTPUT:
Printing array using loop:
Index 0 has: 10
Index 1 has: 20
Index 2 has: 30
Index 3 has: 40
Index 4 has: 50
UPDATING DATA IN ARRAYS
We can even update the data inside arrays just like we replace in variables. You can either access each data using a for loop and update them or change data on just a specific index.
CODE:
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Before updating
System.out.println("Before updating: ");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + " has: " + numbers[i]);
}
// Update values
numbers[2] = 99; // changing roll no 2 (30 → 99)
numbers[4] = 77; // changing roll no 4 (50 → 77)
// After updating
System.out.println("\nAfter updating: ");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + " has: " + numbers[i]);
}
}
}
OUTPUT:
Before updating:
Index 0 has: 10
Index 1 has: 20
Index 2 has: 30
Index 3 has: 40
Index 4 has: 50
After updating:
Index 0 has: 10
Index 1 has: 20
Index 2 has: 99
Index 3 has: 40
Index 4 has: 77
INPUT IN ARRAYS
Just like simple variables we can take input from user inside an array. It can be either on specific index, or on all indexes using for loop.
Let's ask user for length of the array, then start from index 0 and take input in all of them using a for loop.
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask user for array size
System.out.print("Enter number of elements: ");
int size = sc.nextInt();
// Create array of given size
int[] numbers = new int[size];
// Take input in array
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter number at index " + i + ": ");
numbers[i] = sc.nextInt();
}
// Print the array back
System.out.println("\nYou entered:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + " has: " + numbers[i]);
}
}
}
OUTPUT:
FIND DATA IN AN ARRAY
We can do multiple operations on an array. One of the simplest is finding a data inside an array. For that we will use a for loop to search through all indexes, compare the data with target, we will save the index at which target matches and return it. The variable inside which we will store the index will be given a value "-1", so in case no index match it will remain negative. Since real indexes cannot be negative we can easily know if the data is not found. Here is a demo...
CODE:
OUTPUT (Number is found):
OUTPUT (Number is NOT found):
OTHER OPERATIONS ON ARRAYS
Just like searching for data, we can find largest or smallest data in an array. Also we can find sum or average of the data inside array. There are multiple more operations that can be applied on arrays for different purposes.
Enter number of elements: 3
Enter 3 numbers:
Enter number at index 0: 11
Enter number at index 1: 22
Enter number at index 2: 33
You entered:
Index 0 has: 11
Index 1 has: 22
Index 2 has: 33
FIND DATA IN AN ARRAY
We can do multiple operations on an array. One of the simplest is finding a data inside an array. For that we will use a for loop to search through all indexes, compare the data with target, we will save the index at which target matches and return it. The variable inside which we will store the index will be given a value "-1", so in case no index match it will remain negative. Since real indexes cannot be negative we can easily know if the data is not found. Here is a demo...
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Create and fill the array
int[] numbers = {10, 20, 30, 40, 50};
// Ask user what to search
System.out.print("Enter a number to search: ");
int target = sc.nextInt();
// Search through array
int foundIndex = -1; // assume not found
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
foundIndex = i; // save the roll number
break; // stop searching once found
}
}
// Show result
if (foundIndex != -1) {
System.out.println("Number " + target + " found at index " + foundIndex);
} else {
System.out.println("Number " + target + " not found in array.");
}
}
}
OUTPUT (Number is found):
Enter a number to search: 30
Number 30 found at index 2
OUTPUT (Number is NOT found):
Enter a number to search: 99
Number 99 not found in array.
OTHER OPERATIONS ON ARRAYS
Just like searching for data, we can find largest or smallest data in an array. Also we can find sum or average of the data inside array. There are multiple more operations that can be applied on arrays for different purposes.
EXERCISE
Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.
CODE:
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Ask user for size
System.out.print("Enter size of array: ");
int size = sc.nextInt();
int[] numbers = new int[size];
// Step 2: Take input
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < numbers.length; i++) {
System.out.print("Enter number at index " + i + ": ");
numbers[i] = sc.nextInt();
}
// Step 3: Assume first number is both largest & smallest
int largest = numbers[0];
int smallest = numbers[0];
// Step 4: Check each element
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
// Step 5: Print results
System.out.println("\nLargest number = " + largest);
System.out.println("Smallest number = " + smallest);
sc.close();
}
}
OUTPUT:
Enter size of array: 5
Enter 5 numbers:
Enter number at index 0: 12
Enter number at index 1: 45
Enter number at index 2: 7
Enter number at index 3: 89
Enter number at index 4: 23
Largest number = 89
Smallest number = 7
MINI PROJECT (Monkey’s Banana Weights)
Boss Monkey has collected bananas of different weights. He wants to find out which banana is the heaviest and which one is the lightest. You will create a program that solves this problem using arrays.
Tasks
⦿ Create a class BananaWeights.
⦿ In the main method:
1. Ask the user how many bananas there are.
2. Take input for each banana’s weight and store it in an array.
3. Write logic to find the total and average weight from the array.
4. Print the results neatly.
EXAMPLE OUTPUT:
Enter number of bananas: 5
Enter weight of banana 0: 2
Enter weight of banana 1: 5
Enter weight of banana 2: 3
Enter weight of banana 3: 6
Enter weight of banana 4: 4
Heaviest banana = 6
Lightest banana = 2
Total weight = 20
Average weight = 4.0
CLOSING That's it for Arrays in Java. Arrays like "Variable of variables". Where we can store multiple data of same type and run many operations on it.