Arrays in Java

An array is a fixed size object holding elements of one type, indexed from zero, with the length fixed at creation.

Definition

An array is an object that holds a fixed number of values of a single type. Elements are reached by an index that starts at zero, and the size is decided when the array is created and can never change afterwards.

Why arrays exist

  • Constant time access to any element by position.
  • A compact, predictable memory layout.
  • The foundation on which ArrayList, String and most collections are built.

Declaring and creating

int[] marks = new int[5];            // five elements, all 0
String[] names = new String[3];      // three elements, all null

int[] scores = {45, 78, 62, 91};     // shorthand, size inferred as 4
int[] copy = new int[]{1, 2, 3};     // full form, needed when not declaring

The brackets belong to the type. int[] marks is preferred over the legal but discouraged int marks[], because the type is then written in one piece.

Default values

Element typeDefault
Numeric primitives0 or 0.0
booleanfalse
charthe null character
Any reference typenull
An array of objects contains references, not objects. new String[3] creates three null slots, not three strings. Forgetting this produces a NullPointerException on the first use.

Reading and writing

int[] scores = {45, 78, 62, 91};

System.out.println(scores.length);      // 4 - a field, not a method
System.out.println(scores[0]);          // 45
System.out.println(scores[scores.length - 1]);   // 91

scores[2] = 70;
// scores[4] = 10;   // throws ArrayIndexOutOfBoundsException

Note the inconsistency worth memorising: an array uses length as a field, a String uses length() as a method, and a collection uses size().

Traversing

int[] scores = {45, 78, 62, 91};

for (int i = 0; i < scores.length; i++) {   // index available
    System.out.println(i + ": " + scores[i]);
}

for (int score : scores) {                   // values only
    System.out.println(score);
}

Common operations with java.util.Arrays

import java.util.Arrays;

int[] values = {40, 10, 30, 20};

Arrays.sort(values);                       // 10 20 30 40, sorts in place
System.out.println(Arrays.toString(values));

int position = Arrays.binarySearch(values, 30);   // 2, requires a sorted array

int[] copy = Arrays.copyOf(values, 6);            // padded with zeros
int[] part = Arrays.copyOfRange(values, 1, 3);    // 20 30, end is exclusive

Arrays.fill(copy, 7);
System.out.println(Arrays.equals(values, copy));  // element by element

Copying correctly

int[] original = {1, 2, 3};

int[] alias = original;                       // NOT a copy, same object
int[] real = Arrays.copyOf(original, original.length);   // a real copy

alias[0] = 99;
System.out.println(original[0]);   // 99 - the alias shared the array
System.out.println(real[0]);       // 1

Arrays and collections

String[] cities = {"Pune", "Kochi", "Surat"};

List<String> fixed = Arrays.asList(cities);        // fixed size view, writes through
List<String> flexible = new ArrayList<>(Arrays.asList(cities));   // independent
String[] back = flexible.toArray(new String[0]);

Arrays.asList returns a view. Adding or removing throws UnsupportedOperationException, and setting an element changes the original array.

Comparing arrays

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};

System.out.println(a == b);              // false - different objects
System.out.println(a.equals(b));         // false - Object identity, not contents
System.out.println(Arrays.equals(a, b)); // true

Arrays do not override equals, hashCode or toString. Printing an array directly shows a type marker and a hash, which is why Arrays.toString exists.

Common mistakes

  • Looping to i <= length and stepping past the last index.
  • Using length() on an array or length on a String.
  • Expecting an array to grow. Use ArrayList when the size changes.
  • Calling binarySearch on an unsorted array, which returns a meaningless result rather than failing.
  • Assigning one array variable to another and believing it copied.

Best practices

  • Prefer List in application code, and keep arrays for fixed size data, primitives and performance sensitive work.
  • Never return an internal array directly from a getter; return a copy or an unmodifiable list.
  • Use the enhanced for loop unless the index is needed.
  • Use Arrays.toString for one dimension and Arrays.deepToString for more.

Practice

  1. Write a method that returns the second largest value in an int[], handling arrays that are too short.
  2. Predict the output of System.out.println(new int[]{1, 2}); and explain it.
  3. Why does Arrays.asList(new int[]{1, 2, 3}).size() return 1?
  4. Reverse an array in place, without allocating a second array.
  5. Explain the difference between a.equals(b) and Arrays.equals(a, b).

Conclusion

An array is a fixed size object of one element type with zero based indexing. Learn Arrays.toString, sort, copyOf and equals early, and reach for a List as soon as the size needs to change.

Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Java notes →
Java

Strings in Java

String is an immutable object with a shared literal pool, and both facts explain how comparison, concatenation and performance behave.

Read more
Java

Introduction to Java

Java is a statically typed, object oriented language that compiles to bytecode and runs on a virtual machine, which is what makes it portable.

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.