Static Methods. Why use methods?

Similar documents
For example, when we first started Java programming we described the HelloWorld class:

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

CS 106 Introduction to Computer Science I

Lecture 04 FUNCTIONS AND ARRAYS

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Function Call Stack and Activation Records

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Lecture 04 FUNCTIONS AND ARRAYS

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

Shut the Box. By the time you are done with this activity, you and your team should be able to:

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Example Program. public class ComputeArea {

Repetition, Looping. While Loop

Chapter 7 User-Defined Methods. Chapter Objectives

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CS113: Lecture 4. Topics: Functions. Function Activation Records

Methods CSC 121 Fall 2016 Howard Rosenthal

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

COMP 110 Programming Exercise: Simulation of the Game of Craps

Scope of this lecture. Repetition For loops While loops

Smaller, simpler, subcomponent of program Provides abstraction

Methods CSC 121 Spring 2017 Howard Rosenthal

CS-201 Introduction to Programming with Java

Introduction to Python (All the Basic Stuff)

QUIZ. What is wrong with this code that uses default arguments?

Reliable programming

Object Oriented Methods : Deeper Look Lecture Three

CS121: Computer Programming I

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

Loops. CSE 114, Computer Science 1 Stony Brook University

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

Chapter 4: Writing Classes

CS201 Latest Solved MCQs

COMP 202 Java in one week

Chapter Goals. Contents LOOPS

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

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

CS-201 Introduction to Programming with Java

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Standard Version of Starting Out with C++, 4th Edition. Chapter 6 Functions. Copyright 2003 Scott/Jones Publishing

Fundamentals of Programming Data Types & Methods

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

STUDENT LESSON A12 Iterations

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Chapter 1 Getting Started

Appendix: Common Errors

JAVA GUI PROGRAMMING REVISION TOUR III

Methods. CSE 114, Computer Science 1 Stony Brook University

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Pointers in C/C++ 1 Memory Addresses 2

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Your First Windows Form

4. Java language basics: Function. Minhaeng Lee

COMP-202 Unit 4: Programming with Iterations

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

Controls Structure for Repetition

3 The L oop Control Structure

How to approach a computational problem

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Midterms Save the Dates!

First Java Program - Output to the Screen

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Full file at

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

For example, let s say we define an array of char of size six:

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

The compiler is spewing error messages.

C Functions. 5.2 Program Modules in C

6.096 Introduction to C++

C++ for Java Programmers

Chapter 4 Defining Classes I

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Mobile App:IT. Methods & Classes

Functions and Recursion

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Textbook. Topic 6: Functions. Motivation. What is a Function? What s a function? How can we use functions to write better software?

CS12020 for CGVG. Practical 2. Jim Finnis

1: Introduction to Object (1)

Chapter01.fm Page 1 Monday, August 23, :52 PM. Part I of Change. The Mechanics. of Change

D - Tic Tac Toe. Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9

User Defined Functions

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

The Parts of a C++ Program

Ch. 6. User-Defined Methods

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CSCE 120: Learning To Code

Transcription:

Static Methods A method is just a collection of code. They are also called functions or procedures. It provides a way to break a larger program up into smaller, reusable chunks. This also has the benefit of making programs easier to understand. You are already familiar with one method, the main method. The parameter list is used to pass data to the method. Since a method is a function, we have to declare what type of value the function will return (e.g., int, float, long, etc.) If we don t want the method to return any value, we have a special type called void. For now, we will only study a type of method called a static method. With a static method, there is only one of these for the whole program you can think of it like a globally accessible method. Later we will examine methods that don t use the static keyword. Why use methods? So far, we have been working with relatively small programs. As such, the entire program has been coded up into a single method, main. For larger programs, a single method is often inconvenient and also hard to work with. The technique of dividing a program up into manageable pieces is typically done by constructing a number of smaller methods and then piecing them together as modules. This type of modularization has a number of benefits: Avoids repeat code (reuse a method many times in one program) Promotes software reuse (reuse a method in another program) Promotes good design practices (Specify interfaces) Promotes debugging (can test an individual method to make sure it works properly) Let s examine how to write programs using methods. Before starting We ve already been using quite a few methods in our programs. Calls like println() and nextint() are all methods that have been written by someone else that we re using. Note how the innards of these functions are all hidden from you as long as you know the interface, or the input/output behavior, you are able to use these functions in your own programs. This type of data-hiding is one of the goals of methods and classes, so that higher-level code doesn t need to know the details of particular tasks. Before starting and jumping into writing programs using methods, it is a good idea to look at the problem you are trying to address and see how it might logically be broken up into pieces. For example, if you are writing a program to give a quiz then you might have separate methods to:

Defining a Method Load the questions and answers from the disk Ask a single question to the player and get an answer Test if an answer is correct Display the final score Coordinate all of the actions above (might go in the main method) To define a method use the following template: modifier static return_type varname2, ) Instructions return (return_value); methodname(type1 varname1, type2 Modifier is either public or private to indicate if this method is available from outside the class. (There is also a modifier protected but we will defer its discussion for now). For now we ll use public. Static may be left off. If it is included then there is only one of these methods that can be thought of as a global method accessible to anyone, without the need for a calling object. When static is left off, the method can only be called from certain places. For now, we ll use static. Return_type is a data type returned by the function. For example, int, float, long, another Class, or void if we have no data to return. If we are returning a value, we must specify what value the method returns with the return statement. Usually this is at the end of the function, but it could be anywhere inside the function. methodname is an identifier selected by the user as the name for the method. The list of parameters are input variables that are passed to the function from the caller. This gives data for the function to operate on. To define these parameters, specify the type of the variable followed by the variable name. Multiple parameters are separated by commas. Here is a method that finds the maximum of three numbers and returns the max back, and some code in main that invokes this function:

public class Foo public static int maximum(int num1, int num2, int num3) int curmax; curmax = num1; if (num2 > num1) curmax = num2; if (num3 > curmax) curmax = num3; return (curmax); int max; // Local variable, only exists // within this function! max = maximum(5, 312, 55); // Max gets 312 System.out.println(max); // prints 312 Code starts executing inside main. We invoke the method named maximum with three parameters: 5, 312, and 55. This executes the code inside maximum and binds num1 with 5, num2 with 312, and num3 with 55. The code inside maximum has logic to determine which number of the three parameters is smallest. This is done by defining a variable called curmax. Any variable defined inside a function is considered a local variable. It exists only within the scope of the function. When the function exits, this variable is gone forever! This is a good way to declare variables we need temporarily. How do we get data back from the method to the caller? We can use the return statement, which returns any value we like back to the caller. In this case, we return the local variable curmax, and it is assigned into the variable max inside the main function before curmax is destroyed. Here is another example of a method that converts a temperature specified in Fahrenheit to Celsius: public static double converttocelsius(int tempinfahr) return ((tempinfahr 32)*5.0/9.0); Filling in the code using Top-Down Design Two ways of completing our program are to use either top-down or bottom-up design. In top-down design, we write the most general code first and then fill in the details later. In bottom-up design, we write the detailed code first and then incorporate them into more

general code. In both cases, testing is done along the way. This is called incremental testing. It is generally a bad idea to write a lot of code and assume that it will run this approach is very hard to debug if there are errors. Let s first look at top-down design. Generally this means we start by defining main. Here is an example of a dice game: int wallet = 1000; boolean keepplaying = true; int roll, bet; while (keepplaying) bet = getbet(wallet); roll = rolldice(); System.out.println("Roll=" + roll + " bet=" + bet); // Other stuff here to process the bet and the roll This makes for a nice and simple main method! Main assumes that there are methods associated with it to perform the betting and dice rolling activities. However, we haven t yet filled in what getbet() and rolldice() will do. If you wish to test what you ve created so far, a good practice is to write stubs for each function. The stubs simply print out dummy information, so that you can test to see if the calling code is functioning properly. Here are some sample stubs: class DiceGame public static int rolldice() // Define roll dice here return (5);// always returns the number 5 public static int getbet(int cashavailable) int bet; Scanner keyboard = new Scanner(System.in); System.out.println( Enter bet: ); bet = keyboard.nextint(); // More GetBet code here, need to validate input still // To make sure it is a valid amount return (bet);

Note that the getbet method has access to the parameter named cashavailable, which holds the value that was passed into from the calling routine. This is referred to as a local variable, and will be described more later. There is also a local variable called bet. This program will now compile and run, and give the output: Enter bet: 4 Roll is 5 bet is 4 Enter bet: 3 Roll is 5 bet is 3 This allows us to test to see if the outer loop is working properly. If there were bugs, like the wrong value was being returned, or other problems, then you could hopefully fix them before moving on! The next step would be to flesh out the rest of the main function and have it handle the other cases for the game. Once again, these cases can be tested using the stubs that we wrote for getbet and rolldice. After main has been written and debugged, the next step is to flesh out the individual functions. If getbet() invoked methods of its own, we could follow the same top-down procedure and write the code for getbet(), leaving stubs for functions called by getbet. However since getbet is pretty short without calling any functions we can just write it all: public static int getbet(int cashavailable) int bet; Scanner keyboard = new Scanner(System.in); do System.out.println( Enter bet: ); bet = keyboard.nextint(); while ((bet > cashavailable) (bet <= 0)); return (bet); We can do the same for RollDice: public static int rolldice() Random rnd = new Random(); // Better to define elsewhere // but OK here return (rnd.nextint(6) + rnd.nextint(6) + 2);

When we put this all together, the entire program is finished! Filling in the code using Bottom-Up design We can take the opposite approach and write our functions using a bottom-up process. In this case, we would write the individual, detailed functions first, and the more general code later. For example, let s say that we wrote both the RollDice and GetBet methods, but we haven t written main() yet. The process to follow is to test each individual function using some type of test harness. Once we re satisfied that the individual functions work, we can move on and start writing the main function. // Test harness main to see if RollDice is really working int i; for (i=0; i<100; i++) System.out.println(RollDice()); // Expect 100 random nums In this case, our tests might discover that RollDice returns an invalid dice roll, like a total of 1 or 0, or perhaps gives the wrong distribution of numbers. Depending on what you want to do (print an error? Print nothing?) you might want to go back and change the function accordingly. Passing Primitive Parameters: Call By Value What we ve done so far is pass the parameters using what is called call by value. For example we passed the variable num1 to a function. The function gets the value contained in the variable num1 and can work with it. However, any changes that are made to the variable are not reflected back in the calling program. For example: public class Foo public static void doesntchange(int num1) int y = 3; // Local variable, used later System.out.println(num1); // Prints 1 num1 = 5; System.out.println(num1); // Prints 5 return;

int val = 1; doesntchange(val); System.out.println("Back in main:" + val);// Prints 1 The output for this program is: 1 5 Back in main: 1 The variable val is unchanged in main. This is because the function DoesntChange treats its parameters like local variables. The contents of the variable from the caller is copied into the variable used inside the function. When the function exits, this variable is destroyed. The original variable retains its original value. Passing Object Parameters: Call By Reference We get a different behavior if we pass an object as a parameter rather than a primitive data type. We create objects with the keyword new. We haven t defined our own objects yet, but an array is an example of an object we have seen already. If we change the contents e.g. for an array, this would be the data inside the array - of an object that is passed as a parameter inside a method, then the change is reflected back in the calling code. This is called call by reference. Setting the object itself to something different does not reflect back in the calling code. For example: public class Foo public static void doeschange(int[] arr) arr[0] = 100; int[] a = new int[3]; a[0] = 1; doeschange(a); System.out.println("Back in main:" + a[0]); //Prints 100 First, some mechanics of how to pass an array. When we define the method, the array parameter is defined using [] after the data type followed by a parameter name, just like when it is defined in main. We don t need to specify the array size.

When we send an array into a method, we give the variable name but no square brackets. Just the variable name by itself. The variable is changed back in the caller because we re passing an object as a parameter. Internally, objects are passed to the method by providing the address of the object in memory. This means changes to the object inside the function change the original copy of the data. This is not the case when we pass primitive data types; instead we give a copy of the entire variable instead of providing the address. Underneath the Hood The Stack and Parameter Passing We will give a discussion of this in class. There is a special area of memory called the stack. Every time we call a method, we create a stack frame on top of the stack that holds any variables allocated for the method.