In Java, a function definition starts with a heading of the general form
public static Type Name(Arguments)where
Type is the type of answer that the function yields. For example, if the function produces a result of type int, then you write int just after static. The type is required.
Name is the name of the function.
Arguments tells about the arguments. For each argument, write the type of the argument followed by its name. If there are two or more arguments, separate them by commas.
For example, a function called gcf that takes two integer arguments and produces an integer result has the following heading.
public static int gcf(int x, int y)
After the heading, write a compound statement, called the function body. Inside the body, use statement
return v;to cause the function to quit running and to produce v as its value. (v can be any expression, as long as it has the right type.) Notice the semicolon at the end.
Note. The body must be a compound statement, even if it is only one line long. So write braces around it.
Note. In Java, do not write an = sign after the function heading. The body immediately follows the heading.
You can define a squaring function as follows. Java definition
public static int sqr(int x) { return x*x; }is equivalent to Cinnameg definition
Define sqr(x: Integer) : Integer by sqr(x) = x*x %DefineSo sqr(9) = 81 and sqr(5) = 25.
Java does not allow you to have several cases in a function definition. There is always just one body. To deal with cases, use an if-statement. For example, the following defines a function max(x, y) that yields the larger of two real numbers x and y. (Recall that a real number has type double in Java.)
public static double max(double x, double y) { if(x >= y) return x; else return y; }
After defining max, you will find that statement
double z = max(20.1, 18.6);makes z = 20.1.
[solve] The following function definition is not correct Java. What is wrong with it?
public static int h(int y) return y + 1;
[solve] Convert Cinnameg definition
Define f(x: Integer): Integer by f(x) = 3*x - 1 %Defineto an equivalent Java function definition. Use type int for integers.
[solve] The absolute value function can be written as follows in Cinnameg.
Define case absolute(x) = x when x >= 0 case absolute(x) = -x %DefineConvert that to an equivalent Java function definition. Assume that x has type int. (Remember that Java does not allow definition by cases. Instead, use an if-statement.
Java has functions that have similar intent to Cinnameg functions. There are differences in appearance. You can only have one body. Use statement
return E;to say that the function's answer is the value of expression E.
Use an if-statement to make a decision while a program runs and a while-statement to create a loop.
The idea behind Java if-statements and while-statement are the same as the idea behind Cinnameg If-statement and While statements, but there are differences in how you write them.