Assigning array values on creation

It is useful to assign values to arrays at the time of creation. For example if you were creating an array of Strings to represents the days of the week, it would be useful to assign the String values at creation time. The following example shows how you can do this.

public class Days{
    static String[] saDays = {"mon","tue","wed","thu","fri"};
    public static void main(String argv[]){
	System.out.println(saDays[0]);
    }
}

Note that this only creates elements for the weekdays, if you were to attempt to access elements 6 or 7 in the expectation of retrieving "sat" and "sun" the program would show an error message. This is known as "Throwing an exception" in Java jargon.

The new for loop

JDK1.5 (Java 5) introduced a new more compact version of the for loop. Thus the code in the previous example can be expressed as

public class NewFor{
static int income[] = new int[]{1,2,3,4};
	public static void main(String argv[]){
	for(int i : income){
		System.out.println(i);
	}	
}

Note how this form of the for loop does not require explicit coding of the increment counter and how it automatically steps through each element of the arrays. As well as arrays, it is particularly useful for stepping through the elements of instances of the Collection classes (introduced later).

Last modified: Sunday, 20 September 2015, 07:21 PM