310 likes | 327 Views
Java Programming Function Introduction. Phil Tayco San Jose City College Slide version 1.1 March 19, 2019. Math Concepts. A common thought about learning software development and coding is that one must be good at mathematics
E N D
Java ProgrammingFunction Introduction Phil Tayco San Jose City College Slide version 1.1 March 19, 2019
Math Concepts A common thought about learning software development and coding is that one must be good at mathematics This is not necessarily so because as we see with sequences, selection and repetition statements, these tend towards developing logical skills One area where math and coding do tend to overlap, though, is with functions The concept is quite similar and is useful in learning how function concepts work in programming languages
Math Concepts f(x, y) = 2x + y In math, this function has an inherent sequence of steps in the formula Multiply x by 2 Take the result and add y The function completes the formula on the values of x and y and “returns” the result
Math Concepts f(2, 4) = 2(2) + 4 = 8 f(3, 2.1) = 8.1 etc. When we “call” this function, we provide values that are applied within the function to return a result Notice the second example shows that when we call the function, all that is really seen from our perspective is the final result Internally, the function multiplies 3 by 2 and adds 2.1, but what matters is that when we call it with these values, the result that comes back is 8.1
Math Concepts This is often leads to functions being thought of as “black boxes” Whomever is calling a function, they do so by name, provides value(s) and a value is returned These 3 parts are critical to identifying how functions work In general, the 3 parts of the function format are: f(x, y, …) = result We can break these into parts to formally define how they are used in coding
Math Concepts f(x, y) = result “f” here is the function name In math, a simple letter is often used. In programming, more descriptive names will be seen as more useful Using descriptive names improves readability of code Rule 1: All functions have a name
Math Concepts f(x, y) = result The variables in parentheses here imply a few things The parentheses denote the use of a function To use this function, you must provide 2 values These variables for the function are known as input parameters In programming, input parameters are more involved which we’ll discuss later The number of parameters can also vary, some functions take 1, 2, or n number of parameters In programming, some functions don’t take any at all!
Math Concepts f(x, y) = result When the function is complete, a resulting value is returned This value is referred to as the return value With all 3 parts defined in a math function, we can use the same concepts with programming: Function name Input parameters Return value
Code Functions Here’s a simple program that calculates the area of a rectangle based on user input public static void main(String[] args) { Scanner input = new Scanner(System.in); double length; double width; System.out.print(“Enter length: “); length = input.nextDouble(); System.out.print(“Enter width: “); width = input.nextDouble(); double area = length * width; System.out.printf(“Area is %.2f\n”, area); }
Code Functions There is not much fancy going on in this program – read 2 doubles from the user and use those values to calculate the area The main thing to notice here is that the action of calculating an area may be something that is common – i.e. can be potentially reused Such actions (a.k.a. “methods”) are useful to separate for reuse by other parts of the program In this example, only one line of code is representing performing an action of calculating an area Later, we’ll have actions that will require multiple lines of code so look at this approach as identifying potentially reusable actions (as opposed to using functions to “make things simpler”)
Code Functions The line that we want to replace then is: double area = length * width; System.out.printf(“Area is %.2f\n”, area); } We can move this to a separate function keeping in mind the 3 parts we discussed earlier: public static double calculateArea(double l, double w) { double area = l * w; return area; }
Code Functions public static double calculateArea(double l, double w) { double area = l * w; return area; } public static void main(String[] args) { … First, note that the function is written outside of main and starts with “public static” The exact meaning for this is for a later time For now, all functions in the same class where your main function is must start with public static just like main does
Code Functions public staticdouble calculateArea(double l, double w) { double area = l * w; return area; } “calculateArea” is the name of the function Notice we start it with a lower case letter – that is typical Java notation – you don’t have to follow it, but do note that all function names are case sensitive (CalculateArea is a different function name than calculateArea) Subsequent words in the function name start with a capital letter – underscores are okay too Because functions are performing actions, function names usually start with an action word (e.g. “calculate” and “print”)
Code Functions public staticdouble calculateArea(double l, double w) { double area = l * w; return area; } “double l” and “double w” in parentheses are the input parameters to the calculateArea function Note that l and w are essentially variable declarations with a few added rules: l and w will be initialized with the values that are coming in when the function is called. l and w are declared with data types which means the calling function must provide values that match types The order of l and w matters (first value when the function is called will go to l and the second to w) When the function ends, l and w will disappear (the scope of the input parameter variables is limited)
Code Functions public static doublecalculateArea(double l, double w) { double area = l * w; returnarea; } The “double” here is a return type This represents the type of the value that will be returned by the function (i.e. it tells the function caller what type of information to expect when the function is complete) The “return” statement is the point where the function code officially ends and the value after is what returns to the function caller The type of the value being returned must match the return type of the function – any code that appears after it will not be reached
Code Functions With the calculateArea function available, we now call it from main: public static void main(String[] args) { … double area = calculateArea(length, width); System.out.printf(“Area is %.2f\n”, area); } The sequence of actions and variable creations is important to understand “calculateArea(length, width);” means look for a function created that is named calculateArea and expects to receive two doubles as input parameters
Code Functions The input parameters in the function call must match the types of the function: public static void main(String[] args) { … double area = calculateArea(“length”, width); System.out.printf(“Area is %.2f\n”, area); } This would not call the function we wrote because this is saying call a function called calculateArea that receives a String and a double as input parameters
Code Functions The function name must also match exactly: public static void main(String[] args) { … double area = CalculateArea(length, width); System.out.printf(“Area is %.2f\n”, area); } Even though the input parameter types match, this would not call the function we wrote because this is saying call a function called CalculateArea (ours is calculateArea) When all is correct, the values that are in length and width go to the function – the main function now pauses and control goes to the function
Code Functions Let’s assume length and width had values 3.0 and 2.1 respectively public staticdouble calculateArea(double l, double w) { double area = l * w; return area; } l is now created in calculateArea and initialized with 3.0. w will have 2.1 Note that main still exists as well as its variables Its sequence of code is suspended exactly at the point where the function call was made Control will resume with main after calculateArea is complete – for now, we’re in calculateArea’s world
Code Functions public staticdouble calculateArea(double l, double w) { double area = l * w; return area; } Inside calculateArea, we execute code as normal area is declared and initialized with the values of l multiplied by w – in this case, a result of 6.3 Note that area is a variable local to the calculateArea function – just like l and w, when the function ends, area will also disappear
Code Functions public staticdouble calculateArea(double l, double w) { double area = l * w; return area; } The return statement means the end of the function and the value there is sent back What happens next is as follows: The value of 6.3 that is in area now represents the return value of the function call l, w, and area all disappear Control resumes with main and resumes at the exact point where the function call was made At that exact point, the function call is replaced with the return value
Code Functions public static void main(String[] args) { … double area = 3.1; System.out.printf(“Area is %.2f\n”, area); } The function call is now replaced with the return value and the rest of the line of code is executed – in this case, assigns 3.1 to the variable “area” main never knew variables l, w, and area existed and vice versa (calculateArea never knew length and width existed) Note both main and calculateArea both have their own declaration of the variable area – this is okay because their scope is localized to the function they were each declared in This sequence of function calls is handled in a structure called the “function call stack”
Function call stack When main starts, the context we are in is main and all variables in it are created in that world All variables in main are now actively used main input = (scanner object) length = 3.0 width = 2.1 area = ?
Function call stack When calculateArea starts, the context changes and all variables in it are the only ones active main’s variables are not in context and are essentially temporarily non-existent calculateArea l = 3.0 w = 2.1 main input = (scanner object) length = 3.0 width = 2.1 area = ?
Function call stack When calculateArea ends, the value in area is what is prepped to be returned calculateArea l = 3.0 w = 2.1 area = 6.3 main input = (scanner object) length = 3.0 width = 2.1 area = ?
Function call stack We return to main because it is the next function context on “top” of the stack The return value of 6.3 from calculateArea goes to main’s area variable main input = (scanner object) length = 3.0 width = 2.1 area = 6.3
Function Signatures Setting up functions like this enables opportunities to reuse code as needed Communication between functions is rooted with the function call – this is where the knowing how the 3 parts of a function works is critical All functions will have a function name, input parameter specification and a return type These 3 elements make up what is referred to as a “function signature” Reusing code this way is communicated to other programmers through the function signature often documented in an “Application Programmer’s Interface” (a.k.a. API) Writing your own and reusing other functions is the heart of the next level of programming
Other Function Notes Not all functions have return values public static void println(String t) This signature means the function name is “println” that takes a String as an input parameter Since the return type is “void”, this means when the function ends, no return value is expected Not all functions have input parameters too public static booleanconnectDatabase() This means the function name is “connectDatabase” with no input parameters needed and returns a boolean value
Function Summary Functions help set up code for reuse and also make the code more readable When designing overall solutions, creating functions are good areas to act as placeholders for writing code incrementally Good practice is to find existing code and find areas that can be replaced with functions More advanced use of functions will be discussed next – become familiar with reading/writing function signatures and using functions accordingly
In Class Exercise Before going to the next concepts, we will work together on a solution for this next problem Create a program that simulates rolling a 6-sided die 6,000,000 times For each die roll, the result is tracked to keep track of how many times a number occurs After all the rolls are complete, display the frequencies of each number that came up (i.e. show how many times a 1 was rolled, a 2 was rolled, etc. up to 6) Do not show the result of each roll, only simulate it and record the result – the only thing the user sees is the final report of number frequencies
Programming Exercise 6 Go back to your solution for Programming Exercise 4 and update it by creating “isPerfectCube” and “isPerfectSquare” functions The functions should take an integer and return true if the given number is a prime number (or return false if it isn’t) Update the main program to use the functions appropriately If you already did this for your exercise 4, make sure I see it so I can mark credit appropriately