Week 13 Methods - New Era University PDF
Document Details
Uploaded by FavoriteWillow
New Era University
Tags
Related
- OOP - JAVA Object-Oriented Programming PDF
- Topic 1.6 Running Program with Objects PDF
- Java Programming: Chapter 3 Using Methods, Classes, and Objects PDF
- Concepts des langages objet - Programmation Orientée Objet - JAVA PDF
- Lecture 2 (Chapter 2) Introduction to Java Programming PDF
- DCIT 201 Programming I - Methods PDF
Summary
This document is lecture notes from New Era University on methods in Java programming. It discusses what methods are, how to create and use them, with examples. It also details method types and declarations.
Full Transcript
New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] Wee...
New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] Week 13 METHODS In this module, you will learn how to create your own methods with or without method parameters and invoke methods with returning values in the program design. Learning Outcomes: At the end of the module, the student should be able to: 1. Understand how methods implemented in Java programming; 2. Specify each element on method declaration; 3. Assign method name and explore built in method that signifies action; 4. Simulate the return values of methods. Method is nothing new to us. Remember that we already used a method in our previous examples called the main() method. In Java, we can identify methods as ( ). That’s is why the System.out.print() is also called print method.in addition to these, methods such as pow(), sqrt() etc., are considered as a built-in method or a pre-defined method that does not need a sub program to do their task. Here is the example: The program PowerAndSqrt is an example of implementing predefined method and uses class Math that is responsible for the computation. As you can see, pow() does not require any subprogram to do the task of computing the parameters (a,2) which means (a=4.0) raised to the power of exponent value (2), even the sqrt(), that returns the correct rounded positive square root of the parameter a don’t have subprograms. These New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] One goal of the method is to break a large program into small sub-programs to easily maintain as you develop a more complex programs. On our example below is a user define method: As the java interpreter implements the program Border starting from main(), the program calls first the method printBorder(). In our program, it shows that the printBorder() method will print 10 equal sign and looks like this: ========== After the program reached the closing curly brace of printBorder() method, it will go back to the main() and execute the print() which is to display the text: Java rocks! As you have noticed, printBorder() method need to be executed again. The program will find where is the method printBorder() and once found, it will execute the loop and display 10 equal sign and looks like this: ========== Then, the program terminates and the out would be: Anatomy of a Method Declaration This part will show you the parts of a method based on out example printBorder(). New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] 1. Access modifier. The class (or program) may allow other classes to use the method you have just defined. Other declarations you could use other than public are private, protected and package. Discussion of the use of private, protected and package is beyond the discussion of this content. We use these modifiers on Object Oriented Programming (OOP). For now, we will just use public modifier on all methods that we will create. 2. Method type. There are two types of methods in a java program: instance method and class method. What we have used since the start of the content is a class method. You identify the class method with the word static. Failure to include static would mean that the method you are declaring is an instance method. Again, instance method is an OOP concept that is beyond the discussion of this content. Never mind if the concept is not clear to you yet. All method type declarations we will use for this learning content will be static. 3. Return data type. Think all methods that we will define are just like a variable we are declaring at the start of the program. In declaring a variable in a program we need to define its data type. Same goes with method. It can be declared as int, double, float, char, boolean or as another class String. When you say return data type, the method needs to return a value depending on the declaration you have just defined. String declaration means return a text value to the calling method/program; double and float mean return a number with fractional value; int returns whole number; boolean returns value either true or false. When void is used New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] on method declaration, the method needs not to return anything to the calling method/program. All other data types (except for void) defined on method declaration must use a return statement within the body of the method. 4. Method name. The programmer has a liberty to name a method of one’s choice. Though, good programming practice insists that method name should connote action. This means that the first word to be used is an action word: verb. Example of these are: printBorder, calculateSalary, displayOutput, isValid, etc. 5. Parameters. If you need to pass information to a method, you need to define the list of parameters or arguments within the parenthesis. Each parameter must define its data type separated by a comma if there is more than one parameter. You don’t need to define a parameter if there is no need to pass information to the method. We will have good example for these. 6. Method body. Just like our main() method you define the scope of the method by a set of curly braces. Inside the body is where statements are located that execute the functionality of the method. Pass-by-Value Method From the term pass-by-value, the value of the parameter will pass from one method to another. To understand, consider the following code problem: Create a method-oriented program Cylinder that computes the lateral surface area and volume of the cylinder. Designate methods computeLateralArea() and computeVolume() that will facilitate the computation of its values. No System.out.println() should be seen on these methods. Use the following formulas in solving the requirements: lateralAreaCylinder = 2 * 3.1416 *radius * (radius + height); volumeCylinder = 3.1416 * radius * radius * height; diameter = 2 * radius; Sample Input/Output: Enter diameter: 2.5 New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] Enter height: 3.0 Lateral surface of the cylinder is 33.3795 Volume of the cylinder is 14.72625 To start up, create program Cylinder declaring its Scanner class with its input object and variables diameter and height as double data type. Initialize diameter and height with 0.0 value. Include the input prompts that will get the diameter and height of the cylinder. We are ready to display the surface lateral area and volume of the figure. Concatenate the corresponding texts to methods computeLateralArea() and computeVolume() to display the results by System.out.println() statement. Our program should look like this: Let us define now the structure of the two methods. computeLateralArea() must return fractional value that is why the return data type is double. Its parameters include d and h (declared double separately) that will absorb the values passed by diameter and height respectively. As we proceed on the body of the method, declare variable radius since our formula for computing the lateral area need this. Initialize radius with value 0.0. In assigning a value for radius, get the half value of diameter. New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] All data are in place to compute for the lateral area. Declare/initialize variable lateralAreaCylinder that will hold the computed values of the surface area. Assign the value for the variable with the formula guide above. Return the value with a return statement. computeVolume() will have the same structure just like the computeLateralArea(). Though we prefer to change the parameter names of the values passed, it will have the same double data type declaration. You will notice here that variable r stands for radius; h2 for height. On the values passed in main() for the method computeVolume(), diameter is already being divided with 2. It is the same formula in obtaining the radius; therefore, the value passed is already divided in a half. No more variables used in the body of the method. This is a good approach in making your program sleek by directly returning the value whatever will be the result of the mathematical operation. We have the following codes as the working program: import java.util.Scanner; public class Cylinder { public static void main(String[] args) { Scanner input = new Scanner(System.in); double diameter = 0.0, height = 0.0; System.out.print("Enter diameter: "); diameter = input.nextDouble(); System.out.print("Enter height: "); height = input.nextDouble(); System.out.println("\nLateral surface of the cylinder is " + computeLateralArea(diameter, height)); System.out.println("Volume of the cylinder is " + computeVolume(diameter/2.0, height)); } New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] public static double computeLateralArea(double d, double h) { double radius = 0.0; double lateralAreaCylinder = 0.0; radius = d / 2.0; lateralAreaCylinder = 2 * 3.1416 * radius * (radius + h); return lateralAreaCylinder; } public static double computeVolume(double r, double h2) { return 3.1416 * r * r * h2; } } Simulate: Determine the output Let us show the solution of simulation for the program below: public class CD { public static void main(String[] args) { double diameter = 120.0; double radius = 0.0; String output = ""; radius = diameter/2.0; output += "Circumference is "; output += solveCircumference(radius); output += " mm"; output += "\nSurface area of CD is "; output += solveAreaCD(solveAreaCircle(radius), solveAreaCircle((diameter*0.125)/2.0)); output += " sqr mm"; System.out.println(output); } public static double solveCircumference(double rad) { return 2.0 * 3.1416 * rad; } public static double solveAreaCircle(double r) { return 3.1416 * r * r; } public static double solveAreaCD(double outer, double inner) { return outer - inner; } } New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] Initialize diameter, radius and output with 120.0, 0.0, and a null value, respectively. radius is set with a value of 60.0 when diameter is divided by 2.0. Concatenate “Circumference is “ with the current value of output (which is empty ). The value to join with output must come from solveCircumference(). Jump to method solveCircumference() with the parameter value of radius. rad absorb the value of radius. As the return statement do the mathematical operation, it will return a value of 376.992 for solveCircumference() and concatenate again to variable output. “ mm” and “Surface area of CD is “ are added to output variable. Take note that a “\n” newline character is also included moving the text to a new line. solveAreaCD() contains two double data type parameters. On this case, before we could obtain the values of these parameters, we need to jump on method solveAreaCircle() twice to generate it. Take note that each method has different values on its parameters. First the value radius 60.0 is passed to the method achieving 11309.76. The second round of execution of the method passed a radius of 7.5 achieving a value of 176.715. outer variable absorbs 11309.76; inner gets 176.715. Performing subtraction of the two values returns 11133.045 for solveAreaCD(). Again, the value of solveAreaCD() is concatenated with variable output. The last text added to output is “ sqr mm”. Display output with System.out.println() statement. Activity: 1. Watch the method tutorials here: https://drive.google.com/file/d/1yabjikXgLzE8t_4oOx05Ey0yB0XR1fyZ/view?u sp=sharing 2. Read Chapter 5 Methods of the wiley textbook “Big Java Late Object” page 201 New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] New Era University College of Computer Studies Rm. 247-B, High School Annex B, New Era University Tel. No.: (+632) 981-4221 loc 3825 E-mail: [email protected] integers whether the second integer is a multiple of the first. The method should e second is a multiple of the first References: Jeremias C. Ezperanza (2013), My first Java Program, Lulu.com Cay S. Horstmann (2019), Brief Java: Early Objects, Enhanced eText Edition 9, Wiley Global Education US, ISBN: 9781119499138 https://www.tutorialspoint.com/java/java_methods.htm http://www.btechsmartclass.com/c_programming/C-Program-Development-Life- Cycle.html http://cssimplified.com/computer-organisation-and-assembly-language- programming/beginner-write-your-first-assembly-language-program-hello-world- explained