Java2 Certification
|
|
You can discuss this topic with others at http://www.jchq.net/discus
Read reviews and buy a Java Certification book at http://www.jchq.net/bookreviews/jcertbooks.htm
Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms, both for declaration and for initialization.
Arrays in Java are similar in syntax to arrays in other languages such as C/C++ and Visual Basic. However, Java removes the feature of C/C++ whereby you can bypass the [] style accessing of elements and get under the hood using pointers. This capability in C/C++ , although powerful, makes it easy to write buggy software. Because Java does not support this direct manipulation of pointers, this source of bugs is removed.
An array is a type of object that contains values called elements. This gives you a convenient bag or holder for a group of values that can be moved around a program, and allows you to access and change values as you need them. Unlike variables which are accessed by a name, elements are accessed by numbers starting from zero. Because of this you can "walk" through an array, accessing each element in turn.
Every element of an array must be of the same type The type of the elements of an array is decided when the array is declared. If you need a way of storing a group of elements of different types, you can use the collection classes which are a new feature in the Java2 exam, and are discussed in section 10.
The declaration of an array does not allocate any storage, it just announces the intention of creating an array. A significant difference to the way C/C++ declares an array is that no size is specified with the identifier. Thus the following will cause a compile time error
int num[5];
The size of an array is given when it is actually created with the new operator thus
int num[]; num = new int[5];
This can be compressed into one line as
int num[] = new int[5];
Also the square brackets can be placed either after the data type or after the name of the array. Thus both of the following are legal
int[] num; int num[];
You can read these as either
You might also regard it as enough choice to cause confusion
Java arrays know how big they are, and the language provides protection from accidentally walking off the end of them. |
This is particularly handy if you are from a Visual Basic
background and are not used to constantly counting from 0. It also
helps to avoid one of the more insidious bugs in C/C++ programs where
you walk off the end of an array and are pointing to some arbitrary
area of memory.
Thus the following will cause a run time
error,
ArrayIndexOutOfBoundsException
int[] num= new int[5]; for(int i =0; i<6; i++){ num[i]=i*2; }
The standard idiom for walking through a Java array is to use the length member of the array thus
int[] num= new int[5]; for(int i =0; i<num.length; i++){ num[i]=i*2; }
Just in case you skipped the C/C++ comparison, arrays in Java always know how big they are, and this is represented in the length field. Thus you can dynamically populate an array with the following code
int myarray[]=new int[10]; for(int j=0; j<myarray.length;j++){ myarray[j]=j; }
Note that arrays have a length field not a length()
method. When you start to use Strings you will use the string,
length method, as in
s.length();
With an array the length is a field (or property) not a method.
Arrays in Java always start from zero. Visual Basic arrays may start from 1 if the Option base statement is used. There is no Java equivalent of the Visual Basic redim preserve command whereby you change the size of an array without deleting the contents. You can of course create a new array with a new size and copy the current elements to that array.
An array declaration can have multiple sets of square brackets. Java does not formally support multi dimensional arrays, however it does support arrays of arrays, also known as nested arrays.
The important difference between multi dimensional arrays, as
in C/C++ and nested arrays, is that each array does not have to be of
the same length. If you think of an array as a matrix, the matrix
does not have to be a rectangle. According to the Java Language
Specification
(http://java.sun.com/docs/books/jls/html/10.doc.html#27805)
"The
number of bracket pairs indicates the depth of array nesting."
In
other languages this would correspond to the dimensions of an array.
Thus you could set up the squares on a map with an array of 2
dimensions thus
int i[][];
The first dimension could be X and second Y coordinates.
Instead of looping through an array to perform initialisation, an array can be created and initialised all in one statement. This is particularly suitable for small arrays. The following will create an array of integers and populate it with the numbers 0 through 4
int k[]=new int[] {0,1,2,3,4};
Note that at no point do you need to specify the number of elements in the array. You might get exam questions that ask if the following is correct.
int k=new int[5] {0,1,2,3,4} //Wrong, will not compile!
You can populate and create arrays simultaneously with any data type, thus you can create an array of strings thus
String s[]=new String[] {"Zero","One","Two","Three","Four"};
The elements of an array can be addressed just as you would in
C/C++ thus
String s[]=new String[] {"Zero","One","Two","Three","Four"}; System.out.println(s[0]);
This will output the string Zero.
The elements of arrays are always set to default values wherever the array is created |
Unlike other variables that act differently between class level creation and local method level creation, Java arrays are always set to default values. Thus an array of integers will all be set to zero, an array of boolean values will always be set to false.
Create a class with a method that simultaneously creates and initialises a String array. Initialise the array with four names, then print out the first name in the array.
Create a class that creates a 5 element array of Strings called Fruit at class level but do not initialise with any values. Create a method called amethod. In amethod initialise the first four elements with the names of fruit. Create another method called modify and change the contents of the first element of the Fruit array to contain the string "bicycle". Within the modify method create a for loop that prints out every element of the Fruit array.
public class Bevere{ public static void main(String argv[]){ Bevere b = new Bevere(); b.Claines(); } public void Claines(){ String[] names= new String[]{"Peter","John","Balhar","Raj"}; System.out.println(names[0]); } }
Note: The syntax for simultaneous creation and initialisation is
not obvious and is worth practising. I asked for the first name to be
printed out to ensure you did not request names[1].
public class Barbourne{ String Fruit[]= new String[5]; public static void main(String argv[]){ Barbourne b = new Barbourne(); b.amethod(); b.modify(); } public void amethod(){ Fruit[0]="Apple"; Fruit[1]="Orange"; Fruit[2]="Bannana"; Fruit[3]="Mango"; } public void modify(){ Fruit[0]="Bicycle"; for(int i=0; i< Fruit.length; i++){ System.out.println(Fruit[i]); } } }
Note: that when the loop executes the output for the final elements is null
How can you re-size an array in a single statement whilst keeping the original contents?
You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it?
public class MyAr{ public static void main(String argv[]){ int[] i = new int[5]; System.out.println(i[5]); } }
You want to loop through an array and stop when you come to the last element. Being a good java programmer, and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use?
1)myarray.length(); 2)myarray.length; 3)myarray.size 4)myarray.size();
Your boss is so pleased that you have written HelloWorld he she has given you a raise. She now puts you on an assignment to create a game of TicTacToe (or noughts and crosses as it was when I were a wee boy). You decide you need a multi dimensioned array to do this. Which of the following will do the job?
1) int i=new int[3][3]; 2) int[] i=new int[3][3]; 3) int[][] i=new int[3][3]; 4) int i[3][3]=new int[][];
You want to find a more elegant way to populate your array than looping through with a for statement. Which of the following will do this? 1) myArray{ [1]="One"; [2]="Two"; [3]="Three"; end with 2)String s[5]=new String[] {"Zero","One","Two","Three","Four"}; 3)String s[]=new String[] {"Zero","One","Two","Three","Four"}; 4)String s[]=new String[]={"Zero","One","Two","Three","Four"};
You cannot "resize" and array. You need to create a
new temporary array of a different size and populate it with the
contents of the original. Java provides resizable containers with
classes such as Vector or one of the members of the collection
classes.
You will get a runtime error as you attempt to walk off the end of the array. Because arrays are indexed from 0 the final element will be i[4], not i[5]
2) myarray.length;
3) int[][] i=new int[3][3];
3)String s[]=new String[] {"Zero","One","Two","Three","Four"};
Other sources on this topic
This topic is covered in the Sun Tutorial
at |
Last updated
10 July 2000
copyright © Marcus Green
2000
most recent copy at http://www.jchq.net