Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Arrays: Declaration, Creation, and Initialization

Tech Jul 7 2

Introduction to Arrays

Arrays are fundamental data structures in nearly every programming language, though their implementation and handling vary. In Java, an array is a container object that holds a fixed number of values of a single type. Instead of declaring 100 separate variables like number0, number1, …, number99, you can declare an array variable such as numbers[100]. This tutorial covers how to declare, create, and initialize arrays in Java, with code examples.

Declaring Array Variables

Before you can use an array, you must declare a variable that references it. The syntax for declaring an array variable is:

dataType[] arrayRefVar;   // preferred method
// or
dataType arrayRefVar[];   // works but not preferred

Note: It is recommended to use the dataType[] arrayRefVar style. The dataType arrayRefVar[] style comes from C/C++ and is adopted in Java to help C/C++ programmers transition more easily.

Example

double[] myList;   // preferred
// or
double myList[];   // works but less common

Cerating Arrays

In Java, arrrays are created using the new operator:

arrayRefVar = new dataType[arraySize];

The statement above does two things:

  • It creates an array using new dataType[arraySize].
  • It assigns the reference of the newly created array to the variable arrayRefVar.

Declaration and creation can be combined into one statement:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively, you can create and initialize an array with values directly:

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

Array elements are accessed using an index, starting from 0 up to arrayRefVar.length - 1.

Example with Summation

The following code declares an array variable, creates an array of 10 doubles, assigns values, and calculates the sum:

public class ArrayDemo {
    public static void main(String[] args) {
        int length = 10;
        double[] values = new double[length];
        values[0] = 5.6;
        values[1] = 4.5;
        values[2] = 3.3;
        values[3] = 13.2;
        values[4] = 4.0;
        values[5] = 34.33;
        values[6] = 34.0;
        values[7] = 45.45;
        values[8] = 99.993;
        values[9] = 11123.0;

        double sum = 0;
        for (double v : values) {
            sum += v;
        }
        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 11367.373

The array indices range from 0 to 9. Each element is accessed by its index.

Processing Arrays

Because array elements and size are fixed, loops are commonly used to process them. Java supports basic for loops and enhanced for-each loops.

Example: Print, Sum, Find Maximum

public class ArrayProcessing {
    public static void main(String[] args) {
        double[] numbers = {1.9, 2.9, 3.4, 3.5};

        // Print all elements
        for (double num : numbers) {
            System.out.println(num);
        }

        // Calculate sum
        double sum = 0;
        for (double num : numbers) {
            sum += num;
        }
        System.out.println("Total is " + sum);

        // Find maximum
        double max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        System.out.println("Max is " + max);
    }
}

Compile and run — the output will be:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.