Java Glossary : array

CMP home Java glossary home Menu no menu Last updated 2004-06-30 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : A words : array.

array
A fixed length block of primitives or references. Java never stores blocks of repeating structures. It always creates blocks of references to separately stored structures. Novices make two common errors: failing to allocate space for the array and failing to allocate objects for each cell. Java automatically initialises arrays of primitives to 0 and arrays of references to null. It won't create any objects for you automatically. Here is how you would allocate an array of primitives:

// note how you never specify the array's size in its type declaration.
int[] v;
// allocate space for the array (normally collapsed onto the previous line)
v = new int [100];
for ( int i=0; i<v .length; i++ ) v[i] = i*2+999;

Here is how you would allocate an array of objects.

String[] fruits =
{
   "banana" , "pear" , "orange" , null, favouriteFruit()
};

You can initialise an array to a list of values this way:

fruits = new String []
{
   "banana" , "pear" , "orange" , null, favouriteFruit()
};

Methods can return arrays. Usually the callee allocates them. However the caller could allocate them and pass them as parameters.

String[] getFruits()
   {
   String[] s = new String [3];
   // at this point s[i] is null not ""
   s[0] = "banana";
   s[1] = "strawberry";
   s[2] = favouriteFruit();
   return s;
   }
Here are some ways from simple to complex that you can return an array of Strings from a method.
// Returning an array of Strings from a method
// When you know all the strings at once.
return new String[]{ "one", "two" };

// Returning an array of Strings from a method
// when you know in advance how many there will be.
String[] things = new String[2];
things[0] = "one";
things[1] = "two";
return things;

// Returning an array of Strings from a method
// when you don't know in advance how many there will be.
Arraylist al = new ArrayList( max );
al.add( "one" );
al.add( "two" );
...
// converting an ArrayList to an array
return (String[])al.toArray( new String[al.size()] );


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 7066.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/array.html J:\mindprod\jgloss\array.html