Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Arrays
  6. Lesson 11: Single-Dimensional Arrays

Lesson 11: Single-Dimensional Arrays

Lecture in pdf

Lesson 11: Single-Dimensional Arrays

Understanding array declaration, creation, processing, and common operations.

Introduction

Arrays in Java have the following features:

  • Every element in the array contains a value.
  • Arrays are zero-indexed, that is, the first item in the array is element 0.
  • The size of an array is the total number of elements that it can contain.
  • Arrays can be single-dimensional, multidimensional, or jagged.
  • The rank of an array is the number of dimensions in the array.

Important: A single array variable can refer to a large collection of data.

When an array is created, its size is fixed. An indexed variable is used to access an element of the array.

An array is used to store a collection of data, but often we think of it as a collection of variables of the same type. Instead of declaring individual variables such as number0, number1, …, number99, you declare one array variable, for example, numbers, and use indexed variables such as numbers[0], numbers[1], ..., numbers[99] to access individual elements in the array. This section describes how to declare, create, and process arrays using indices.

Declaring Arrays

To use an array in a program, you must declare a variable to reference the array and specify the array's element type.

Syntax for declaring an array variable:

elementType[] arrayRefVar;

or

elementType arrayRefVar[]; // Allowed, but less preferred

elementType can be any data type, and all elements in the array will have the same data type. For example, the following code declares a variable myList that references an array of double elements.

double[] myList;

or

double myList[]; // Allowed, but less preferred

Creating Arrays

Unlike declaring primitive type variables, declaring an array variable does not allocate any memory for the array. It only allocates memory for a reference to an array. If a variable does not contain a reference to an array, its value is null. You cannot assign values to array elements until the array is created. After declaring an array variable, you can create an array using the new operator and assign its reference to the variable with the following syntax:

arrayRefVar = new elementType[arraySize];

This statement does two things: (1) it creates an array using new elementType[arraySize]; (2) it assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement as follows:

elementType[] arrayRefVar = new elementType[arraySize];

or

elementType arrayRefVar[] = new elementType[arraySize];

Here is an example of such a statement:

double[] myList = new double[10];

This statement declares an array variable myList, creates an array of 10 elements of type double, and assigns its reference to myList. To assign values to array elements, use the following syntax:

arrayRefVar[index] = value;

For example, the following code initializes the array myList:

myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123;

Important: An array variable that appears to hold an array actually contains a reference to that array. Strictly speaking, an array variable and an array are two different things, but most of the time the distinction can be ignored. Thus, for simplicity, we will often say that myList is an array, rather than stating that it is a variable that contains a reference to an array of double elements.

Array Size and Default Values

When allocating memory for an array, you must specify the size of the array to indicate the number of elements that can be stored in it. Once an array is created, its size cannot be changed. You can obtain the size using arrayRefVar.length. For example, myList.length is 10.

When an array is created, its elements are assigned default values: 0 for numeric primitive types, \u0000 for char, and false for boolean.

Accessing Array Elements

Array elements are accessed through an index. Array indices start at 0; they range from 0 to arrayRefVar.length - 1. In the previous figure, array myList contains 10 double values, and the array indices range from 0 to 9 inclusive.

Each element in the array is represented using the following syntax, called an indexed variable:

arrayRefVar[index];

For example, myList[9] represents the last element in array myList.

An indexed variable can be used just like a regular variable. For example, the following code adds the values in myList[0] and myList[1] to myList[2]:

myList[2] = myList[0] + myList[1];

The following loop assigns 0 to myList[0], 1 to myList[1], ..., 9 to myList[9]:

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

Array Initializers

Java has a shorthand notation, called an array initializer, which combines declaring, creating, and initializing an array in one statement with the following syntax:

elementType[] arrayRefVar = {value0, value1, ..., valuek};

For example, the statement

double[] myList = {1.9, 2.9, 3.4, 3.5};

declares, creates, and initializes the array myList with four elements, which is equivalent to the following statements:

double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Important: The array initializer syntax does not use the new operator. Using an array initializer, you can declare, create, and initialize an array in a single statement. Splitting these operations may cause a syntax error. Thus, the following statements are incorrect:

double[] myList;
myList = {1.9, 2.9, 3.4, 3.5}; // Invalid

Processing Arrays

