CodeGym /Courses /JAVA 25 SELF /Fundamental operations with one-dimensional arrays

Fundamental operations with one-dimensional arrays

JAVA 25 SELF
Level 7, Lesson 2
Available

1. Array of type String

And briefly, I’d like to say a few words about an array of type String.

As we’ve already said, an array can be of any type. Which means you can create an array of type String. Here’s what the code would look like if we needed to write a program that “reads 10 lines from the keyboard and prints them to the screen in reverse order.”

String[] array = new String[10];	// Create an array object with 10 elements
for (int i = 0; i < 10; i++)		// Loop from 0 to 9
{
   array[i] = console.nextLine();	// Read a line from the keyboard and store it in the array cell
}
for (int i = 9; i >= 0; i--)		// Loop from 9 down to 0
{
    System.out.println(array[i]);	// Print the next array cell to the screen
}

The code has hardly changed! We only needed to replace the type int with String when creating the array. Everything else is exactly the same!

Getting to know null

Here’s a riddle—what is stored in the cells of each of these arrays right after creation?

int[] numbers = new int[10];
String[] strings = new String[10];
User[] users = new User[10];

If you think about it, most likely the cells of numbers contain 0. Correct.

Then by the same logic, the cells of strings should be filled with empty strings — "". Let’s suppose.

And what are the cells of the users array filled with? Empty User objects?

Here’s the catch: not every data type has a “default value.” So the creators of Java devised a special constant — null. null is a null reference. When a variable for an object type is created, its initial value is null: a reference to nothing, the absence of a reference.

String name; 	// name contains null
name = "Alex";  // name holds a reference to the object/string "Alex"
name = null; 	// name contains null

Working with null

You cannot call methods on an object if the reference to it is null — the object doesn’t exist! In the following code, the program will terminate with an error:

String name; 	// name contains null
String upperName = name.toUpperCase(); // Will throw NullPointerException: name == null

As for our “riddle”, the answer is:

int[] numbers = new int[10];		// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
String[] strings = new String[10];  // {null, null, null, null, null, null, null, null, null, null}
User[] users = new User[10];		// {null, null, null, null, null, null, null, null, null, null}

Only primitive types have a “default value.” All other types default to null. The initial value of String is not the empty string. That’s life.

2. Array of type String in memory

Figure 1. How a String object is laid out in memory:

String array in memory

Note that the text of the string is not stored directly in the variable: a separate block of memory is allocated for it. And a variable of type String stores the address (reference) to the object with the text.

Figure 2. How an array of integers is laid out in memory:

int array in memory

You’ve seen this diagram before as well.

Figure 3. How an array of strings is laid out in memory:

How a String array is laid out in memory

On the left we see an array variable of type String[] (stores the address of the array object).

In the middle — the array object of type String.

And on the right — string objects that store some texts.

The cells of an array object of type String store not the strings (texts) themselves, but their addresses (references). Just like variables of type String store the addresses of strings (text).

3. Quick array initialization in Java

Arrays are very useful, so Java developers tried to make working with them as convenient as possible. And the first thing they did was simplify array initialization, i.e., setting its initial values.

Very often, besides the data the program reads from somewhere, it also needs its own internal data to work. For example, we need to store in an array the lengths of all months. What might that code look like:

int[] months = new int[12];
months[0] = 31; // January
months[1] = 28; // February
months[2] = 31; // March
months[3] = 30; // April
months[4] = 31; // May
months[5] = 30; // June
months[6] = 31; // July
months[7] = 31; // August
months[8] = 30; // September
months[9] = 31; // October
months[10] = 30; // November
months[11] = 31; // December

But there’s a shorter way to write it — thanks to the creators of Java:

// lengths of the months of the year
int[] months = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

You can simply list all the array values separated by commas!

It turns out the compiler can determine the type of the container (the array object) based on the type of the array variable. And to determine the length of the array, it can simply count the number of elements written inside the curly braces.

Therefore, this code can be written even shorter:

// lengths of the months of the year
int[] months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Isn’t it nice? 🙂 This notation is called “quick array initialization.” It works for types other than int as well...

// names of the months of the year
String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

4. The for-each loop

Iterating over all elements of an array is such a common operation that a special loop was invented for it — for-each. It’s written like this:

for (int score : scores)
{
    System.out.println("Score: " + score);
}
Iterating over an array with for-each

Here the loop iterates the elements by itself—no manual index. But you can’t modify elements directly (the loop variable holds only a copy of the value), although it’s very convenient to simply “walk” the array.

The compiler will turn the for-each loop into the code below:

for (int i = 0; i < scores.length; i++)
{
    int score = scores[i];
    System.out.println("Score: " + score);
}
How for-each works under the hood

So there’s no magic. And now it’s clear why you can’t change the array elements through the score variable.

