One Dimensional Arrays

Creating One Dimensional Arrays

🙋 Need help? Ask an expert now!

In the real world, programmers examine, use, test, and manipulate gigantic amounts of data. Arrays are used to systematically organize and process this data efficiently and effectively. When data is standardized and formulated into arrays, a simple and small Java program can handle an enormous amount of data. Take a look at the three different arrays below.

OneDimensionalArraysExample.java
package exlcode;

public class OneDimensionalArraysExample {

  // exampleVariableOne is declared but not initialised
  public static int[] exampleVariableOne;
  public static int[] exampleVariableTwo = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  public static boolean[] exampleVariableThree = {true, false, false, true};

  public static void main(String[] args) {
    // the default value for int[] elements is 0
    exampleVariableTwo[0] = 10;
    System.out.println(exampleVariableTwo[3]);
    System.out.println(exampleVariableThree[1]);

  }
}

An array is made up of a cells that are used to store a value. Each array can hold a list of values. All the values in an array need to have same data type. Like String variables, the index of an array starts with 0. There are two ways to initialize an array:

  1. datatype[] arrayname = {valueOne, valueTwo, valueThree};

    The simplest way to create an array is enclosing its values in curly braces separated by commas.

  2. datatype[] arrayname = new datatype[arraylength];

    We give an array a certain length and adhere to it throughout the whole program. The length cannot be altered once given.

You can access the elements in the array using: arrayname[index]. This indicates a specific element inside the array using the index. You can then manipulate the value it holds.

Application Question

#!exl::repl('index.prob.repl.yaml')