When processing array elements, we often use a for loop for the following reasons:

  1. All elements in an array are of the same type, so they can be processed uniformly using a loop.
  2. The size of the array is known, so it is natural to use a counted loop, such as a for loop.

Assume the array is created as follows:

double[] myList = new double[10];

Here are examples of processing the array:

1. Initializing an Array with Input Values

The following loop initializes the array myList with user input:

java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
    myList[i] = input.nextDouble();

2. Initializing an Array with Random Values

The following loop initializes the array myList with random values between 0.0 and 100.0:

for (int i = 0; i < myList.length; i++) {
    myList[i] = Math.random() * 100;
}

3. Displaying an Array

To print an array, you need to print each element using a loop, for example:

for (int i = 0; i < myList.length; i++) {
    System.out.print(myList[i] + " ");
}

A char[] array can be printed with a single println() statement. For example, the following code displays Moscow:

char[] city = {'M', 'o', 's', 'c', 'o', 'w'};
System.out.println(city);

4. Summing All Elements

Use a variable named total to store the sum. Initialize total to 0. Add each element to total using a loop, for example:

double total = 0;
for (int i = 0; i < myList.length; i++) {
    total += myList[i];
}

5. Finding the Largest Element

Use a variable named max to store the largest element. Initialize max with myList[0]. To find the largest element in array myList, compare each element with max and update max if the current element is greater.

double max = myList[0];
for (int i = 1; i < myList.length; i++) {
    if (myList[i] > max)
        max = myList[i];
}

6. Finding the Smallest Index of the Largest Element

Sometimes you need to locate the largest element in an array. If the array has several elements with the same largest value, find the smallest index among them. Assume array myList is {1, 5, 3, 4, 5, 5}. The largest element is 5, and the smallest index for 5 is 1. Use a variable named max to store the largest element and a variable named indexOfMax to store the index of the largest element. Initialize max with myList[0] and indexOfMax with 0. Compare each element in myList with max and update max and indexOfMax if the element is greater than max.

double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) {
    if (myList[i] > max) {
        max = myList[i];
        indexOfMax = i;
    }
}

7. Shuffling Elements

In many applications, you need to randomly reorder the elements in an array. To do this, for each element myList[i], generate a random index j and swap myList[i] with myList[j] as follows:

for (int i = 0; i < myList.length; i++) {
    // Generate a random index j
    int j = (int)(Math.random() * myList.length);
    // Swap myList[i] and myList[j]
    double temp = myList[i];
    myList[i] = myList[j];
    myList[j] = temp;
}

8. Shifting Elements

Sometimes you need to shift elements left or right. Here is an example of shifting elements one position to the left and filling the last element with the first element's value:

double temp = myList[0]; // Save the first element

// Shift elements left
for (int i = 1; i < myList.length; i++) {
    myList[i - 1] = myList[i];
}

// Move the first element to fill the last position
myList[myList.length - 1] = temp;

9. Simplifying Coding

Arrays can greatly simplify coding for certain tasks. Suppose you want to obtain the name of a given month by its number. If the month names are stored in an array, the month name for a given month is accessed directly via the index. The following code prompts the user to enter a month number and displays the month name:

String[] months = {"January", "February", ..., "December"};
System.out.print("Enter month number (1 to 12): ");
int monthNumber = input.nextInt();
System.out.println("Month is " + months[monthNumber - 1]);

If the array of months were not used, you would have to determine the month name using a long multiway if-else statement.

Random Range: rand.nextInt(maxValue - minValue + 1) + minValue ensures inclusive bounds.

foreach Loop

Java supports a convenient for loop, called a foreach loop, that enables you to traverse the array sequentially without using an indexed variable. For example, the following code displays all elements in array myList:

for (double e : myList) {
    System.out.println(e);
}

You can read this code as “for each element e in myList, do the following.” Note that the variable e must be declared of the same type as the elements in myList.

In general, the syntax for a foreach loop is:

for (elementType element : arrayRefVar) {
    // Process element
}

If you need to traverse the array in a different order or modify the array elements, you must use an indexed variable.

Important: Attempting to access an array out of bounds is a common programming error that throws a runtime ArrayIndexOutOfBoundsException. To avoid this error, do not access indices beyond arrayRefVar.length - 1 or simply use a foreach loop when possible.

