book musings



missle defense



cultcha blog


scripts & programs

on the town



creds (PDF)



Java Arrays

Arrays can be used to keep multiple variables under a single variable name.

Defining an array is very much like defining a variable, albeit with a few modifications.

Two steps are required to initialize an array for use. They can combined later, but you should understand them separately.

First you must DECLARE an array; Then you must DEFINE one. Two different steps, see?

The basic format for DECLARING an array is here:

datatype [] variableName
Note, this is just like declaring a variable, except there is a pair of brackets (after the datatype) to signify the array-ness of the variable. Any data type that you can use for a variable, you can use for an array (string, int, etc.).

Second step: DEFINE your array:

variableName = new Datatype[size of array];
The new tells the JVM to make space in memory for the array. The size of the array tells the JVM how many spaces (of that data type) to set aside.

Here is an example of the last two steps:

int elephantWeights [];
elephantWeights = new int[10];
Also, note, you can combine the declaring and defining of an array into one step:
int [] elephantWeights = new int [10] ;
NOTE: The two data types must be the same in the above construction.

* * *

To put numbers in an array you do much the same you would for assigning a value to a variable:

[arrayname] = {[Value 1], [Value 2], etc...};
* * *
To access a particular value in the array, you call the name of the array and put the number of the array location within the bracket:
...will give you the contents of the 5th element in the array (Keep in mind that when the JVM allocates the spaces for each element of an array, it numbers them sequentially, beginning with "0" rather than "1" ).
* * *
Putting this all together, here is the working code for a basic array program:
import java.util.Scanner;

public class ArrayMagic {
			public static void main(String[] args){
				Scanner input = new Scanner(System.in);
				int arrayMagic[];
				arrayMagic = new int[3];
				System.out.println("Enter first number in an array:  ");
				arrayMagic[0] = input.nextInt();
				System.out.println("Enter second number in an array:  ");
				arrayMagic[1] = input.nextInt();
				System.out.println("Enter first number in an array:  ");
				arrayMagic[2] = input.nextInt();
				System.out.println("Your array consists of numbers " + arrayMagic[0] + " and " + arrayMagic[1]
				        + " and " + arrayMagic[2]);
In this command-line-based program, three numbers are collected from the user. The program then stores each one in an array called arrayMagic. It then prints them back out, calling each element in the array.

Material learned from the book, "Introduction to Java Programming" (7th edition), by Y. Daniel Liang..

...…as well as from the materials of a class I am taking. All mistakes are mine..
--Joab Jackson