Java: Arrays


Arrays are treated differently than in C++. In fact, an array is an object in java.

Declaring Arrays

Here are some examples:
char s[];
int array[];
String Names[];
Button B[];

Creating Array Objects

To create an array you must use the new operator to create the instance. An Array is an object itself in Java. You can create Arrays that are arrays of objects like Integer or of primitive types like int. Some examples:
String[] Names = new String[50];  /*an array of strings storing names*/
Button[] B = new Button[3];  /*an array of 3 Buttons*/

//The following two Arrays contain primitive types of int and char 
//respectively rather than using the objects of Integer and Character
int[] array= new int[100];  /* 100 times can be stored in array*/

char[] x = new char[10];  /*an array of 10 x values*/
Note that if you want to only store a single name then you do not need an array of Strings but, just one String.
 

NOTE:   When you are creating an array of Objects, you must not only create the array but, for each
element of the array you must create an individual objects.   Hence the declarations above simply
create the array itself but, not the idividual objects at each array elements.   Here is what you need to
do in general:
 

Step 1:
        ClassName[]    C_Array = new ClassName[50];   //creating array of 50 ClassName

Step 2:
        for(int i=0; i<50; i++)
            C_Array[i] = new ClassName();        //call the constructor for each object that is an array element!!!!!!!!


The Length of an Array

You can always test the number of elements stored in an array by looking at the value stored in the variable called length that is a member of any kind of array. For example,
System.out.println("The number of names is " + Names.length);

Multidimensional Arrays

These are declared just as you would guess. For example, to declare a 2D array with 10 by 3 values you would:
int Image[][] = new int[10][3];
Note that Image[0].length tells you the number of elements in the 0th row of the image.


Initializing Arrays

There are three ways to initialize an array. For all Arrays of Objects with the exception of Strings, you must first declare the array and for each element call the class's constructor as shown in example 1.   For String Arrays and primitive type Arrays (e.g. arrays or int or float), you can either initialize the array at the same time you create it or afterwards. Examples 2 and 3 show these later methods.
 
Example 1  Example 2(only Strings and primitive types) Example 3 (only Strings and primitive types)
Button[] B = new Button[3];
B[0] = new Button();
B[1] = new Button();
B[2] = new Button();
String Names[] = { "Lynne", "Doug", "Butch", "Rosie" };
String Names[] = new Names[4];
Names[0] = "Lynne";
Names[1] = "Doug";
Names[2] = "Butch";
Names[3] = "Rosie";
;
Exercise


YOU CAN NOT DO THIS

You can not declare arrays as you did in C++. This you can NOT DO:
int list[50];
Example