Java Functions

Functions:

public static void mySimpleFunction () { // Defining the function System.out.println("Testing"); } public static void main (String [] args) { mySimpleFunction(); // Calling/Running the function }

- A function is a group of code that can be run in other parts of the program as many times as needed

Functions that receive input:

public static void myParamFunc (String myPrm1, int myPrm2) { System.out.println("My name is " + myPrm1 + " and I am " + myPrm2 + " years old."); } public static void main (String [] args) { myParamFunc("Joey", 12); // Provide parameters when calling function }

- Parameters allow a function to run with specified values

- Parameters have to be provided in the same order that they are defined in the function definition; e.g. you can't call myParamFunc(12, "Joey")

- If a variable is provided as a parameter value such as in myParamFunc(myVar1, 12), it passes the value of the variable, so the variable will not be updated by the function and will retain its original value after the function ends (unless it is an array or object, which will be covered later)

Functions that produce output:

public static int myOutptFunc (int myPrm1) { // Replace "void" with the data type of the result return myPrm1 * 2; } public static void main (String [] args) { int myFuncResult = myOutptFunc(4); // Receieve the function output as a value }

- Functions can return a value of any data type (e.g. float, String, ...), but that type must be declared in the function definition before the function name

- The result of the function doesn't have to be stored as a variable, it could be accessed like a value, for example: System.out.println( myOutptFunc(3) );

- The data type of the result is called the return type, it must be specified before the function name

Generic Types:

public static <T> void myGenericParamFunc (T myPrm1) { // Replace parameter type with generic System.out.println( "testing: " + myPrm1 ); } public static void main (String [] args) { myGenericParamFunc(23); // Call with an int as a parameter myGenericParamFunc("blah"); // Call with a string as a parameter myGenericParamFunc(12.54); // Call with a float as a parameter }

- A generic type specified as 'T' acts as a placeholder for a variety of different data types that can be used (e.g. int, String, float, ...)

- It doesn't have to be called 'T', but whatever you call it must be specified withing the < > area specified before the function return type

Challenge

Write a function that will display a count down starting from the number passed as a parameter and stopping at 0 : e.g. "Countdown: 9", "Countdown: 8", ... (with each count on a new line)

Quiz

Completed