MT2 - 1D Array
What is an Array?
Imagine you have five exam scores:
85, 92, 76, 88, 95
Normally, you could create five separate variables:
int score1 = 85;
int score2 = 92;
int score3 = 76;
int score4 = 88;
int score5 = 95;
however this is buns. So java gives us arrays to solve this problem
An array lets us store multiple values of the same data type under one variable name.
Instead we can write:
int[] scores = {85,92,76,88,95};
That is an array
Understanding index
Java arrays start at 0 NOT 1
so our indexes for the one above would go from 0 1 2 3 4
So if i write:
System.out.println(scores[0]);
It will print 85
System.out.println(scores[3]);
prints 88
Index is the position, not value
The .length property
How do we figure out how many elements an array contains?
We use:
scores.length
For our example:
System.out.println(scores.length);
Output: 5
Index starts at 0 but length starts from 1
Creating an array without filling it manually
You can also create an empty array with a specific number of spaces:
int[] numbers = new int[5];
This creates 5 integer slots and java automatically initializes them to 0
you can assign values afterwords:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
Now the array looks like
[10, 20, 30, 0, 0]
Traversing an array
Remember how we learned for loops?
We can combine them with arrays to visit every element automatically.
This is called traversing an array.
Suppose we have:
int[] numbers = {10, 20, 30, 40, 50};
We want to print every number.
We could manually write:
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
System.out.println(numbers[3]);
System.out.println(numbers[4]);
but that is inefficient and buns
Instead:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Output:
10
20
30
40
50
Using loops to calculate a sum
Now let's make the loop actually do something useful.
Suppose we have:
int[] numbers = {10, 20, 30, 40, 50};
We want to calculate the total.
First create an accumulator:
int sum = 0;
Accumulator is a variable that keeps the running total
Then:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
Output: 150
Calculate the average
This is practically the same problem:
We already know: Average = Sum / Number of Elements
So:
double average = (double) sum / numbers.length;
Counting elements that meet a condition
Now let's combine arrays with the Boolean conditions we learned earlier.
Suppose:
int[] numbers = {12, 5, 18, 7, 20, 3};
Question: How many numbers greater than 10?
We need a counter
int count = 0;
Then traverse:
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > 10) {
count++;
}
}
Finding minimum and maximum
Suppose we have:
int[] numbers = {8, 3, 12, 5, 2, 9};
We want to find the smallest number
Establish a starting minimum
int min = numbers[0];
Why?
Because we need something to compare the other numbers against.
Initially, we assume 8 is the smallest.
Next we compare eveyr remaining element
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
Notice that we started i at 1 instead of 0 because we already used numbers[0] to initialize min.
Finding maximum
int[] numbers = {8, 3, 12, 5, 2, 9};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++ {
if (numbers[i] > max) {
max = numbers[i];
}
}
Searching through arrays
Goal: Determine whether a particular value exists inside an array.
Suppose we have:
int[] numbers = {12, 5, 18, 7, 20, 3};
We want to know whether the # 18 exists (it does) but how do we do that?
We examine each element until we find the number.
Create a boolean value
boolean found = false;
False because b4 searching, we haven’t found anything
Think of found as a light switch:
false= haven't found it.true= found it.
Traverse the Array
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 18) {
found = true;
}
}
Check result
if (found) {
System.out.println(“Found it!”);
}
else {
System.out.println"(“Not found!”);
Searching with a variable
What if we don't know beforehand which number we're searching for?
We can create a target variable:
int target = 18;
then:
if (numbers[i] == target) {
found = true;
}
This makes our code reusable. We can change target without rewriting the loop.
Filling arrays with random values
Now let's look at another question from your notes.
Suppose we want to create an array containing five random decimal values.
double[] array = new double[5];
This creates 5 slots with all of them being 0.0
Remember Math.random() ? It generates a number from 0<= Math.random() < 1
So we can write;
for (int i = 0; i < array.length; i++) {
array[i] = Math.random();
}
Random integers in a specific range
This is an important formula.
Suppose you want random integers from 1 through 10.
int randomNumber = (int) (Math.random() * 10) + 1)
int randomNum = min + (int)(Math.random() * ((max - min) + starting));
Reversing an Array
Suppose we have:
int[] arr = {1, 2, 3, 4, 5, 6};
we want to reverse it so it becomes:
{6, 5, 4, 3, 2, 1}
The important thing is that we're changing the original array.
Understand Swapping:
To reverse an array, we swap elements on opposite ends.
We need a temporary variable to perform a swap.
For example:
int temp = arr[0];
arr[0] = arr[5];
arr[5] = temp;
Let’s understand this:
temp = arr[0] saves temp as original index 0 (which is one)
arr[0] = arr[5] puts 6 into index 0
arr[5] = temp puts the saved 1 into index 5
Why do we need temp?
Imagine doing this
arr[0] = arr[5];
arr[5] = arr[0];
After the first line, arr[0] is already 6. The second line would copy 6 into index 5 too.
We would lose the original 1, so the temporary variable prevents that
Automate the steps with a loop
for (int i = 0; i < arr.length / 2;i++) {
int temp = arr[i]
arri[i] = arr[arr.length - 1 - i];
arr[arr.length-1-i] = temp;
}
Why arr.length/2?
Because we only need to swap half the array
For 6 elements, 6/2 = 3 so 3 swaps
Why arr.length-1-i?
This calculates the index on the opposite side.
For an array of length 6:
|
| Swap |
|---|---|---|
0 | 5 | Index 0 and 5 |
1 | 4 | Index 1 and 4 |
2 | 3 | Index 2 and 3 |
Copying an array
Suppose
double[] a = {0.3, 0.6, 0.99, 0.01, 0.5};
We want to create another array called b with the exact same values.
A common mistake is writing:
double[] b = a;
This doesn’t create a new independent array but b just refers to a
Here is how to actually copy an array:
double[] b = new double[a.length];
This creates a new b with the same length as a but they are all 0.0
Copy each element:
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
Now b and a have the same values but diff arrays
Array Aliasing (HIGH PRIORITY!!!!!!)
First, let's understand the problem.
Suppose we create an array:
int[] a = {10, 20, 30};
Now we write int[b] = a;
We already know this doesn’t create a separate array containing the values. This is called aliasing, 2 variables refer to the same object
What happens when we modify the array?
int[] a = {10, 20, 30};
int[] b = a;
b[0] = 99;
System.out.println(a[0]);
it prints out 99 because a and b refer to the same array
Compare Aliasing with Copying
Let's compare two situations.
Aliasing:
int[] a = {1, 2, 3};
int[] b = a;
b[1] = 50;
Result:
a = {1, 50, 3}
b = {1, 50, 3}
Copying:
int[] a = {1, 2, 3};
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
b[1] = 50;
Comparing arrays with ==
Here’s a trap
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b);
you’d think this would print true but it’s false as even tho the arrays contain identical values, they are two separate arrays.
Now for:
int[] a = {1, 2, 3};
int[] b = a;
System.out.println(a == b);
This is TRUE because they ARE the same array
Arrays as Method parameters
One more important connection to upcoming methods chapter:
public static void change(int[] numbers) {
numbers[0] = 100;
}
public static void main(String[] args) {
int[] values = {1, 2, 3};
change(values);
System.out.println(values[0]);
}
Output: 100
Why?
The method receives a reference to the same array. Changing an element inside the method changes that original array. We will focus more on this learning bout Methods
Removing elements from an array by shifting
Suppose we have:
int[] arr = {10, 20, 30, 40, 50};
We want to remove the value 30
Here’s the catch: Java arrays have a fixed length so we can’t simply delete an element
Instead, we shift the elements after it one position to the left.
Understand shifting
We want to remove index value 2 (30)
We move everything after index 2 one position to the left.
arr[2] = arr[3]→ 40 moves into index 2.arr[3] = arr[4]→ 50 moves into index 3.
Result:
{10, 20, 40, 50, 50}
There is still a 50 because we didn’t shorten the array but just shifted the values
We need a separate variable to track how many elements are actually being used.
The shifting loop
Suppose the element at index 2 is being removed
for (int i = 2; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
Let’s understand every part
int i = 2: Start at position we removing
i < arr.length - 1: Stop before final index
i++: move one position right
arr[i] = arr[i + 1]: Copy next element into current position
Why i + 1?
Because we're pulling the element from the position immediately to the right.
Why arr.length - 1?
Because we need arr[i + 1] to remain a valid index.
Track the logical size:
In a real removal problem, we'd keep track of the number of valid elements:
int size = arr.length;
After shifting:
size--;
Now size is 4 instead of 5
The array still physically has five slots, but we only consider the first four elements valid.
{10, 20, 40, 50, 50}
↑
Valid elements end here
When printing the shortened array, we'd use:
for (int i = 0; i < size; i++) {
System.out.println(arr[i]);
}
Enhanced for loops
This is another array concept in your practice materials.
Normally, we traverse an array like this:
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Java gives us a shorter version:
for (int number : numbers) {
System.out.println(number);
}
How does it work?
for (int number : numbers)
Read it as:
For every integer called number inside numbers
You don't need:
An index variable.
A condition.
An increment.
Java handles the traversal.
Important limitation
An enhanced for loop is great when you only need to read elements.
But if you need to:
Access a specific index.
Modify elements by index.
Reverse an array.
Shift elements.
Traverse backward.
Trad for loop is better choice
Also, assigning a new value to the enhanced-loop variable does not replace the array element:
for (int number : numbers) {
number = 100;
}
This does NOT turn the array into {100, 100, 100, 100}.