Methods - in COBOL and Java

COBOL Java
class-id Functions.
*> Pass by value (in, default), reference (in/out), and reference (out)
method-id TestFunc (x as binary-long,
                    reference y as binary-long,
                    output z as binary-long).
      add 1 to x, y
      move 5 to z
end method.

method-id InstMethod.
    declare a as binary-long = 1
    declare b as binary-long = 1
    declare c as binary-long
    invoke TestFunc(value a reference b output c)
    *> Or
    invoke self::TestFunc(a b c)
    display a space b space c

    declare total as binary-long
    *> Commas in parameter lists are optional
    set total to function sum(4 3 2 1) *> returns 10
    display total
end method.

method-id main static.
    declare i as binary-long
    set i to MySum(1 2 3 4)
    display i
    declare o = new self

    *> Parentheses are optional when there are no parameters.
    invoke o::InstMethod
    invoke SayHello("Strangelove", "Dr.")
    invoke SayHello("Madonna")
end method.

*> To create a non intrinsic variable argument list function:
method-id MySum static (params nums as binary-long occurs any)
                      returning mysum as binary-long.
    perform varying i as binary-long through nums
        add i to mysum
    end-perform
end method.

*> COBOL supports optional arguments/parameters.
*> The default value is specified with the syntax '= value'.
*> Optional parameters must be listed last.
method-id SayHello static (nam as string,
                           prefix as string = "").
      display "Greetings, " prefix space nam
end method.

end class.
public class functions
{
    // Java only allows arguments to be passed by value
    
    public static void main(String[] args)
    {
       int i = mySum(1, 2, 3, 4); 
       System.out.println(i);
    }
    
    // Use ellipses to indicate a variable argument list
    public static int mySum(int... arguments)
    {
        int sum = 0;
        for (int i : arguments)
        {
            sum += i;
        }
        return sum; 
    }
}

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