Programmers often mistakenly reference the first element in an array with index 1 instead of 0. This is called an off‑by‑one error. Another common loop error is using <= where < should be used. For example, the following loop is incorrect:

for (int i = 0; i <= list.length; i++)
    System.out.print(list[i] + " ");

Here <= should be replaced with <. You can avoid off‑by‑one errors by using a foreach loop.

Passing Arrays to Methods

Important: When an array is passed to a method, a reference to the array is passed.

Just as you can pass primitive type values to methods, you can also pass arrays. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
}

You can invoke this method by passing an array. For example, the following statement invokes the printArray() method to display 3, 1, 2, 6, 4, 2.

printArray(new int[]{3, 1, 2, 6, 4, 2});

Note: In the preceding statement, the array is created using the syntax:

new elementType[]{value0, value1, ..., valuek};

There is no explicit reference to the array, so such an array is called an anonymous array.

Java uses pass‑by‑value to pass arguments to a method. There are important differences between passing values of primitive data types and passing arrays.

  • For an argument of a primitive type, the argument's value is passed.
  • For an array argument, the argument's value is a reference to the array; this reference value is passed to the method. This is called pass‑by‑reference, meaning the passed array and the array inside the method are the same. Thus, if you change the array inside the method, the change will be visible outside the method.

Consider the program TestArrayArguments:

public class TestArrayArguments {
    public static void main(String[] args) {
        int x = 1; // x represents an int value
        int[] y = new int[10]; // y represents an array of int values
        
        m(x, y); // Invoke method m with arguments x and y
        System.out.println("x is " + x);
        System.out.println("y[0] is " + y[0]);
    }

    public static void m(int number, int[] numbers) {
        number = 1001; // Assign a new value to number
        numbers[0] = 5555; // Assign a new value to numbers[0]
    }
}

You may wonder why after invoking m(), x remains 1 but y[0] becomes 5555. This is because y and numbers, although independent variables, refer to the same array, as shown in the following figure. When m(x, y) is invoked, the values of x and y are passed to number and numbers. Since y contains a reference to the array, numbers now contains the same reference to the same array.

Note: In Java, arrays are objects (objects will be introduced in later courses). The JVM stores objects in an area of memory called the heap, which is used for dynamic memory allocation.

The program TestPassArray illustrates the difference between passing a primitive data type value and passing an array reference to a method.

The program TestPassArray contains two methods for swapping elements in an array. The first method, named swap, fails to swap two int arguments. The second method, named swapFirstTwoInArray, successfully swaps the first two elements in the array argument.

public class TestPassArray {
    /** Main method */
    public static void main(String[] args) {
        int[] a = {1, 2};

        // Swap elements using the swap method
        System.out.println("Before invoking swap");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
        swap(a[0], a[1]);
        System.out.println("After invoking swap");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");

        // Swap elements using the swapFirstTwoInArray method
        System.out.println("Before invoking swapFirstTwoInArray");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
        swapFirstTwoInArray(a);
        System.out.println("After invoking swapFirstTwoInArray");
        System.out.println("array is {" + a[0] + ", " + a[1] + "}");
    }

    /** Swap two variables */
    public static void swap(int n1, int n2) {
        int temp = n1;
        n1 = n2;
        n2 = temp;
    }

    /** Swap the first two elements in the array */
    public static void swapFirstTwoInArray(int[] array) {
        int temp = array[0];
        array[0] = array[1];
        array[1] = temp;
    }
}

As shown in the following figure, the two elements are not swapped using the swap() method, but they are swapped using the swapFirstTwoInArray() method. Because the parameters in swap() are of primitive type, the values of a[0] and a[1] are passed to n1 and n2. The memory locations for n1 and n2 are independent of those for a[0] and a[1], so the call does not affect the array's contents.

The parameter of the swapFirstTwoInArray() method is an array. As shown in the previous figure, a reference to the array is passed to the method. Thus, the variables a (outside the method) and array (inside the method) refer to the same array in the same memory location, so swapping array[0] and array[1] inside swapFirstTwoInArray() is the same as swapping a[0] and a[1] outside the method.

Returning an Array from a Method

Important: When an array is returned from a method, a reference to the array is returned.