Let’s write another example: find the sum of all scores.

int sum = 0;
for (int score : scores)
{
    sum += score;
}
System.out.println("Sum of all scores: " + sum);
Computing the sum of array values using for-each

When should you use which loop?

  • If you need an index or need to modify elements — use for.
  • If you just need to iterate over the values — for-each is faster and cleaner.

5. Modifying array elements

What if we need to increase each grade by 1 point (for example, for good behavior)? Here we need the classic for with an index, because only this way can we change the values in the array.

Example: increment each element by 1

for (int i = 0; i < grades.length; i++) {
    grades[i] = grades[i] + 1;
}

After this code runs, the grades array will have new values.

Why can’t you do it with for-each?

for (int grade : grades) {
    grade = grade + 1; // Doesn’t work!
}

This code won’t change the array because grade is a copy of the value from the array, not a reference to the element itself.

6. Computations based on an array

Arrays are often used for calculations: sum, average, maximum, minimum, and so on.

Example: sum of all elements of an array

int sum = 0;
for (int i = 0; i < grades.length; i++) {
    sum += grades[i]; // same as sum = sum + grades[i];
}
System.out.println("Sum of grades: " + sum);

Example: finding the maximum value

int max = grades[0]; // start with the first element
for (int i = 1; i < grades.length; i++) {
    if (grades[i] > max) {
        max = grades[i];
    }
}
System.out.println("Maximum grade: " + max);

Example: finding the minimum value

int min = grades[0]; // start with the first element
for (int i = 1; i < grades.length; i++) {
    if (grades[i] < min) {
        min = grades[i];
    }
}
System.out.println("Minimum grade: " + min);

Example: computing the arithmetic mean

int sum = 0;
for (int i = 0; i < grades.length; i++) {
    sum += grades[i];
}
double average = (double) sum / grades.length; // be sure to cast to double!
System.out.println("Average grade: " + average);

Note: to get a fractional number rather than an integer, you need to explicitly cast the sum to double before division.

7. Practical tasks

Reading an array from the keyboard

It’s often necessary to fill an array with values entered by the user. To do this, use the Scanner class and a loop.

Scanner console = new Scanner(System.in);

int n = 5; // array size
int[] numbers = new int[n];

System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
    numbers[i] = console.nextInt();
}

System.out.println("You entered:");
for (int i = 0; i < n; i++) {
    System.out.println(numbers[i]);
}

Printing an array in reverse order

Sometimes you need to print the elements of an array from the end (for example, to find out who entered the room last).

for (int i = grades.length - 1; i >= 0; i--) {
    System.out.println("Grade #" + (i + 1) + ": " + grades[i]);
}

8. Typical mistakes when working with one-dimensional arrays

Error #1: array index out of bounds

The most common problem is trying to access a non-existent element. In Java this leads to an ArrayIndexOutOfBoundsException. Remember: the last valid index is arr.length - 1.

int[] arr = new int[5];
System.out.println(arr[5]); // Error! Indices range from 0 to 4.

Error #2: forgot to initialize the array

You declared a variable but didn’t create the array:

int[] arr;
arr[0] = 5; // Error! The array hasn’t been created.

You must create the array with new:

arr = new int[10];

Error #3: trying to change array elements via for-each

In a for-each loop, the variable is a copy of the value, not a reference to the element:

for (int x : arr) {
    x = 100; // Does not modify the array!
}

To change values, use a regular for with an index.

Error #4: incorrect use of array length

Sometimes people confuse the array length with the last index:

for (int i = 0; i <= arr.length; i++) { // Error! Should be i < arr.length
    // ...
}

This code will go out of bounds.

Error #5: implicit type conversion

If the array is of type int, you can’t directly assign a value of type double:

int[] arr = new int[3];
arr[0] = 3.14; // Error! 3.14 is a double.
1
Task
JAVA 25 SELF, level 7, lesson 2
Locked
Initial high score table setup 🚀
Initial high score table setup 🚀
1
Task
JAVA 25 SELF, level 7, lesson 2
Locked
Collection of favorite movies in reverse order 🎞️
Collection of favorite movies in reverse order 🎞️
1
Task
JAVA 25 SELF, level 7, lesson 2
Locked
Calculating the total amount of purchases in the cart 🛍️
Calculating the total amount of purchases in the cart 🛍️
1
Task
JAVA 25 SELF, level 7, lesson 2
Locked
Determine the maximum temperature of the day 🌡️
Determine the maximum temperature of the day 🌡️
Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 1, San Diego, United States
10 January 2026
Output Interstellar Inception The Shawshank Redemption
Anonymous #11744457 Level 8, Seattle, United States
4 January 2026
int [] gameHighScores = {10, 20, 30, 40, 50};