Skip to main content
IBM 
ShopSupportDownloads
IBM HomeProductsConsultingIndustriesNewsAbout IBM
Java Language EssentialsDownload tutorial zip fileEmail this tutorial to a friend
Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
Course Notes
  


Arrays page 33 of 37


COBOL has tables that hold contiguous sequences of elements in memory just like a file holds contiguous sequences of records. Each element is uniquely identified by an integer index ("subscript" in COBOL terminology) within the table. Instead of having 5 name variables called name1, name2, ..., name5 you would define a table with 5 elements:


    02 NAMES OCCURS 5 TIMES PIC X(15).

The third name variable would correspond to the third element in the table. You access the elements of a table by specifying the table name followed by the index in parentheses:


MOVE 'John' TO names(3).

Table elements are typically accessed in PERFORM "loop" statements:


PERFORM VARYING Idx FROM 1 BY 1
        UNTIL Idx GREATER THAN 5
  DISPLAY names(Idx)
END-PERFORM

Java programming language has arrays that correspond to COBOL tables, however, Java arrays are themselves objects and are indexed from 0 instead of 1. You must use the new operator to create space for an array object. Here is the Java source code that declares an array called names containing five strings:


// elements names[0]..names[4]
String[] names = new String[5];

To set array elements, use the name followed by square brackets instead of parentheses:


names[3] = "John";

Loops in the Java programming language are also often used to access arrays. The following loop prints out the elements within the names array.


for (int i=0; i<="4;" i="i+1)" {	// i="0..4"
  System.out.println(names[i]);
}

copyright 1996-2000 Magelang Institute dba jGuru


Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
PrivacyLegalContact