When a method is called, you can pass arrays to it. A method can also return an array. For example, the following method reverse() returns an array that is a reversal of another array.

 1 public static int[] reverse(int[] list) {
 2   int[] result = new int[list.length];
 3
 4   for (int i = 0, j = result.length - 1; i < list.length; i++, j--)
 5     result[j] = list[i];
 6
 7   return result;
 8 }

In line 2, a new array result is created. Lines 4–5 copy elements from array list to array result. In line 7, the array is returned.

For example, the following statement returns a new array list2 with elements 6, 5, 4, 3, 2, 1:

int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

Laboratory Work

Lab 1: Number of Odd Elements in an Array (Java Version)

Objective: Process an integer array to:

  • print its elements;
  • count odd elements;
  • count positive elements.

Expected Output:

Array:
-1 -2 3 4 5 6 7
Number of odd elements: 4, number of positive elements: 4.

File name: L11Lab1.java

Step‑by‑Step Implementation

  1. Step 1: Create the Java File
    • Create a new Java class named L11Lab1.
    • Ensure the file is saved as L11Lab1.java.
  2. Step 2: Define the Class and Main Method
    public class L11Lab1 {
        public static void main(String[] args) {
            // Step 3 will go here
        }
    }
  3. Step 3: Initialize the Array

    Inside the main method, declare and initialize the integer array:

    int[] a = new int[] { -1, -2, 3, 4, 5, 6, 7 };
  4. Step 4: Create the printArray Method

    Below the main method, define a static method to print the array:

    static void printArray(int[] arr) {
        System.out.println("Array:");
        for (int x : arr) {
            System.out.print(x + " ");
        }
        System.out.println(); // New line after printing all elements
    }

    Explanation:

    • Uses an enhanced for loop (foreach) to iterate through arr.
    • System.out.print() prints elements on the same line.
    • Final println() adds a newline.

  5. Step 5: Call printArray in main

    Add this line in main after array initialization:

    printArray(a);
  6. Step 6: Create the countOddPositive Method

    Below printArray, define the counting method:

    static void countOddPositive(int[] arr, int[] counts) {
        counts[0] = 0; // countOdd
        counts[1] = 0; // countPos
    
        for (int x : arr) {
            if (x % 2 != 0) {
                counts[0]++; // Increment odd counter
            }
            if (x > 0) {
                counts[1]++; // Increment positive counter
            }
        }
    }

    Key Notes:

    • We use an int[] counts array (size 2) to return both values:
      • counts[0] → number of odd elements.
      • counts[1] → number of positive elements.
    • Initialize counters to 0 at the start of the method.

  7. Step 7: Prepare and Call countOddPositive in main

    Add these lines after printArray(a);:

    int[] counts = new int[2]; // [countOdd, countPos]
    countOddPositive(a, counts);
    
    int countOdd = counts[0];
    int countPos = counts[1];
  8. Step 8: Print the Results

    Add the output statement:

    System.out.println("Number of odd elements: " + countOdd + 
                   ", number of positive elements: " + countPos + ".");
  9. Step 9: How to Run
    1. Save the file as L11Lab1.java.
    2. Compile:
      javac L11Lab1.java
    3. Run:
      java L11Lab1

Lab 2: Random (Java Version)

Objective: Create a program that:

  • fills an array of 10 elements with random integers (range: –10 to 15);
  • prints the array;
  • finds and counts elements divisible by 3.

Expected Output:

Array:
-1 -2 3 4 5 6 7 12 9 10
elements divisible by 3:
3 6 12 9
number of elements divisible by 3: 4

File name: L11Lab2.java

