MainframeCOBOL

50 COBOL Interview Questions and Answers (2026)

TT
TopicTrick Team
50 COBOL Interview Questions and Answers (2026)

50 COBOL Interview Questions and Answers (2026)

COBOL (Common Business-Oriented Language) processes an estimated $3 trillion in daily commerce and remains central to banking, insurance, government, and logistics systems worldwide. COBOL skills command premium salaries and strong job security — and a solid COBOL interview performance is your entry point.

This guide covers 50 essential COBOL interview questions with detailed answers, from fundamentals through advanced topics including DB2 embedded SQL and modernisation.


Fundamentals (Questions 1–12)

Question 1: What is COBOL and where is it used?

Answer

COBOL (Common Business-Oriented Language) is a high-level programming language designed for business data processing. Created in 1959 by a committee including Grace Hopper, it was designed to be readable by non-programmers and to process large volumes of structured business data efficiently.

COBOL runs primarily on IBM z/OS mainframes but also on Linux, Windows (via MicroFocus/Broadcom COBOL), and cloud environments. It powers:

  • Banking (ATM transactions, core banking, settlements)
  • Insurance (claims processing, actuarial calculations)
  • Government (tax systems, social security, customs)
  • Retail and logistics (inventory, order processing)
  • Healthcare (billing, claims adjudication)

An estimated 800 billion lines of COBOL code are in production globally, processing $3 trillion per day.


Question 2: What are the four COBOL divisions?

Answer

Every COBOL program is organised into four divisions in a fixed order:

  1. IDENTIFICATION DIVISION — program metadata. Required paragraphs: PROGRAM-ID (the only mandatory one). Optional: AUTHOR, DATE-WRITTEN, INSTALLATION, DATE-COMPILED, SECURITY.

  2. ENVIRONMENT DIVISION — describes the hardware and software environment. Contains:

    • CONFIGURATION SECTION (source and object computer)
    • INPUT-OUTPUT SECTION (FILE-CONTROL paragraph, mapping file names to DD names)
  3. DATA DIVISION — declares all data structures. Contains:

    • FILE SECTION (record layouts for files defined in ENVIRONMENT)
    • WORKING-STORAGE SECTION (program variables, constants, work areas)
    • LOCAL-STORAGE SECTION (variables re-initialised on each CALL — thread-safe)
    • LINKAGE SECTION (data passed from calling programs or JCL PARM)
  4. PROCEDURE DIVISION — the executable code. Business logic, I/O operations, calculations. Optionally divided into sections and paragraphs.


Question 3: What is the structure of a COBOL data item (PIC clause)?

Answer

A COBOL data item is defined with a level number, name, and PICTURE (PIC) clause describing its format.

PICTURE symbols:

  • 9 — a single numeric digit
  • A — a single alphabetic character
  • X — a single alphanumeric character (any character)
  • S — sign (leading or trailing); used for signed numbers
  • V — implied decimal point (no actual decimal stored)
  • P — assumed decimal position (scaling)
  • Z — numeric digit, suppressed to space if zero
  • $, ,, ., -, + — editing symbols for display formatting

Examples:

cobol
05 WS-AMOUNT     PIC 9(7)V99.      *> 7 digits, 2 decimal places
05 WS-NAME       PIC X(30).        *> 30-character string
05 WS-CODE       PIC S9(4) COMP.   *> Signed 4-digit binary integer
05 WS-DISPLAY    PIC ZZ,ZZZ.99-.   *> Edited display field

Level numbers: 01 (record level), 02–49 (subordinate fields), 66 (RENAMES), 77 (independent items), 88 (condition names).


Question 4: What is the COMP / COMPUTATIONAL usage clause?

Answer

USAGE specifies how a data item is stored internally:

UsageDescriptionBest for
DISPLAYCharacter representation (default)Character fields, edited output
COMP / COMPUTATIONALBinary integer (2, 4, or 8 bytes)Integer arithmetic, table indexes
COMP-3 / PACKED-DECIMALPacked decimal (2 digits per byte)Financial calculations
COMP-1Single-precision floating pointScientific calculations
COMP-2Double-precision floating pointHigh-precision scientific
COMP-4Same as COMP (binary)Synonymous with COMP
COMP-5Native binary (no truncation)High-performance integer math
INDEXInternal table indexSEARCH and SET statements

COMP-3 (Packed Decimal) is the most common usage for business arithmetic — faster than DISPLAY, exact decimal precision (unlike floating point), and compact storage.


Question 5: What is the difference between WORKING-STORAGE and LINKAGE SECTION?

Answer

WORKING-STORAGE SECTION:

  • Data items belong to the program itself
  • Storage is allocated and initialised when the program is first called
  • Values persist between calls (if the program is loaded in memory as a resident module)
  • Used for program variables, work areas, flags, counters, tables

LINKAGE SECTION:

  • Data items do not own storage — they are pointers to storage owned by the caller
  • Maps to data passed via CALL...USING (from a calling COBOL program) or via the JCL PARM parameter
  • Changes made to LINKAGE SECTION items are visible to the caller
  • Used for parameter passing between programs

Key distinction: if you initialise a WORKING-STORAGE item to ZEROS, it stays zero unless your code changes it. A LINKAGE SECTION item points to whatever the caller provided — its initial value depends entirely on the caller.


Question 6: What is a COPYBOOK and how is it used?

Answer

A COPYBOOK is a reusable source code fragment stored as a PDS member that is physically inserted into a COBOL program at compile time using the COPY statement.

cobol
WORKING-STORAGE SECTION.
    COPY WSCUSTOM.
    
FILE SECTION.
FD CUSTOMER-FILE.
    COPY FDCUSTOM.

Benefits:

  • Consistency: All programs using the same COPYBOOK have identical record layouts — if the layout changes, only the copybook needs updating (then recompile all programs)
  • Reuse: Define a data structure once, use in hundreds of programs
  • Error reduction: Eliminates copy-paste mistakes in record definitions

The REPLACING clause allows text substitution within a COPY:

cobol
COPY WSTEMPL REPLACING ==:PREFIX:== BY ==WS-CUST==.

COPYBOOKS are stored in a source library (e.g., MY.COPY.LIB) referenced by the SYSLIB DD in the compile JCL step.


Question 7: What is the 88-level condition name?

Answer

Level 88 defines a condition name — a meaningful name assigned to one or more specific values of a parent data item. Using 88-levels makes code more readable and maintainable.

Definition:

cobol
05 WS-STATUS         PIC X.
   88 STATUS-ACTIVE  VALUE 'A'.
   88 STATUS-INACTIVE VALUE 'I'.
   88 STATUS-PENDING  VALUE 'P'.
   88 STATUS-VALID    VALUE 'A' 'I' 'P'.

Usage:

cobol
IF STATUS-ACTIVE
    PERFORM PROCESS-ACTIVE-RECORD
END-IF

SET STATUS-PENDING TO TRUE   *> sets WS-STATUS to 'P'

Instead of IF WS-STATUS = 'A', you write IF STATUS-ACTIVE — self-documenting code. The SET...TO TRUE statement assigns the corresponding VALUE to the parent field.


Question 8: What is REDEFINES in COBOL?

Answer

REDEFINES allows multiple data names to occupy the same physical storage, enabling different interpretations of the same bytes.

