1) Declarations and Access Control
Objective 1
Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms, both for declaration and for initialization.
1. Arrays are Java objects. (An object is a class instance or an array.) and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. If you create an array of 5 Strings, there will be 6 objects created.
2. Arrays should be
1. Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
2. Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
3. Initialized. for (int i = 0; i < a.length; a[i++] = 0)
3. The above three can be done in one step. int a[] = { 1, 2, 3 }; or int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.
4. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns array’s size, cannot be changed. (Use Vectors for dynamic purposes).
5. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable. Note that arrays have a length field (or property) not a length() method. When you start to use Strings you will use the string, length method, as in s.length();
6. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]
7. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0.
8. Comma after the last initializer in array declaration is ignored.
int[] i = new int[2] { 5, 10}; // Wrong
int i[5] = { 1, 2, 3, 4, 5}; // Wrong
int[] i[] = {{}, new int[] {} }; // Correct
int i[][] = { {1,2}, new int[2] }; // Correct
int i[] = { 1, 2, 3, 4, } ; // Correct
int i[][] = new int [10][]; //Correct, i.length=10.
int [] i, j[] == int i[], j[][];
9. Array indexes start with 0. Index is an int data type.
10. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.
11. Arrays declared even as member variables also need to be allocated memory explicitly.
static int a[];
static int b[] = {1,2,3};
public static void main(String s[]) {
System.out.println(a[0]); // Throws a null pointer exception
System.out.println(b[0]); // This code runs fine
System.out.println(a); // Prints ‘null’
System.out.println(b); // Prints a string which is returned by toString
}
12. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values.(0 for numeric arrays, false for boolean, '