Example 3 - Java Calling COBOL Programs

This example demonstrates a Java program running code from a native COBOL program.

Run the following instructions from a Visual COBOL command prompt (Windows), or.

  1. Create the following COBOL file (demo3.cbl):
          $set sourceformat(variable)
           >>JAVA-CALLABLE
           program-id. "demo3" .
    
           working-storage section.
           01 i pic 9(9) comp-5.
           01 primes.
             03 pic 9(9) comp-5 occurs 10 value 2,3,5,7,11,13,17,19,23,27.
    
           linkage section.
           01 ltable1.
             03 str pic X(100) occurs 4.
           01 lint1 pic 9(9) comp-5.
           01 ltable2.
             03 int1 pic 9(9) comp-5 occurs 10.
           procedure division using ltable1 by value lint1 returning ltable2.
               perform varying i from 1 by 1 until i > 4
                   display "COBOL " i " " str(i)
               end-perform
               display "COBOL " lint1
               move primes to ltable2
           goback.
  2. Create an src3 subfolder to your current working folder.
  3. Compile the file with the necessary directives:
    cobol demo3.cbl java-output-path(src3) java-package-name(com.mycompany.demo3) java-gen-progs;

    The supporting class files are generated using the com.mycompany.demo3 package name and placed in the src3 folder.

  4. Create the required library file from the compiled object file:
    cbllink -D demo3.obj

    The COBOL library file is generated.

  5. Create the following Java source file (Demo3.java):
    import com.mycompany.demo3.*;
    
    public class Demo3
    {
        public static void main(String[] args)
        {
          String[] s = {"hello", "there", "pink", "green"};
          int int1 = 23;
          System.out.println("---------demo3---------");
          int[] i = com.mycompany.demo3.progs.demo3(s, int1);
          System.out.println("Hello from Java");
          for (int k=0; k<i.length; k++)
              System.out.println(i[k]);
    
        }
    }

    The Java code imports the namespace that the COBOL compilation used. You should also ensure that the current working folder and the src3 folder are on the CLASSPATH.

  6. Compile, and the run the Java bytecode:
    javac Demo3.java
    java Demo3

    The following output is produced:

    ---------demo3---------
    COBOL 0000000001 hello
    COBOL 0000000002 there
    COBOL 0000000003 pink
    COBOL 0000000004 green
    COBOL 0000000023
    Hello from Java
    2
    3
    5
    7
    11
    13
    17
    19
    23
    27

    The code and the output show that the Java program calls into the demo3 COBOL program when declaring the i integer array. It passes in a couple of arguments used by the COBOL code, and then the COBOL code also returns a table/array, which the Java program then displays.