cobol
05 WS-DATE-NUMERIC    PIC 9(8).
05 WS-DATE-PARTS      REDEFINES WS-DATE-NUMERIC.
   10 WS-YEAR         PIC 9(4).
   10 WS-MONTH        PIC 9(2).
   10 WS-DAY          PIC 9(2).

Rules:

  • The redefining item must immediately follow the item it redefines (at the same level)
  • The redefining item cannot be larger than the redefined item
  • REDEFINES cannot be used at the 01 level in File Section (use REDEFINES at 05 level within a record instead)
  • 88-level items under a REDEFINES clause inherit the parent's storage

REDEFINES is commonly used for: date reformatting, union-style fields that hold different data types, and mapping packed/binary fields to display fields for printing.


Question 9: What is the OCCURS clause and how are COBOL tables defined?

Answer

OCCURS defines a table (array) — a data item repeated a fixed or variable number of times.

Fixed-length table:

cobol
05 WS-MONTH-TABLE.
   10 WS-MONTH-NAME  PIC X(9) OCCURS 12 TIMES.

Variable-length table (OCCURS DEPENDING ON):

cobol
05 WS-ITEM-COUNT     PIC S9(4) COMP.
05 WS-ITEM-TABLE.
   10 WS-ITEM        PIC X(20) OCCURS 1 TO 100 TIMES
                     DEPENDING ON WS-ITEM-COUNT.

Accessing table elements:

cobol
MOVE 'JANUARY'   TO WS-MONTH-NAME(1)
MOVE WS-MONTH-NAME(WS-IDX) TO WS-DISPLAY-MONTH

Multi-dimensional tables:

cobol
05 WS-MATRIX.
   10 OCCURS 5 TIMES.
      15 WS-CELL     PIC 9(5) OCCURS 10 TIMES.

Access: WS-CELL(row, col)

OCCURS INDEXED BY creates an index item for use with SEARCH and SET.


Question 10: What is the SEARCH and SEARCH ALL statement?

Answer

SEARCH and SEARCH ALL look up values in COBOL tables.

SEARCH — sequential (linear) search through a table:

cobol
SEARCH WS-MONTH-TABLE
    AT END MOVE 'NOT FOUND' TO WS-RESULT
    WHEN WS-MONTH-NAME(WS-IDX) = WS-LOOKUP-MONTH
        MOVE WS-IDX TO WS-FOUND-INDEX
END-SEARCH

The table must have an INDEX item (INDEXED BY clause). SEARCH increments the index from its current value.

SEARCH ALL — binary search (much faster for large tables):

cobol
SEARCH ALL WS-MONTH-TABLE
    AT END MOVE 'NOT FOUND' TO WS-RESULT
    WHEN WS-MONTH-NAME(WS-IDX) = WS-LOOKUP-MONTH
        MOVE WS-FOUND TO WS-RESULT
END-SEARCH

Requires the table to be sorted (ASCENDING/DESCENDING KEY clause on OCCURS). SEARCH ALL uses binary search — O(log n) vs SEARCH's O(n).


Question 11: What is the difference between MOVE CORRESPONDING and a regular MOVE?

Answer

MOVE source TO destination — moves an individual data item. If moving between different data types, COBOL performs implicit conversion (numeric to display, etc.).

MOVE CORRESPONDING (MOVE CORR) group1 TO group2 — automatically moves each data item in group1 to the data item with the same name in group2, if it exists.

cobol
01 WS-INPUT-REC.
   05 WS-NAME    PIC X(30).
   05 WS-AMOUNT  PIC 9(7)V99.
   05 WS-CODE    PIC X(3).

01 WS-OUTPUT-REC.
   05 WS-NAME    PIC X(30).
   05 WS-AMOUNT  PIC 9(7)V99.
   05 WS-DATE    PIC 9(8).

MOVE CORRESPONDING WS-INPUT-REC TO WS-OUTPUT-REC
*> Moves WS-NAME and WS-AMOUNT (matching names); ignores WS-CODE and WS-DATE

Useful when two records share many field names but differ in some. Avoid when records differ significantly — the implicit matching can cause hard-to-spot bugs if naming conventions are inconsistent.


Question 12: What are the COBOL file organisations and access modes?

Answer

File Organisation (physical structure):

  • SEQUENTIAL — records stored one after another. Must be read in order.
  • INDEXED (VSAM KSDS) — has a key index allowing random access by key.
  • RELATIVE — records accessed by relative record number.

Access Mode (how the program reads/writes):

  • SEQUENTIAL — process records in physical order (read next, write next)
  • RANDOM — access individual records by key or relative number
  • DYNAMIC — can switch between sequential and random within the same program

Common combinations:

  • Sequential file + Sequential access = flat file batch processing
  • Indexed (VSAM KSDS) + Random = online-style lookup (find customer by ID)
  • Indexed (VSAM KSDS) + Dynamic = read a range starting at a key, then continue sequentially

File operations: OPEN (INPUT/OUTPUT/I-O/EXTEND), READ (NEXT/INTO), WRITE, REWRITE (update in place), DELETE (from VSAM), CLOSE, START (position to a key in VSAM).


Procedure Division and Logic (Questions 13–25)

Question 13: What is the difference between PERFORM and CALL?

Answer

PERFORM — transfers control to a paragraph or section within the same program, then returns:

cobol
PERFORM CALCULATE-TOTAL
PERFORM WRITE-RECORD 5 TIMES
PERFORM PROCESS-LOOP UNTIL WS-EOF = 'Y'

The paragraph/section being performed is part of the same compilation unit.

CALL — invokes a separate, independently compiled COBOL subprogram:

cobol
CALL 'SUBPROG' USING WS-INPUT-DATA WS-OUTPUT-DATA
CALL WS-PROGRAM-NAME USING BY REFERENCE WS-PARM

