Thursday, 27 October 2011

Sun Certified Java Programmer (SCJP)

Declarations and access control


Arrays


Arrays are dynamically created objects in Java code. An array can hold a number of variables of the same type. The variables can be primitives or object references; an array can even contain other arrays.

Declaring array variables


When we declare an array variable, the code creates a variable that can hold the reference to an array object. It does not create the array object or allocate space for array elements. It is illegal to specify the size of an array during declaration. The square brackets may appear as part of the type at the beginning of the declaration or as part of the array identifier:

int[] i;                 // array of int
byte b[];            // array of byte
Object[] o,         // array of Object
short s[][];        // array of arrays of short



Constructing arrays


You can use the new operator to construct an array. The size of the array and type of elements it will hold have to be included. In the case of multidimensional arrays, you may specify the size only for the first dimension:

int [] marks = new int[100];
String[][] s = new String[3][];



Initializing arrays


An array initializer is written as a comma-separated list of expressions, enclosed within curly braces:

String s[] = { new String("apple"),new String("mango") };
int i[][] = { {1, 2}, {3,4} };


An array can also be initialized using a loop:

int i[] = new int[5];
for(int j = 0; j < i.length;j++)
{
i[j] = j;
}



Accessing array elements


Arrays are indexed beginning with 0 and ending with n-1, where n is the array size. To get the array size, use the array instance variable called length. If you attempt to access an index value outside the range 0 to n-1, an ArrayIndexOutOfBoundsException is thrown.

1 comment: