Java Language Arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Arrays allow for the storage and retrieval of an arbitrary quantity of values. They are analogous to vectors in mathematics. Arrays of arrays are analogous to matrices, and act as multidimensional arrays. Arrays can store any data of any type: primitives such as int or reference types such as Object.

Syntax

  • ArrayType[] myArray; // Declaring arrays
  • ArrayType myArray[]; // Another valid syntax (less commonly used and discouraged)
  • ArrayType[][][] myArray; // Declaring multi-dimensional jagged arrays (repeat []s)
  • ArrayType myVar = myArray[index]; // Accessing (reading) element at index
  • myArray[index] = value; // Assign value to position index of array
  • ArrayType[] myArray = new ArrayType[arrayLength]; // Array initialization syntax
  • int[] ints = {1, 2, 3}; // Array initialization syntax with values provided, length is inferred from the number of provided values: {[value1[, value2]*]}
  • new int[]{4, -5, 6} // Can be used as argument, without a local variable
  • int[] ints = new int[3]; // same as {0, 0, 0}
  • int[][] ints = {{1, 2}, {3}, null}; // Multi-dimensional array initialization. int[] extends Object (and so does anyType[]) so null is a valid value.

Parameters

ParameterDetails
ArrayTypeType of the array. This can be primitive (int, long, byte) or Objects (String, MyObject, etc).
indexIndex refers to the position of a certain Object in an array.
lengthEvery array, when being created, needs a set length specified. This is either done when creating an empty array (new int[3]) or implied when specifying values ({1, 2, 3}).


Got any Java Language Question?