The called program is a separate load module. Data is passed via USING clause (BY REFERENCE — caller's storage is shared; BY CONTENT — a copy is passed; BY VALUE — value only, changes not visible to caller).

CALL...BY REFERENCE is the default and most common — the called program can modify the caller's data directly. Use BY CONTENT to protect the caller's data from modification.


Question 14: What is BY REFERENCE vs BY CONTENT vs BY VALUE in CALL?

Answer

These control how parameters are passed to a called subprogram:

BY REFERENCE (default):

  • The address of the caller's data item is passed
  • The subprogram works directly with the caller's storage
  • Changes made by the subprogram are visible to the caller
  • Most efficient (no copy)

BY CONTENT:

  • A copy of the data item is passed to the subprogram
  • The subprogram works on the copy
  • Changes are NOT visible to the caller
  • Protects the caller's data from accidental modification
  • Slightly less efficient (copy is made)

BY VALUE:

  • The value (not address) is passed
  • Used primarily for interoperability with non-COBOL programs (C, Java via JNI)
  • The called program receives the value but cannot return a modified value through this parameter
cobol
CALL 'SUBPROG' USING
    BY REFERENCE WS-SHARED-DATA
    BY CONTENT WS-READ-ONLY-PARM
    BY VALUE WS-FLAG

Question 15: What is the EVALUATE statement and when is it used?

Answer

EVALUATE is COBOL's structured equivalent of a switch/case statement — cleaner than nested IF/ELSE chains.

Simple form:

cobol
EVALUATE WS-STATUS
    WHEN 'A'
        PERFORM PROCESS-ACTIVE
    WHEN 'I'
        PERFORM PROCESS-INACTIVE
    WHEN 'P' 'Q'
        PERFORM PROCESS-PENDING
    WHEN OTHER
        PERFORM HANDLE-UNKNOWN
END-EVALUATE

Boolean form (EVALUATE TRUE):

cobol
EVALUATE TRUE
    WHEN WS-AMOUNT > 10000
        PERFORM HIGH-VALUE-PROCESS
    WHEN WS-AMOUNT > 1000
        PERFORM MID-VALUE-PROCESS
    WHEN OTHER
        PERFORM LOW-VALUE-PROCESS
END-EVALUATE

Multi-subject form:

cobol
EVALUATE WS-TYPE ALSO WS-STATUS
    WHEN 'CUST' ALSO 'A'
        PERFORM ACTIVE-CUSTOMER
    WHEN 'CUST' ALSO 'I'
        PERFORM INACTIVE-CUSTOMER
    WHEN OTHER
        PERFORM DEFAULT-HANDLING
END-EVALUATE

EVALUATE is preferred over deeply nested IFs — it is more readable, less error-prone, and maps naturally to business decision tables.


Question 16: What is the STRING and UNSTRING statement?

Answer

STRING — concatenates multiple data items or literals into a single receiving field:

cobol
STRING WS-FIRST-NAME DELIMITED BY SPACE
       ', '           DELIMITED BY SIZE
       WS-LAST-NAME   DELIMITED BY SPACE
    INTO WS-FULL-NAME
    WITH POINTER WS-PTR
    ON OVERFLOW PERFORM HANDLE-OVERFLOW
END-STRING

DELIMITED BY SPACE stops at the first space; DELIMITED BY SIZE uses the full field length.

UNSTRING — splits a single field into multiple items based on delimiters:

cobol
UNSTRING WS-CSV-LINE
    DELIMITED BY ','
    INTO WS-FIELD1
         WS-FIELD2
         WS-FIELD3
    TALLYING IN WS-FIELD-COUNT
    ON OVERFLOW PERFORM HANDLE-OVERFLOW
END-UNSTRING

UNSTRING is commonly used to parse delimited files (CSV, pipe-separated) in COBOL. The TALLYING phrase counts how many fields were extracted.


Question 17: What is the INSPECT statement?

Answer

INSPECT examines and optionally modifies a data item's contents — counting occurrences of characters or replacing characters.

INSPECT TALLYING — counts occurrences:

cobol
INSPECT WS-DATA
    TALLYING WS-COMMA-COUNT FOR ALL ','
    TALLYING WS-SPACE-COUNT FOR LEADING SPACES

INSPECT REPLACING — replaces characters:

cobol
INSPECT WS-DATA
    REPLACING ALL ',' BY ';'
    REPLACING LEADING SPACES BY ZEROS

INSPECT CONVERTING — translates character sets:

cobol
INSPECT WS-DATA
    CONVERTING 'abcdefghijklmnopqrstuvwxyz'
           TO  'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

INSPECT CONVERTING is often used to convert lowercase to uppercase, since COBOL on mainframes traditionally worked with uppercase only. The FUNCTION UPPER-CASE intrinsic function is more readable for this purpose in modern COBOL.


Question 18: What are COBOL intrinsic functions?

Answer

Intrinsic functions are built-in COBOL functions invoked with FUNCTION function-name(arguments).

Commonly used intrinsic functions:

FunctionPurpose
FUNCTION UPPER-CASE(str)Convert to uppercase
FUNCTION LOWER-CASE(str)Convert to lowercase
FUNCTION LENGTH(item)Length of a data item
FUNCTION NUMVAL(str)Convert numeric string to number
FUNCTION NUMVAL-C(str)Convert currency string to number
FUNCTION TRIM(str)Remove leading/trailing spaces
FUNCTION CURRENT-DATEReturns 21-character current date/time
FUNCTION WHEN-COMPILEDCompilation date/time
FUNCTION INTEGER-OF-DATE(date)Convert date to integer for arithmetic
FUNCTION DATE-OF-INTEGER(int)Convert integer back to date
FUNCTION MOD(x,y)Modulus
FUNCTION MAX(a,b,c...)Maximum of values
FUNCTION RANDOMRandom number 0–1

Example:

cobol
MOVE FUNCTION UPPER-CASE(WS-INPUT-NAME) TO WS-UPPERCASE-NAME
MOVE FUNCTION CURRENT-DATE(1:8) TO WS-TODAY

Question 19: What is the INITIALIZE statement?

Answer

INITIALIZE sets data items to their default values based on their PICTURE type:

  • Alphabetic (A) and alphanumeric (X) fields → spaces
  • Numeric (9, S9) fields → zeros
  • Alphabetic-edited and numeric-edited fields → spaces/zeros per edit pattern
cobol
INITIALIZE WS-WORK-AREA
INITIALIZE WS-OUTPUT-RECORD REPLACING ALPHANUMERIC BY 'N/A'
                              REPLACING NUMERIC BY -1

INITIALIZE is more concise than:

cobol
MOVE SPACES TO WS-ALPHA-FIELD
MOVE ZEROS TO WS-NUM-FIELD

Especially valuable for initialising complex group items with mixed field types. However, INITIALIZE does not initialise items within OCCURS DEPENDING ON tables to their full maximum — only up to the current DEPENDING ON value.


Question 20: What is the difference between ADD, SUBTRACT, MULTIPLY, DIVIDE and COMPUTE?

Answer

COBOL provides both English-style arithmetic verbs and the more flexible COMPUTE statement:

Arithmetic verbs:

cobol
ADD WS-A WS-B TO WS-TOTAL
ADD 1 TO WS-COUNTER
SUBTRACT WS-DISCOUNT FROM WS-PRICE GIVING WS-NET
MULTIPLY WS-QTY BY WS-PRICE GIVING WS-EXTENDED
DIVIDE WS-TOTAL BY WS-COUNT GIVING WS-AVERAGE REMAINDER WS-REM

COMPUTE — handles complex expressions:

cobol
COMPUTE WS-RESULT = (WS-A + WS-B) * WS-C / WS-D - WS-E
COMPUTE WS-COMPOUND = WS-PRINCIPAL * (1 + WS-RATE) ** WS-YEARS

** is the exponentiation operator. COMPUTE is more concise for multi-step calculations. All arithmetic statements support:

  • ON SIZE ERROR — triggers if result overflows the receiving field
  • ROUNDED — rounds the result to the receiving field's precision

Always use COMPUTE for financial calculations involving multiple operations — it reduces intermediate rounding errors.


Question 21: What is the COBOL file status code?

Answer

File status is a two-character field that COBOL sets after every file operation (OPEN, READ, WRITE, etc.) to indicate the result.

Define it in WORKING-STORAGE and associate with a file in SELECT:

cobol
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT CUSTOMER-FILE ASSIGN TO CUSTFILE
    FILE STATUS IS WS-CUST-STATUS.

WORKING-STORAGE SECTION.
01 WS-CUST-STATUS    PIC XX.

Common file status values:

StatusMeaning
00Successful
10End of file (sequential READ)
22Duplicate key (VSAM write)
23Record not found (random READ)
35File not found (OPEN)
39DCB conflict (OPEN)
46READ attempted on closed file
97OPEN successful but file was not closed properly

Always check file status after every I/O operation in production code. 10 on a sequential READ is the normal end-of-file signal (not an error).


Question 22: How does COBOL handle error conditions — ON SIZE ERROR, INVALID KEY, AT END?

Answer

COBOL provides declarative error handlers built into the syntax of each statement:

ON SIZE ERROR (arithmetic):

cobol
COMPUTE WS-RESULT = WS-A * WS-B
    ON SIZE ERROR PERFORM HANDLE-OVERFLOW
    NOT ON SIZE ERROR PERFORM CONTINUE-PROCESSING
END-COMPUTE

AT END (sequential file READ):

cobol
READ INPUT-FILE INTO WS-RECORD
    AT END MOVE 'Y' TO WS-EOF-FLAG
    NOT AT END PERFORM PROCESS-RECORD
END-READ

INVALID KEY (indexed/relative file access):

cobol
READ CUSTOMER-FILE INTO WS-CUST-REC
    KEY IS WS-CUST-ID
    INVALID KEY PERFORM CUSTOMER-NOT-FOUND
    NOT INVALID KEY PERFORM PROCESS-CUSTOMER
END-READ

Modern practice also checks the FILE STATUS code after every I/O for more specific error information. The USE AFTER ERROR declarative (DECLARATIVES section) provides a catch-all handler for file errors.


Question 23: What is the DECLARATIVES section in COBOL?

Answer

DECLARATIVES is an optional section at the beginning of the PROCEDURE DIVISION that defines error handlers called automatically when specific events occur.

cobol
PROCEDURE DIVISION.
DECLARATIVES.
INPUT-ERROR SECTION.
    USE AFTER STANDARD ERROR PROCEDURE ON INPUT-FILE.
    HANDLE-INPUT-ERROR.
        DISPLAY 'Input error: ' WS-INPUT-STATUS
        PERFORM ABORT-JOB.
        
OUTPUT-ERROR SECTION.
    USE AFTER STANDARD ERROR PROCEDURE ON OUTPUT.
    HANDLE-OUTPUT-ERROR.
        DISPLAY 'Output error'
        PERFORM ABORT-JOB.
END DECLARATIVES.

MAIN-SECTION SECTION.
MAIN-PARA.
    ...

USE AFTER STANDARD ERROR PROCEDURE is triggered when a file operation fails (non-zero file status not otherwise handled by INVALID KEY or AT END clauses). DECLARATIVES can also handle debugging events with USE FOR DEBUGGING.

Declarative sections end with END DECLARATIVES. Execution of the main procedure follows.


Question 24: What is SORT in COBOL (as opposed to JCL SORT)?

Answer

COBOL has a built-in SORT verb that sorts a file or table within the program itself, without requiring a separate JCL SORT step.

Sort a file:

cobol
SORT SORT-WORK-FILE
    ON ASCENDING KEY SR-CUSTOMER-ID
    ON DESCENDING KEY SR-DATE
    USING INPUT-FILE
    GIVING OUTPUT-FILE

Sort with INPUT PROCEDURE and OUTPUT PROCEDURE (for filtering/transforming during sort):

cobol
SORT SORT-WORK-FILE
    ON ASCENDING KEY SR-AMOUNT
    INPUT PROCEDURE IS FILTER-INPUT-RECORDS
    OUTPUT PROCEDURE IS WRITE-SORTED-OUTPUT

In the INPUT PROCEDURE, use RELEASE (instead of WRITE) to pass records to the sort. In OUTPUT PROCEDURE, use RETURN (instead of READ) to retrieve sorted records.

The sort file (SORT-WORK-FILE) must be defined in FILE SECTION with SD (Sort Description) instead of FD, and a corresponding SORTWK DD in the JCL (or DFSORT handles it automatically).


Question 25: What are COBOL intrinsic date functions and why are they important?

Answer

Date arithmetic in COBOL is handled via integer-based intrinsic functions to avoid calendar complexity:

cobol
*> Convert Gregorian date (YYYYMMDD) to integer
COMPUTE WS-INT-DATE1 = FUNCTION INTEGER-OF-DATE(WS-DATE-1)
COMPUTE WS-INT-DATE2 = FUNCTION INTEGER-OF-DATE(WS-DATE-2)

*> Calculate days between dates
COMPUTE WS-DAYS-DIFF = WS-INT-DATE2 - WS-INT-DATE1

*> Add 30 days to a date
COMPUTE WS-NEW-INT = WS-INT-DATE1 + 30
COMPUTE WS-NEW-DATE = FUNCTION DATE-OF-INTEGER(WS-NEW-INT)

FUNCTION CURRENT-DATE returns a 21-character string:

  • Positions 1–4: year, 5–6: month, 7–8: day, 9–10: hours, 11–12: minutes, 13–14: seconds, 15–16: hundredths, 17: GMT offset sign, 18–19: GMT hours, 20–21: GMT minutes

These functions were crucial for the Year 2000 remediation effort and remain essential for any date-sensitive financial or scheduling logic.


DB2 Embedded SQL and Advanced Topics (Questions 26–40)

Question 26: How is DB2 SQL embedded in COBOL?

Answer

DB2 SQL statements are embedded within COBOL code using the EXEC SQL...END-EXEC delimiter. The COBOL source is first processed by the DB2 Precompiler (or COBOL with integrated DB2 syntax support), which replaces SQL with COBOL CALL statements.

cobol
WORKING-STORAGE SECTION.
    EXEC SQL
        INCLUDE SQLCA
    END-EXEC.
    
    EXEC SQL
        DECLARE CUST-CURSOR CURSOR FOR
            SELECT CUST-ID, CUST-NAME, BALANCE
            FROM CUSTOMER
            WHERE STATUS = :WS-STATUS-PARM
            ORDER BY CUST-NAME
    END-EXEC.

PROCEDURE DIVISION.
    EXEC SQL
        OPEN CUST-CURSOR
    END-EXEC.
    
    PERFORM UNTIL SQLCODE = +100
        EXEC SQL
            FETCH CUST-CURSOR
            INTO :WS-CUST-ID, :WS-CUST-NAME, :WS-BALANCE
        END-EXEC
        IF SQLCODE = 0
            PERFORM PROCESS-CUSTOMER
        END-IF
    END-PERFORM.

Host variables (COBOL data items used in SQL) are prefixed with a colon (:). SQLCA (SQL Communication Area) provides SQLCODE and SQLERRM after each SQL statement.


Question 27: What is SQLCA and what is SQLCODE?

Answer

SQLCA (SQL Communication Area) is a data structure included in every DB2 COBOL program that holds information about the most recent SQL statement's execution. It is included with EXEC SQL INCLUDE SQLCA END-EXEC.

SQLCODE is the key field in SQLCA:

SQLCODEMeaning
0Successful execution
+100Row not found (SELECT INTO, FETCH at end of cursor)
-803Duplicate key (INSERT violation)
-805Package not found in DB2 (program not bound)
-811More than one row returned by SELECT INTO
-904Resource unavailable (table locked)
-911Deadlock or timeout — transaction rolled back
-922Authorisation error

SQLERRM contains a text description of the error.

After every SQL statement, check SQLCODE:

cobol
EXEC SQL
    SELECT ... INTO ...
END-EXEC
EVALUATE SQLCODE
    WHEN 0   PERFORM PROCESS-ROW
    WHEN +100 PERFORM NO-DATA-FOUND
    WHEN OTHER PERFORM SQL-ERROR-HANDLER
END-EVALUATE.

Question 28: What is a DB2 cursor and when is it used?

Answer

A cursor is a named query result set that allows a COBOL program to process multiple rows returned by a SELECT statement, one row at a time.

Cursor lifecycle:

  1. DECLARE — define the query (compile time)
  2. OPEN — execute the query, position before first row
  3. FETCH — retrieve next row into host variables
  4. CLOSE — release the cursor
cobol
EXEC SQL
    DECLARE ORDER-CURSOR CURSOR FOR
        SELECT ORDER-ID, AMOUNT, STATUS
        FROM ORDERS
        WHERE CUST-ID = :WS-CUST-ID
        FOR READ ONLY
END-EXEC.

EXEC SQL OPEN ORDER-CURSOR END-EXEC.
PERFORM UNTIL SQLCODE = +100
    EXEC SQL
        FETCH ORDER-CURSOR INTO :WS-ORD-ID, :WS-AMT, :WS-STAT
    END-EXEC
    IF SQLCODE = 0
        PERFORM PROCESS-ORDER
    END-IF
END-PERFORM.
EXEC SQL CLOSE ORDER-CURSOR END-EXEC.

FOR READ ONLY on the cursor declaration allows DB2 to optimise (no locking, no update capability). FOR UPDATE OF column enables positioned updates/deletes via WHERE CURRENT OF cursor-name.


Question 29: What is the difference between SELECT INTO and a cursor?

Answer

SELECT INTO retrieves exactly one row directly into host variables:

cobol
EXEC SQL
    SELECT CUST-NAME, BALANCE
    INTO :WS-NAME, :WS-BALANCE
    FROM CUSTOMER
    WHERE CUST-ID = :WS-CUST-ID
END-EXEC.
  • SQLCODE = 0: row found
  • SQLCODE = +100: no row found (not an error — check for it)
  • SQLCODE = -811: more than one row returned — program error, query must return at most 1 row

Cursor retrieves multiple rows iteratively via FETCH.

Use SELECT INTO when:

  • The query logically returns one row (lookup by primary key)
  • You need a single aggregated value (COUNT, SUM)

Use a cursor when:

  • The query can return zero to many rows
  • You need to process each row individually

Attempting SELECT INTO on a multi-row result set causes SQLCODE -811 — always use a cursor if there's any possibility of multiple rows.


Question 30: What is DB2 COMMIT and ROLLBACK in COBOL?

Answer

COMMIT and ROLLBACK control transaction boundaries in DB2:

EXEC SQL COMMIT END-EXEC — makes all changes since the last COMMIT permanent and releases locks.

EXEC SQL ROLLBACK END-EXEC — undoes all changes since the last COMMIT and releases locks.

Best practices for batch COBOL:

cobol
PERFORM PROCESS-RECORDS UNTIL WS-EOF = 'Y'

PROCESS-RECORDS.
    PERFORM READ-RECORD
    IF NOT WS-EOF
        PERFORM UPDATE-DATABASE
        ADD 1 TO WS-RECORDS-PROCESSED
        IF WS-RECORDS-PROCESSED >= WS-COMMIT-INTERVAL
            EXEC SQL COMMIT END-EXEC
            MOVE 0 TO WS-RECORDS-PROCESSED
        END-IF
    END-IF.

Commit frequency: commit too rarely → large rollback segments, long lock holds, deadlock risk. Commit too often → overhead from repeated commit overhead. Common intervals: every 1,000–10,000 rows for bulk batch processing.

If a DB2 deadlock or timeout occurs (SQLCODE -911), z/OS automatically rolls back the current transaction unit — the program must handle this and restart from the last committed point.


Question 31: What is a NULL indicator in DB2 COBOL?

Answer

SQL NULL means "no value" — it is not zero, not spaces, not anything. COBOL host variables cannot directly represent NULL. Null indicators are COBOL PIC S9(4) COMP fields that communicate NULL status between COBOL and DB2.

Declaration:

cobol
05 WS-AMOUNT          PIC S9(9)V99 COMP-3.
05 WS-AMOUNT-IND      PIC S9(4) COMP.

Usage in FETCH:

cobol
EXEC SQL
    FETCH CURSOR INTO :WS-AMOUNT :WS-AMOUNT-IND
END-EXEC.
IF WS-AMOUNT-IND = -1
    DISPLAY 'AMOUNT IS NULL'
ELSE
    DISPLAY WS-AMOUNT
END-IF.

Null indicator values:

  • -1 — column value is NULL (WS-AMOUNT is undefined/unreliable)
  • 0 — column has a value (WS-AMOUNT is valid)
  • > 0 — value was truncated (for variable-length strings)

For INSERT/UPDATE, set the indicator to -1 to insert NULL, or 0 to use the COBOL field's value.


Question 32: What is the difference between static and dynamic SQL in COBOL?

Answer

Static SQL: SQL statements are fixed at compile time, precompiled into the DB2 DBRM (Database Request Module), and bound into a Package/Plan before execution. DB2 creates an access path at bind time.

Advantages: access path determined once (fast execution), syntax errors caught at compile/bind time, no runtime parsing overhead.

cobol
EXEC SQL
    SELECT CUST-NAME INTO :WS-NAME
    FROM CUSTOMER WHERE CUST-ID = :WS-ID
END-EXEC.

Dynamic SQL: SQL is built as a character string at runtime and prepared/executed during program execution.

cobol
MOVE 'SELECT COUNT(*) FROM ' TO WS-SQL-STMT
STRING WS-SQL-STMT WS-TABLE-NAME INTO WS-FULL-SQL
EXEC SQL PREPARE STMT FROM :WS-FULL-SQL END-EXEC.
EXEC SQL EXECUTE STMT INTO :WS-COUNT END-EXEC.

Advantages: flexible (table names, WHERE clauses can vary), needed for ad-hoc query tools and report generators. Disadvantages: access path determined at runtime, higher CPU overhead, SQL errors only caught at runtime.

Most batch COBOL uses static SQL. Dynamic SQL is used in interactive tools, generic query programs, and where the table or column names are not known until runtime.


Question 33: What is the WORKING-STORAGE vs FILE SECTION for record processing?

Answer

FILE SECTION defines the record buffer directly in the I/O buffer. When you READ a record, the data goes directly into the FILE SECTION record area.

WORKING-STORAGE defines a separate copy of the record layout for program processing.

Best practice — use READ INTO / WRITE FROM:

cobol
FILE SECTION.
FD INPUT-FILE.
01 INPUT-RECORD         PIC X(100).

WORKING-STORAGE SECTION.
01 WS-INPUT-RECORD.
   05 WS-CUST-ID        PIC X(10).
   05 WS-CUST-NAME      PIC X(30).
   ...

PROCEDURE DIVISION.
    READ INPUT-FILE INTO WS-INPUT-RECORD
        AT END MOVE 'Y' TO WS-EOF
    END-READ.
    
    WRITE OUTPUT-RECORD FROM WS-OUTPUT-REC.

READ INTO copies the I/O buffer to WORKING-STORAGE after the read. WRITE FROM copies WORKING-STORAGE to the I/O buffer before the write.

Advantages: you can manipulate WS-INPUT-RECORD freely without interfering with the I/O buffer; the FILE SECTION record can remain a single PIC X field.


Question 34: What is COBOL structured programming and what are its benefits?

Answer

Structured COBOL uses end-scope terminators (END-IF, END-PERFORM, END-READ, END-EVALUATE, etc.) to create explicit scope, making code easier to read and maintain.

Old style (period-delimited scopes):

cobol
IF A > B
    PERFORM PROCESS-A
    IF B > C
        PERFORM PROCESS-B
    END-IF.

A single misplaced period ends all open scopes — a notorious source of bugs.

Structured (scope terminators):

cobol
IF A > B
    PERFORM PROCESS-A
    IF B > C
        PERFORM PROCESS-B
    END-IF
END-IF.

Benefits:

  • Explicit scope — no ambiguity about where an IF ends
  • Nested logic is clearly visible
  • A misplaced period is a compile error, not a silent logic bug
  • Supports inline PERFORM (code directly within PERFORM...END-PERFORM)
  • More readable for multi-programmer teams and maintenance

Modern COBOL shops mandate structured style. Legacy code using period-terminated sentences is a maintenance hazard.


Question 35: What is the LOCAL-STORAGE SECTION?

Answer

LOCAL-STORAGE is a COBOL section (part of DATA DIVISION) where data is automatically re-initialised on every CALL to the program.

Contrast:

  • WORKING-STORAGE: initialised once when the program is first loaded. Values persist between calls.
  • LOCAL-STORAGE: initialised to the VALUE clauses (or default zeros/spaces) on every call entry.
cobol
LOCAL-STORAGE SECTION.
01 LS-WORK-AREA.
   05 LS-COUNTER     PIC 9(5) VALUE ZEROS.
   05 LS-TEMP-STRING PIC X(50) VALUE SPACES.

LOCAL-STORAGE is critical for re-entrant programs — programs that may be called concurrently by multiple tasks (threads). WORKING-STORAGE is not thread-safe (shared between all callers). LOCAL-STORAGE is allocated per-call and therefore thread-safe.

Used in: CICS transaction programs (each transaction gets its own LOCAL-STORAGE), multi-threaded batch environments, and recursive COBOL programs.


Question 36: What are the differences between OPEN modes: INPUT, OUTPUT, I-O, EXTEND?

Answer

ModeDescriptionOperations allowed
INPUTOpen for reading onlyREAD
OUTPUTOpen for writing (creates/overwrites)WRITE
I-OOpen for both reading and updatingREAD, WRITE, REWRITE, DELETE
EXTENDOpen to append records to end of sequential fileWRITE (appends)

Key points:

  • OUTPUT creates the file if it doesn't exist; if it exists, it is overwritten (DISP=OLD or DISP=MOD in JCL)
  • EXTEND requires the file to already exist; new records are added after the last existing record (DISP=MOD in JCL)
  • I-O on sequential files allows REWRITE (update the last record read) but not random updates
  • I-O on VSAM KSDS allows random READ, WRITE, REWRITE, and DELETE

For VSAM random update:

cobol
OPEN I-O VSAM-FILE
READ VSAM-FILE INTO WS-REC KEY IS WS-KEY
    INVALID KEY PERFORM KEY-NOT-FOUND
END-READ
MOVE NEW-DATA TO WS-REC-FIELD
REWRITE VSAM-RECORD FROM WS-REC
    INVALID KEY PERFORM REWRITE-FAILED
END-REWRITE

Question 37: What is a COBOL subprogram and how are parameters passed?

Answer

A COBOL subprogram (called module) is a separately compiled COBOL program invoked via CALL. The calling program passes data via the USING clause; the subprogram receives it in its LINKAGE SECTION.

Calling program:

cobol
WORKING-STORAGE SECTION.
01 WS-INPUT-DATA     PIC X(100).
01 WS-RETURN-CODE    PIC S9(4) COMP.

PROCEDURE DIVISION.
    CALL 'SUBPROG' USING WS-INPUT-DATA WS-RETURN-CODE.
    IF WS-RETURN-CODE NOT = 0
        PERFORM HANDLE-ERROR
    END-IF.

Called subprogram (SUBPROG):

cobol
LINKAGE SECTION.
01 LS-INPUT-DATA     PIC X(100).
01 LS-RETURN-CODE    PIC S9(4) COMP.

PROCEDURE DIVISION USING LS-INPUT-DATA LS-RETURN-CODE.
    *> process LS-INPUT-DATA
    MOVE 0 TO LS-RETURN-CODE.
    STOP RUN.

STOP RUN in a subprogram terminates the entire job. Use GOBACK or EXIT PROGRAM instead — these return control to the caller while keeping the caller running.


Question 38: What is the difference between STOP RUN, GOBACK, and EXIT PROGRAM?

Answer

StatementBehaviour in main programBehaviour in subprogram
STOP RUNTerminates the jobTerminates the entire job (not just the subprogram) — dangerous in subprograms
GOBACKTerminates the program (same as STOP RUN in main)Returns control to the calling program
EXIT PROGRAMNo effect in main programReturns control to the calling program

Best practice:

  • Use GOBACK in all programs — it behaves correctly whether the program is a main program or a subprogram
  • Never use STOP RUN in a subprogram — if the subprogram is called from a mainline COBOL program (or CICS), it will abruptly terminate the entire address space
cobol
*> Universal good practice — works correctly everywhere:
GOBACK.

Question 39: What is the COBOL CICS interface?

Answer

CICS (Customer Information Control System) is the online transaction processing middleware on IBM mainframes. COBOL CICS programs use the EXEC CICS...END-EXEC interface to interact with CICS services.

Common EXEC CICS commands:

cobol
*> Read from terminal screen
EXEC CICS RECEIVE MAP('MAPNAME') MAPSET('MAPSET') INTO(WS-SCREEN)
END-EXEC.

*> Write to terminal screen
EXEC CICS SEND MAP('MAPNAME') MAPSET('MAPSET') FROM(WS-SCREEN) ERASE
END-EXEC.

*> Read a VSAM file via CICS file control
EXEC CICS READ FILE('CUSTFILE') INTO(WS-CUST-REC)
    RIDFLD(WS-CUST-ID) LENGTH(WS-REC-LEN)
    RESP(WS-RESP)
END-EXEC.

*> End transaction
EXEC CICS RETURN END-EXEC.

CICS COBOL programs do not use normal file I/O statements (OPEN/READ/WRITE/CLOSE) for VSAM files — all file access goes through EXEC CICS commands. Local-Storage is used instead of Working-Storage for thread safety across concurrent transactions.


Question 40: What is performance tuning in COBOL — key techniques?

Answer

Key COBOL performance techniques:

  1. Use COMP-3 (Packed Decimal) for all arithmetic fields — faster than DISPLAY and exact decimal
  2. Use COMP (Binary) for counters, subscripts, and loop variables
  3. Minimise I/O — buffer large batches, avoid random I/O on sequential files
  4. BLOCK CONTAINS 0 RECORDS — lets z/OS choose optimal block size
  5. Read INTO / Write FROM — avoids unnecessary data movement between sections
  6. Avoid unnecessary MOVE — don't move data that isn't needed
  7. SEARCH ALL over SEARCH — binary search is O(log n) vs O(n)
  8. Minimise DB2 SQL calls — bulk fetch with FETCH FOR n ROWS; avoid SELECT inside loops
  9. COMMIT at intervals — reduces lock contention in DB2 batch
  10. Use DFSORT in JCL for sorting — faster than COBOL SORT for large files
  11. PERFORM inline — modern compilers optimise inline code better than paragraph calls
  12. Review SYSOUT and SMF records — use IBM Fault Analyzer and OMEGAMON for profiling

The biggest gains usually come from I/O reduction (blocking) and DB2 access path optimisation (proper indexes, statistics up-to-date).


Modernisation and Best Practices (Questions 41–50)

Question 41: What is COBOL modernisation and what are the main approaches?

Answer

COBOL modernisation encompasses several strategies:

  1. Rehosting / Lift-and-shift: Move COBOL applications from mainframe to distributed platforms (Linux/x86) using emulation software (Micro Focus Enterprise Server, LzLabs, NTT Data Mainstar). No code changes — same COBOL, different hardware. Reduces mainframe costs.

  2. Re-platforming: Recompile COBOL for modern open-source COBOL compilers (GnuCOBOL, OpenCOBOL). May require minor code changes. Applications run on Linux/cloud.

  3. Wrapping / API-enabling: Expose COBOL business logic as REST APIs or microservices using IBM z/OS Connect or COBOL-based web service stubs. The COBOL core is preserved; modern frontends consume it via API.

  4. Refactoring: Modernise COBOL code style (structured programming, eliminate GOTOs, add unit tests with COBOL-Check or zUnit) while staying on z/OS.

  5. Rewriting: Convert COBOL to Java, Python, or Go. Highest risk and cost — business rules encoded in decades of COBOL are often poorly documented.

Most organisations choose a hybrid: keep critical, stable batch COBOL on z/OS, API-enable it for new digital channels, and rewrite only where the cost/benefit is clear.


Question 42: What is the GOTO statement and why is it discouraged?

Answer

GO TO transfers control unconditionally to a paragraph or section label, similar to a goto in C/C++.

cobol
IF ERROR-FLAG = 'Y'
    GO TO ERROR-HANDLER
END-IF.
...
ERROR-HANDLER.
    DISPLAY 'Error occurred'
    STOP RUN.

Why GO TO is discouraged:

  • Spaghetti code: unrestricted jumps make control flow impossible to follow
  • Maintenance nightmare: changing a paragraph that is a goto target requires finding all callers
  • Testing difficulty: programs with heavy GOTO are nearly impossible to unit test
  • Structured alternatives: PERFORM, EVALUATE, IF/ELSE provide all the same logic without jumping

GO TO is still acceptable in one specific pattern: GO TO error-paragraph at the bottom of a section as a single forward jump to an error handler. Modern COBOL shops prohibit GO TO except in this pattern.

ALTER (which changes the target of a GO TO dynamically) is obsolete and never acceptable.


Question 43: What is the 77-level data item?

Answer

Level 77 declares an independent (elementary) working storage item that is not subordinate to any group item. It cannot have subordinate items.

cobol
WORKING-STORAGE SECTION.
77 WS-COUNTER         PIC S9(9) COMP VALUE ZEROS.
77 WS-EOF-FLAG        PIC X VALUE 'N'.

Level 77 items are functionally equivalent to level 01 elementary items. Modern COBOL style prefers level 01 for standalone items:

cobol
01 WS-COUNTER         PIC S9(9) COMP VALUE ZEROS.
01 WS-EOF-FLAG        PIC X VALUE 'N'.

Level 77 is considered legacy — most modern COBOL shops use 01 for all top-level items for consistency. Some coding standards prohibit 77 entirely. You will encounter it in legacy code.


Question 44: What is the COBOL REXX and how does REXX relate to mainframe COBOL?

Answer

REXX (Restructured Extended Executor) is a scripting language on IBM mainframes used for:

  • JCL automation (building and submitting jobs dynamically)
  • TSO/ISPF scripting
  • Mainframe administration
  • Glue scripts between COBOL batch jobs

REXX does not replace COBOL — they are complementary. A typical mainframe workflow might be:

  1. REXX script checks if input files exist and have records
  2. REXX builds and submits a JCL job that runs COBOL programs
  3. REXX checks the job return codes
  4. REXX routes output or sends notifications

COBOL can call REXX via IKJEFT01 in JCL, and REXX can submit COBOL jobs. In modern environments, COBOL programs can also call z/OS UNIX services and shell scripts.

For COBOL interview purposes, REXX knowledge demonstrates mainframe breadth beyond pure coding.


Question 45: What is COBOL unit testing?

Answer

Unit testing COBOL has historically been challenging due to lack of tooling, but modern frameworks now exist:

COBOL-Check (open-source): a unit test framework that allows writing test cases directly in COBOL syntax. Tests are co-located with source code.

zUnit (IBM Developer for z/OS): IBM's unit testing framework integrated into IBM Developer (Eclipse-based). Supports test stubs, mocks, and test suites.

Micro Focus Unit Testing: available in Micro Focus Enterprise Developer for COBOL on distributed platforms.

A basic test pattern:

cobol
*> Using zUnit / COBOL-Check style
TEST-CALCULATE-NET-PRICE.
    MOVE 100.00 TO WS-GROSS-PRICE
    MOVE 20.00  TO WS-DISCOUNT
    PERFORM CALCULATE-NET
    ASSERT WS-NET-PRICE EQUAL TO 80.00.

Key principles:

  • Test individual paragraphs/sections in isolation
  • Mock VSAM and DB2 I/O (avoid real I/O in unit tests)
  • Test boundary conditions (zero, maximum values, NULL indicators)
  • Use COPY REPLACING to inject test stubs for file operations

Question 46: What is a COBOL copybook and how does REPLACING work?

Answer

(Extended from Question 6 — the REPLACING clause detail)

COPY...REPLACING performs text substitution when including a copybook:

cobol
COPY CUST-LAYOUT REPLACING ==:PREFIX:== BY ==WS-ORDER==.

If CUST-LAYOUT contains:

cobol
01 :PREFIX:-RECORD.
   05 :PREFIX:-ID     PIC X(10).
   05 :PREFIX:-NAME   PIC X(30).

After REPLACING, the program sees:

cobol
01 WS-ORDER-RECORD.
   05 WS-ORDER-ID     PIC X(10).
   05 WS-ORDER-NAME   PIC X(30).

The ==...== delimiters mark the text to be substituted. This allows a single copybook to be used multiple times in the same program with different prefixes — for example, one copybook for both the input customer record and the output customer record, with different field name prefixes to avoid duplicate data-name errors.

This technique is standard in shops that have common record layouts shared across hundreds of programs.


Question 47: What is the COBOL POINTER data type and ADDRESS OF?

Answer

COBOL supports pointer data items for working with dynamic memory allocation and interfacing with C or system routines.

cobol
WORKING-STORAGE SECTION.
01 WS-PTR            USAGE IS POINTER.
01 WS-DATA-AREA      PIC X(100).

PROCEDURE DIVISION.
    SET WS-PTR TO ADDRESS OF WS-DATA-AREA
    
    CALL 'GETMAIN' USING BY VALUE 1000 RETURNING WS-PTR
    SET ADDRESS OF LINKAGE-AREA TO WS-PTR

ADDRESS OF data-item returns the virtual storage address of a COBOL data item as a pointer. SET pointer TO ADDRESS OF item assigns the address. SET ADDRESS OF linkage-item TO pointer makes a LINKAGE SECTION item point to arbitrary storage.

Used in:

  • Dynamic memory allocation (COBOL ALLOCATE/FREE in later standards)
  • Interfacing with C programs that pass pointers
  • Processing variable-length records or dynamically structured data

Pointer arithmetic is not directly supported in standard COBOL — use ADD 1 TO WS-PTR after REDEFINES with a binary integer for pointer arithmetic when needed.


Question 48: What is the difference between COBOL standards (COBOL-85, COBOL-2002, COBOL-2014)?

Answer

COBOL has evolved through several ISO/ANSI standards:

COBOL-85 (ANSI X3.23-1985):

  • End-scope terminators (END-IF, END-PERFORM, etc.)
  • EVALUATE statement
  • Improved PERFORM variants
  • Still the baseline for much legacy code

COBOL-2002 (ISO 1989:2002):

  • Object-Oriented COBOL (classes, methods, inheritance)
  • Intrinsic functions (UPPER-CASE, CURRENT-DATE, etc.)
  • Unicode support
  • POINTER and dynamic memory
  • Free-format source (no column restrictions)
  • XML GENERATE and PARSE

COBOL-2014 (ISO 1989:2014):

  • Floating-point decimal (IEEE 754 decimal)
  • Conditional expressions
  • JSON GENERATE and PARSE
  • ALLOCATE/FREE for dynamic memory
  • Improved OO features

IBM Enterprise COBOL for z/OS implements a subset of COBOL-2014 plus IBM extensions. Most mainframe shops run Enterprise COBOL 6.3+, which supports JSON, XML, UTF-8, 64-bit arithmetic, and modern structured syntax.


Question 49: How do you handle large files efficiently in COBOL batch?

Answer

Processing multi-million-record files efficiently requires:

  1. Maximise blocking: Use BLOCK CONTAINS 0 RECORDS (let z/OS optimise) or explicitly set large BLKSIZE to reduce I/O operations.

  2. Sequential processing: Avoid random I/O lookups within a sequential loop. Pre-sort lookup files and use a merge approach instead.

  3. Minimise data movement: Use READ INTO only if needed; direct FILE SECTION access avoids a MOVE per record.

  4. Table lookups: Load small reference tables into WORKING-STORAGE at the start and use SEARCH ALL (binary search) instead of hitting a VSAM file per record.

  5. DB2 bulk fetch: For programs with DB2 cursors, use multi-row FETCH:

cobol
EXEC SQL
    FETCH NEXT 100 ROWS FROM CURSOR
    INTO :WS-ARRAY :WS-IND-ARRAY
    FOR 100 ROWS
END-EXEC.

Reduces DB2 FETCH calls by 100x.

  1. Commit intervals: Commit every N records to balance checkpoint overhead vs lock hold time.

  2. Parallel processing: Split the file into ranges and run multiple job steps in parallel using JCL step dependencies.

  3. DFSORT for pre-sorting: Sort before processing to enable sequential instead of random access.

Frequently Asked Questions

Q: What COBOL topics are most commonly tested in technical interviews?

Interviewers for COBOL roles focus heavily on the Data Division (PIC clauses, level numbers, 88-levels, COMP variants), file handling (VSAM, FILE STATUS codes, sequential vs indexed access), the PROCEDURE DIVISION (PERFORM, EVALUATE, string handling verbs), and JCL basics (DD statements, DISP parameters, running compile and link steps). For senior roles, expect questions on CICS transaction processing, DB2 embedded SQL, subprogram linkage (CALL, LINKAGE SECTION), and performance topics like COMP-3 vs binary arithmetic.

Q: How should I explain COBOL's relevance to a non-technical interviewer?

Frame it around business impact: COBOL runs the financial infrastructure that processes trillions of dollars daily — every ATM withdrawal, wire transfer, and insurance claim settlement touches COBOL code somewhere. Mainframe COBOL systems are chosen for their reliability (five nines uptime), auditability, and performance on batch workloads that no modern language matches cost-effectively at scale. Being a COBOL developer means maintaining and extending systems that are genuinely critical to the global economy — a different value proposition than greenfield development, but a deeply important one.

Q: What is the difference between CALL BY REFERENCE and CALL BY CONTENT in COBOL?

CALL BY REFERENCE passes the address of the data item — changes the called program makes to the parameter are visible in the calling program after the call returns. CALL BY CONTENT passes a copy of the data item — the called program works on the copy and changes do not propagate back. BY REFERENCE is the default and is most common. BY CONTENT is used when you want to protect a calling program's data from modification by a subprogram, similar to passing a const argument in C.

Question 50: What questions should you ask in a COBOL interview to demonstrate expertise?

Answer

Asking good questions signals seniority and genuine interest. Strong questions to ask interviewers:

Technical depth:

  • "What COBOL standard does the shop target — Enterprise COBOL 6.x? Are you using any modern features like JSON GENERATE or UTF-8 support?"
  • "How do you handle unit testing of COBOL programs — do you use zUnit, COBOL-Check, or something else?"
  • "What is your DB2 commit strategy for large batch jobs?"

Architecture:

  • "Are you API-enabling existing COBOL logic with z/OS Connect, or keeping it purely batch?"
  • "How is the COBOL code version-controlled — Endevor, Git, something else?"

Modernisation:

  • "What is your roadmap for the COBOL estate — maintain on z/OS, rehost, or phased rewrite?"
  • "Do you have a COBOL-to-Java or COBOL-to-Python conversion initiative underway?"

Culture:

  • "What does code review look like for COBOL changes?"
  • "What does the onboarding process look like for someone coming to this codebase for the first time?"

These questions demonstrate that you think beyond syntax and care about the broader engineering practices around the COBOL ecosystem.


Summary

These 50 COBOL interview questions cover the complete range from language fundamentals through DB2 integration and modernisation strategy. To stand out in COBOL interviews:

  • Master the four divisions cold — interviewers always start here
  • Understand COMP-3 vs COMP vs DISPLAY — storage and performance implications
  • Know DB2 cursors, SQLCODE, and commit strategy — DB2/COBOL is the core enterprise pattern
  • Be able to explain COPYBOOKS and record layouts — fundamental to real-world COBOL shops
  • Have an opinion on modernisation — senior candidates are expected to understand the landscape

For hands-on practice, use IBM's free Z Trial environment, Hercules with OpenMVS, or Micro Focus Visual COBOL (community edition) to write, compile, and run real COBOL programs.


Part of the COBOL Mastery Course.