-
Notifications
You must be signed in to change notification settings - Fork 0
Java Functions
Adrian Patterson edited this page Nov 23, 2021
·
2 revisions
-
Functions are called to perform some sort of routine
- This routine could be adding two numbers, printing a statement, whatever you'd like!
-
We create functions so that we don't have to rewrite code
-
Functions consist of three main parts:
- A return type, arguments, and a body
- The return type tells us what type of variable the function will give us (maybe an integer or a string)
- The arguments are what we can pass to a function (maybe we pass it one integer, maybe two)
- The body defines what we do with the arguments, and what we return
- A return type, arguments, and a body
-
E.g. take a look at the following two functions
public static int add(int x, int y) { int sum = x + y; return sum; }
- Here the return type is integer, the arguments are the two integers x and y, and the body of the function adds the two arguments.
-
A function could also not return anything. In that case, we say the return type is
voidprivate static void print() { System.out.println("Hello World!"); }
- Note that this function has no return type, nor does it take any arguments! It just prints Hello World! to the terminal.
-
Finally, to invoke or call these functions, we would do the following
int sum = add(5,10); // here we assign the return value to the variable sum print(); // here we invoke a void function with no arguments