Arrays

Array is a data structure that allows you to store a collection of elements of the same data type.

It provides a way to group multiple values under a single variable name, making it easier to manage and manipulate data.

Array Format

  • Any datatype in java can create an array, we put empty square brackets after the datatype

  • We provide a variable name for it

  • We create a “new” array and we must set a size before we used it

Examples of Arrays

  • Implicit array must have its size (maximum number of items) declared. (Line 1 and 2)

    • This arrays currently have empty spots; they do not have values

  • Use { ... } to explicitly create an array.

  • Explicit array (arrays that already contain values) do not need to specify the size.

Array Requirements

  1. The values in an Array must be all the same datatype

  2. The number of total items in the Array must be set prior and it cannot be changed after

  3. We can access individual items in a list by indexing,

    index value starts at zero (0)

  4. A value at a certain index can be changed which makes Arrays mutable.

Mutability

Mutable means that the object has the ability to change without recreation.

An immutable data type can only be changed by having their variables reassigned to a new value.

Example: Strings are Immutable

String name = "Jim";

name = "Tim"; // this is a valid code

name[0] = "J";

// Only changing a single part of a String is impossible

Arrays are Mutable

When an array wants to change a value at a certain index, we do not need to recreate the array, but we can just update the value at the index.

Traversal: Way to look at each individual Values

Explanation

  • All arrays have .length property to refer to the size of an array

  • Indexing (grabbing a value at a location) always starts at 0 zero. It can be also said that the last item of an array is located at length - 1 index.

  • A similar traversal can be done with a for loop

String Object to a Character Array

In Java, .toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.

Character Array to String Object

By creating a new string similar to creating a new scanner and providing a Character Array as an input, you can create a new string.

Printing an Array

We cannot simply print an array within System.out.println(). We must convert it to a string first.

Using Arrays.toString()

Output:

String to String Array using .split()

Purpose of .split() is to locate separating patterns such as commas or whitespace in a string to obtain a collection of data.

Last updated