M e t h o d s a n d P a r a m e t e r s

Similar documents
AP CS Unit 3: Control Structures Notes

Introduction to Computer Science Unit 2. Notes

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Java Bytecode (binary file)

Lecture 5: Methods CS2301

Selected Questions from by Nageshwara Rao

DATA TYPES AND EXPRESSIONS

Introduction to Computer Science Unit 2. Notes

Methods Summer 2010 Margaret Reid-Miller

CS110: PROGRAMMING LANGUAGE I

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

4. Java Project Design, Input Methods

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Introduction to Computer Science Unit 2. Exercises

CS110D: PROGRAMMING LANGUAGE I

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

A Foundation for Programming

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CIS133J. Working with Numbers in Java

AP Computer Science Unit 1. Programs

CS-201 Introduction to Programming with Java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Math Modeling in Java: An S-I Compartment Model

Computational Expression

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Full file at

Object-Oriented Programming

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

MODULE 02: BASIC COMPUTATION IN JAVA

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

PROGRAMMING STYLE. Fundamentals of Computer Science I

Introduction to Classes and Objects. David Greenstein Monta Vista High School

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

CS115 Principles of Computer Science

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Conditionals, Loops, and Style

Lab 9: Creating a Reusable Class

CS1150 Principles of Computer Science Methods

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Lecture #6-7 Methods

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 4 Defining Classes I

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Full file at

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

PROGRAMMING FUNDAMENTALS

CS11 Java. Fall Lecture 1

CS 231 Data Structures and Algorithms, Fall 2016

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

The Math Class. Using various math class methods. Formatting the values.

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CS111: PROGRAMMING LANGUAGE II