Step‑by‑Step Implementation

  1. Step 1: Create the Java File
    • Create a new Java class named L11Lab2.
    • Save the file as L11Lab2.java.
  2. Step 2: Define the Class and Main Method
    public class L11Lab2 {
        public static void main(String[] args) {
            // Steps 3–6 will go here
        }
    }
  3. Step 3: Declare the Array

    Inside main, declare an integer array of length 10:

    int[] arr = new int[10];
  4. Step 4: Create fillRandomArray Method

    Below main, define a method to fill the array with random values:

    static void fillRandomArray(int[] arr, int minValue, int maxValue) {
        java.util.Random rand = new java.util.Random();
        
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rand.nextInt(maxValue - minValue + 1) + minValue;
        }
    }

    Explanation:

    • java.util.Random is used to generate random numbers.
    • rand.nextInt(range) + minValue ensures values are within [minValue, maxValue].
    • arr.length gives the array size (10).

  5. Step 5: Call fillRandomArray in main

    Add this line in main after array declaration:

    fillRandomArray(arr, -10, 15);
  6. Step 6: Create printArray Method

    Below fillRandomArray, define a method to print the array:

    static void printArray(int[] arr) {
        System.out.println("Array:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println(); // New line after printing
    }

    Note:

    • System.out.print() keeps elements on the same line.
    • Final println() adds a newline.

  7. Step 7: Call printArray in main

    Add this line after fillRandomArray:

    printArray(arr);
  8. Step 8: Create divisibleBy3 Method

    Below printArray, define the method to find elements divisible by 3:

    static void divisibleBy3(int[] arr) {
        int counter = 0;
        System.out.println("elements divisible by 3:");
    
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 3 == 0) {
                System.out.print(arr[i] + " ");
                counter++;
            }
        }
    
        System.out.println(); // New line after listing elements
        System.out.println("number of elements divisible by 3: " + counter);
    }
  9. Step 9: Call divisibleBy3 in main

    Add this line at the end of main:

    divisibleBy3(arr);
  10. Step 10: How to Run
    1. Save the file as L11Lab2.java.
    2. Compile:
      javac L11Lab2.java
    3. Run:
      java L11Lab2

Tasks for Independent Work

Task Description Expected Output File Name
Task 1 An array of doubles is given (the values of its elements: 1.1, -2.3, 3.7, 4.1, 5.6, 6.1, 7.1).
  1. Create a function to print the array.
  2. Create one more function to find and print a minimum and maximum elements of this array. Note, that it is not allowed to use the standard min and max functions.
Note 1: Create a function named print to output the array’s elements.
Note 2: Create a function findMaxMin with foreach loop and if statements to find maximum and minimum elements. The signature of the function should look like this:
static void findMaxMin(double[] arr, double[] max, double[] min) {
    // max[0] and min[0] will hold the results
}
Array:
1.1 -2.3 3.7 4.1 5.6 6.1 7.1
maximum element is: 7.1, minimum element is: -2.3
L11Task1.java
Task 2 An array of integers is given (15 elements with random values in the range from 1 to 10). Find if there is an element equal to N in the array (N is inputted). Output «yes» or «no» only once. To find the element use foreach loop.
  1. Create the functions to fill the array and output its elements.
  2. Create one more function findN to find an element equal to N (N is one of the parameters of the function).
Note 1: To stop loop iterations the break statement is required:
for (int x : arr) {
    if (...) {
        ...
        break; // exit loop
    }
}
Note 2: To check if the number was found you can create a boolean variable:
boolean found = false;
Extra task: Find the index of the found element.
Array:
9 5 1 3 7 7 8 1 4 4
input a number to look for:
6
result: no

Array:
2 6 2 6 8 1 9 1 7 2
input a number to look for:
2
result: yes
L11Task2.java
Task 3 An array of doubles is given (10 elements with random values in the range from -5.0 to 5.0).
  1. Create the functions to fill the array and output its elements.
  2. Create one more function to calculate and print the sum of triples of adjacent elements: a[0]+a[1]+a[2], a[1]+a[2]+a[3], a[2]+a[3]+a[4], ……, a[7]+a[8]+a[9].
Note 1: To generate double values of the array, using the boundaries:
import java.util.Random;
...
Random rand = new Random();
a[i] = rand.nextDouble() * 10 - 5; // range -5.0 to 5.0
Note 2: To output doubles with a number of digits after the decimal point:
// two digits after point
System.out.printf("%.2f ", arr[i]);
Array:
-3.54 0.51 3.79 1.85 -4.11 -2.32 -1.35 -0.78 0.63 4.31
sums of the triples:
0.76 6.15 1.53 -4.59 -7.79 -4.46 -1.50 4.16
L11Task3.java

Educational Content for Students — Lesson 11: Single-Dimensional Arrays

Style Guide: Blue (#2c5aa0), Green (#2c6e26), Gray (#ccc, #333, #f8f9fa), Orange (#ff8c00, #e67e22)

◄ Lesson # 10: Methods
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • ТФНД

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

          • Methods (functions)

          • Arrays

            • AssignmentLesson 11: Single-Dimensional Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2026

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика