Previous Topic Next topic Print topic


Arrays - in COBOL and Java

Arrays in Managed COBOL

01 nums binary-long occurs 3 values 1, 2, 3.  *> reference single-dimensional array

01 names1 string occurs 5. *> 5 is the size of the array
01 names2 string occurs any. *> size of array deferred until run-time
01 names3 string occurs 7.
01 twoD float-short occurs any, any.  *> 2-dimensional (rectangular) array
01 jagged binary-long occurs any, occurs any.  *> 2-dimensional (jagged) array

01 rows binary-short value 4.
01 cols binary-short value 3.

procedure division.

*> another way to reference an array
set content of nums to (1, 2, 3)  

*> another way to set size of array
set size of names1 to 5  
set names1(1) to "Rod"  *> first element indexed as 1
set names1(6) to "Jane"  *> throws ArrayIndexOutOfBoundsException

*> resizing arrays
*> resizes array by assigning reference to new array - current contents are lost to the garbage collector 
set size of names1 to 10  
*> to retain existing values, copy the array into a new array of the required size
invoke type System::arraycopy(names1, 0, names3, 0, size of names3)  *> copies array, maintaining its contents

 *> 2-dimensional arrays
 set size of twoD to rows, cols
 set size of jagged to 3
 set size of jagged(1) to 5
 set jagged(1 5) to 5  

Arrays in Java

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
{
   System.out.println(nums[i]);
}
	 
// 5 is the size of the array
String[] names = new String[5];
names[0] = "Rod";
names[5] = "Jane"; // Throws java.lang.ArrayIndexOutOfBoundsException 
	 
	 
// Copy an array into a new array.
String[] names2 = new String[7]; 
	
System.arraycopy(names, 0, names2, 0, names.length);
	 

float[][] twoD;          
twoD = new float[rows][cols];


// In Java this is just a multi-dimensional array
int[][] jagged = {{1, 2, 3},
  	          {1, 2, 3, 4, 5},
		  {1, 2}};
System.out.println("jagged[0][2] = " + jagged[0][2]); //prints 3

Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.

Previous Topic Next topic Print topic