( &% class MyClass { }

CS1150 Principles of Computer Science Methods

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Lec 3. Compilers, Debugging, Hello World, and Variables

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Final Exam Practice. Partial credit will be awarded.

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

CHAPTER 7 OBJECTS AND CLASSES

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

4 Programming Fundamentals. Introduction to Programming 1 1

CHAPTER 7 OBJECTS AND CLASSES

Building Java Programs Chapter 2

Chapter 2: Programming Concepts

Chapter 02: Using Data

Chapter 2: Using Data

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

CS 302: Introduction to Programming

APCS Semester #1 Final Exam Practice Problems

Objectives. In this chapter, you will:

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

Computer Science is...

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

University of Palestine. Mid Exam Total Grade: 100

Class 9: Static Methods and Data Members

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Transcription:

M e t h o d s a n d P a r a m e t e r s Objective #1: Call methods. Methods are reusable sections of code that perform actions. Many methods come from classes that are built into the Java language. For example, the println method is found in the System class that is automatically available in any Java program. It allows you to display a string with the statement System.out.println("hello world"); The pow method comes from the Math class and can be used in any Java program as in: System.out.println(Math.pow(3, 2)); // 9 is displayed since 3 squared equals 9 There are some classes that exist in Java for the sole purpose of containing handy, reusable methods. Such classes are called utility classes. Math, Integer, and Double are examples of utility classes since they contain so many useful methods including Math.pow(), Math.sqrt(), Math.abs(), Integer.parseInt(), Double.parseDouble() and even constants like Math.PI, Integer.MIN_VALUE, and Integer.MAX_VALUE. You should research methods like the those explained above in the Java API to learn how they work and to find other useful ones. Objective #2: Identify the parts of a method. Very often, as a programmer, it is wise to create your own method. Here is an example of a method that you might create for use in a program: public double computeareatriangle(int base, int height) return base * height / 2.0; The name that the programmer chose for the method above is computeareatriangle. The name of a method should begin with a lowercase letter. The name of a method should be descriptive as to its purpose. Very often, a verb is used in the name of the method to help describe what the method does since the purpose of a method is usually to perform an action. The first line of a method is called the method header as in public double computeareatriangle(int base, int height) The body of the method is the part of the method that is included in its required curly braces as in return base * height / 2.0; The method name, parameters, and body statements together are called the method's definition. Here is the complete definition of the method above. Technically the public double part of the header is not considered to be in the method's definition. computeareatriangle(int base, int height)

return base * height / 2.0; The parameter list for a method is the list of parameters that may be found in the set of parentheses in the method header. The parameter list for the computeareatriangle method above is int base, int height Note that it is not accurate to call this a "variable list" because they are technically not considered to be variables but rather parameters. And sometimes, we call them formal parameters since they are really just formal placeholders for actual values (like the numbers 5 and 10) that will eventually be passed into the method. The method signature of a method is the name of the method along with its parameter list. So the method signature of the computeareatriangle method above is computeareatriangle(int base, int height) and really the formal parameter names are not that important as far as the method signature goes so you can also say that the method signature is computeareatriangle(int, int) Methods should generally be made public especially in this introductory programming course. So the method header should always begin with the keyword public. While it is possible to also use private and protected as scope modifiers for methods. And, by default, if a scope modifier keyword is not used in a method header, than the scope access is considered to be package level that typically gives a class access to any method within a class file contained in the same folder or directory as the file. The use of the data type double in the method header is called the method's return type. If a method includes a return statement, then the data type (usually int, double, or String in this AP Computer Science course) must be typed in the header. If there is no return statement (or the return statement is empty as in return; ) then the keyword void must be used. Examples, public int computesum(int num1, int num2) return num1 + num2; public double computetax(double price, double taxrate) return price * taxrate; public String makefancyname(string name) return "**** " + name + " ******"; public void displayfancyname() System.out.println("**** " + name + " ******"); public void displayfancyname() System.out.println("**** " + name + " ******"); return; // this statement is optional since no value is actually being returned

Methods that are defined (i.e. typed out) and included in the same class file where they are meant to be used are often referred to as static methods. The keyword static must be used in their header. So the keyword static could have been used in many of the examples above as in public static double computeareatriangle(int base, int height) return base * height / 2.0; At this time in our AP Computer Science course do not worry about this use of the keyword static. You will understand when to use it or not later. For now, see the instructor if you have any questions in exercises or programming assignments. Objective #3: Call methods that are implemented in the same class file. A call statement is a statement that makes use of a method. To make use of a method means to call a method. Examples are System.out.println(Math.pow(3, 2)); area = computeareatriangle(10, 2); displayfancyname("smith"); Methods are typically typed out and defined in a class file below the main method. The following program begins with the execution of the main method. But the 3 call statements in the main method invoke and execute the other three methods. It doesn't matter in what order the methods are typed out in the class. The call statements execute in the order that they are listed. public class MethodsDemo1 public static void main(string[] args) drawhead(); drawbody(); drawlegs(); // end of main public static void drawhead() System.out.println("0"); public static void drawbody() System.out.println("I"); public static void drawlegs() System.out.println("/\\");

// end of MethodsDemo1 Objective #3: Pass parameters to methods. You can pass parameters to methods with a call statement. In the following example, an int and a String are passed from one method to another. public class MethodsDemo2 public static void main(string[] args) drawman(3, "Bob"); // end of main public static void drawman(int num, String name) for (int i = 0; i < num; i++) drawhead(); drawbody(); drawlegs(); // end of for System.out.println(name); // end of drawman public static void drawhead() System.out.println("0"); // end of drawhead public static void drawbody() System.out.println("I"); // end of drawbody public static void drawlegs() System.out.println("/\\"); // end of drawlegs // end of MethodsDemo2 Notice the use of inline "end of" comments that are useful in keeping track of where one method, loop, or class ends and another one begins. Also notice that blank lines that are placed around loops and methods to make the code more readable. The value 3 in the call statement automatically matches up with the formal parameter num in the drawman method header while the string literal "Bob" matches up with the formal parameter name. Objective #4: Return values from methods. The methods above are examples of void methods because they have the return type void. They do not return values. In the following examples, each method returns a value such as an int, double, boolean or String.

public class MethodsDemo3 public static void main(string[] args) int sum = 0; sum = addthem(3, 4); System.out.println(addThem(5, 6)); int x = 7, y = 8; System.out.println(addThem(x, y)); System.out.println(isEven(5)); System.out.println(firstLetter("Wyomissing")); System.out.println(addThem(addThem(1, 2), addthem(3, 4))); System.out.println(getRandomDecimalNumber()); public static int addthem(int num1, int num2) return num1 + num2; public static boolean iseven(int num) if (num % 2 == 0) // checking to see if num is evenly divisible by 2 or not return true; return false; public static String firstletter(string word) return word.substring(0, 1); public static double getrandomdecimalnumber() return Math.random(); // returns a random decimal number between 0.0 and.9999 // end of MethodsDemo3 Even though you may not have studied if statements or the random method, the methods above work as their names imply. The data type that is returned by each method is typed after the keyword static and before the name of the method. Objective #5: Write your own user defined static methods. It is proper style to begin the names of methods with lowercase letters as in computetax or

displayfancyname. To implement a method means to type code into the body of that method so the method knows how to execute when it is called. Objective #6: Make use of overloaded methods. It is possible to include two methods with the same name in a class. When this occurs the methods are called overloaded methods. Methods are overloaded when they have the same name but a different parameter lists. For example, you can have one method in a Bug class named move that accepts no parameters and another method that is also named move but that accepts one parameter as in the following example. public void move() and public void move(int amount) Or two methods could have the same number of parameters but with a different order of parameter data types as in public void move(int x, double y) and public void move(double x, int y) Two parameter lists can be different from each other by: having a different number of parameters, having parameters with different data types, or by having the same number of parameters but with the data types in a different order. So the following methods could both be used in a Bug class even though they have the same name. Since they have different parameter lists, they are treated as two different methods. public void move() myx = myx + 5; public void move(int amount) myx = myx + amount; Even though they have different return types, the following methods are considered to have the same parameter lists so they would cause a compile error and are not examples of properly overloaded methods. public void move(int amount, int start) myx = start + amount;

public int move(int amount, int start) return myx + amount + start; Here are more examples of pairs of overloaded methods: int move(int amount) int move(double amount) int move(int amount, int speed) int move(int amount, double speed) int move(double amount, int speed) int move(int amount, double speed) Here are examples of methods that are not properly overloaded int move1(int amount, int speed) ' this does compile int move2(int amount, int speed) double move1(int amount, int speed) int move2(int amount, int speed) int move1(int x, int y) int move1(int a, int b) Objective #7: Use local variables within methods. Local variables can be declared and used within individual methods in a class as in this havebirthday method: public static double computetax(double price, double taxrate) double total = 0.0; total = price * taxrate; return total; Clearly though the use of the local variable num is a waste in this example since the single statement myage++; would have sufficed. public static double computetax(double price, double taxrate) return price * taxrate; A local variable MUST be initialized when it is declared inside of a method. For example, the method public static double computetax(double price, double taxrate) double total; // compile error occurs

total = price * taxrate; return total; will cause a compile error since total was not initialized. Unlike some other computer languages like Visual Basic, Java does not always initialize variables to zero. (Though Java does initialize special kinds of variables called instance variables to zero but more about that later in this course.) A local variable only has a scope of the method in which it is declared. That is, you cannot refer to a local variable in another method. public static double computetax(double price, double taxrate) double total = 0.0; total = price * taxrate; return total; public static double computeshipping(double price, double shippingrate) total = total + price * shippingrate; // compile error since total is not declared in this method return total; Once the method has executed and when the compiler reaches the method's closing curly brace, all of the method's local variables are discarded and "garbage collected". Garbage collection is an aspect of Java in which the memory occupied by unused variables is automatically reclaimed by the operating sysem as a program executes.