Home » Tutorials » Software Development » Java » How to use Arrays in Java..

How to use Arrays in Java

Added March 15, 2008, read 1430 times

Learn about Java Arrays, one of the most useful objects in Java, which enable you to collect objects into an easy-to-manage list.

Arrays in Java are different than they are in other languages. Arrays in Java are actual objects that can be passed around and treated just like other objects.

Arrays can contain any type of value (base types or objects), but you can't store different types in a single array. You can have an array of integers, or an array of strings, or an array of arrays, but you can't have an array that contains, for example, both strings and integers.

To create an array in Java, you use three steps:

  1. Declare a variable to hold the array.
  2. Create a new array object and assign it to the array variable.
  3. Store things in that array.

Declaring Array Variables

The first step to creating an array is creating a variable that will hold the array, just as you would any other variable. Array variables indicate the type of object the array will hold (just as they do for any variable) and the name of the array, followed by empty brackets ([]). The following are all typical array variable declarations:

String difficultWords[]; Point hits[]; int temps[];

An alternate method of defining an array variable is to put the brackets after the type instead of after the variable. They are equivalent, but this latter form is often much more readable. So, for example, these three declarations could be written like this:

String[] difficultWords; Point[] hits; int[] temps;

Creating Array Objects

The second step is to create an array object and assign it to that variable. There are two ways to do this:

  • Using new
  • Directly initializing the contents of that array

The first way is to use the new operator to create a new instance of an array:

String[] names = new String[10];

That line creates a new array of Strings with ten slots, or elements. When you create the new array object using new, you must indicate how many elements that array will hold.

Array objects can contain primitive types such as integers or booleans, just as they can contain objects:

int[] temps = new int[99];

When you create an array object using new, all its elements are initialized for you (0 for numeric arrays, false for boolean, '\0' for character arrays, and null for everything else). You can also create and initialize an array at the same time. Instead of using new to create the new array object, enclose the elements of the array inside braces, separated by commas:

String[] chiles = { "jalapeno", "anaheim", "serrano," "habanero," "thai" };

Each of the elements inside the braces must be of the same type and must be the same type as the variable that holds that array. An array the size of the number of elements you've included will be automatically created for you. This example creates an array of String objects named chiles that contains five elements.

Accessing Array Elements

Once you have an array with initial values, you can test and change the values in each slot of that array. To get at a value stored within an array, use the array subscript expression:

myArray[subscript];

The myArray part of this expression is a variable holding an array object, although it can also be an expression that results in an array). The subscript is the slot within the array to access, which can also be an expression. Array subscripts start with 0, as they do in C and C++. So, an array with ten elements has array values from subscript 0 to 9.

Note that all array subscripts are checked to make sure that they are inside the boundaries of the array (greater than 0 but less than the array's length) either when your Java program is compiled or when it is run. It is impossible in Java to access or assign a value to an array element outside of the boundaries of the array. Note the following two statements, for example:

String arr[] = new String[10]; arr[10] = "eggplant";

A program with that last statement in it produces a compiler error at that line when you try to compile it. The array stored in arr has only ten elements numbered from 0, the element at subscript 10 doesn't exist, and the Java compiler will check for that.

If the array subscript is calculated at run-time (for example, as part of a loop) and ends up outside the boundaries of the array, the Java interpreter also produces an error (actually, to be technically correct, it throws an exception).

How can you keep from overrunning the end of an array accidentally in your own programs? You can test for the length of the array in your programs using the length instance variable. It's available for all array objects, regardless of type:

int len = arr.length // returns 10

Changing Array Elements

To assign a value to a particular array slot, merely put an assignment statement after the array access expression:

myarray[1] = 15; sentence[0] = "The"; sentence[10] = sentence[0];

An important thing to note is that an array of objects in Java is an array of references to those objects (similar in some ways to an array of pointers in C or C++). When you assign a value to a slot in an array, you're creating a reference to that object, just as you do for a plain variable.

When you move values around inside arrays (as in that last line), you just reassign the reference; you don't copy the value from one slot to another. Arrays of primitive types such as ints or floats do copy the values from one slot to another.

Arrays of references to objects, as opposed to the objects themselves, are particularly useful because it means you can have multiple references to the same objects both inside and outside arrays. For example, you can assign an object contained in an array to a variable and refer to that same object by using either the variable or the array position.

Multidimensional Arrays

Java does not support multidimensional arrays. However, you can declare and create an array of arrays (and those arrays can contain arrays, and so on, for however many dimensions you need), and access them as you would C-style multidimensional arrays:

int coords[][] = new int[12][12]; coords[0][0] = 1; coords[0][1] = 2;

Discuss







Comments:

Java programming using arrays

posted by Mark Harold F. Manguino on July 23, 2008 at 10:39 PM

Can I ask to send me more sample programs using arrays in java.

Java programming using arrays

posted by Mark Harold F. Manguino on July 23, 2008 at 10:39 PM

Can I ask to send me more sample programs using arrays in java. Thank You!

how to use array in java programming?

posted by prizesa on August 07, 2008 at 00:07 AM

can you give me more sample program and code on how to use array in java programming

shell

posted by Ronnel T. Orijuela on October 07, 2008 at 04:52 AM

import java.io.*; public class sampleArray { public static void main (String args []) throws IOException { BufferedReader x=new BufferedReader (new InputStreamReader (System.in)); int a; int num [] = new int[10]; for ( a=0; a<10; a++) { System.out.print ("Enter number " + (a+1) + " >> "); num[a] = Integer.parseInt(x.readLine()); } System.out.print("\n\n The inputted numbers are : \n"); for(a=0; a<10; a++) { System.out.println("" + num[a]); } } } Sample Output: Sample Array Output

Java programming using arrays

posted by ryan on October 07, 2008 at 3:24 PM

can you add more sample program?