“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Spring Semester 2013 Lecture 5
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Road Map Introduction to object oriented programming. Classes
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
ECE122 Feb Introduction to Class and Object Java is an object-oriented language. Java’s view of the world is a collection of objects and their.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
CS 201 Functions Debzani Deb.
1 Memory Model of A Program, Methods Overview l Memory storage areas for an executing program l Introduction to methods and methods definitions l General.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Introduction to Methods
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
1 Classes and Objects in C++ 2 Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Procedural programming in Java Methods, parameters and return values.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Functions + Overloading + Scope
Java Primer 1: Types, Classes and Operators
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
User Defined Functions
Chapter 6 Methods: A Deeper Look
Functions.
Chapter 6 Methods.
Chapter 6 – Methods Topics are:
Java Programming Language
Defining Classes and Methods
Classes, Objects and Methods
Corresponds with Chapter 5
SPL – PS3 C++ Classes.
Presentation transcript:

“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.” – Chines Proverb If programs are short We can write the code as one contiguous segment The logic is probably simple There are not too many variables Not too likely to make a lot of errors As programs get longer Programming in a single segment gets more and more difficult Logic is more complex Many variables, expressions, control statements

“Education is a Treasure that follows you everywhere.” – Chines Proverb If programs are short Code as one contiguous segment The logic is probably simple There are not too many variables Not too likely to make a lot of errors As programs get longer Programming in a single segment gets difficult Logic is more complex Many variables, expressions, control statements

“Education is a Treasure that follows you everywhere.” – Chines Proverb Difficult to do if ONE BIG PROGRAM: Isolating and fixing bugs need to be modified program Add to program Answer: Break programs into small segments

“Education is a Treasure that follows you everywhere.” – Chines Proverb Method (or function or subprogram) A segment of code that is logically separate from the rest of the program When invoked (i.e. called) control jumps from main to the method and it executes Usually with parameters (arguments) When finished, control reverts to the next statement after the method call

“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods provide us with functional (or procedural) abstraction Do not need to know all of the details of the methods in order to use them. Need to know: 1.What arguments (parameters) we must provide 2.What the effect of the method is (i.e. what does it do?) The actual implementation could be done in several different ways

“Education is a Treasure that follows you everywhere.” – Chines Proverb Ex: Predefined method: sort(Object [] a) There are many ways to sort! EX: word.length(); This allows programmers to easily use methods that they didn’t write.

“Education is a Treasure that follows you everywhere.” – Chines Proverb Java methods have two primary uses: 1. To act as a function, returning a result to the calling code. These methods are declared with return types, and are called within an assignment or expression Ex:X = inScan.nextDouble(); Y = (Math.sqrt(X))/2; 2. To act as a subroutine or procedure, executing code but not explicitly returning a result These methods are declared to be void, and are called as separate stand-alone statements Ex: System.out.println(“Wacky”); Arrays.sort(myData);

“Education is a Treasure that follows you everywhere.” – Chines Proverb There are MANY predefined methods in Java  Look in the online API  These are often called with dot notation: ClassName.methodName(param_list) ClassName is the class in which the method is defined methodName is the name of the method param_list is a list of 0 or more variables or expressions that are passed to the method

“Education is a Treasure that follows you everywhere.” – Chines Proverb Ex: Y = Math.sqrt(X); These are called STATIC methods or CLASS methods They are associated with a class, not with an object.

“Education is a Treasure that follows you everywhere.” – Chines Proverb Some are also called in the following way ClassName.ObjectName.methodName(param_list) ObjectName is the name of a static, predefined object that contains the method Ex: System.out.println(“Hello There”); System is a predefined class out is a predefined PrintStream object within System println is a method within PrintStream These are instance methods – associated with an object – Primarily we will focus on static methods

“Education is a Treasure that follows you everywhere.” – Chines Proverb What if we need to use a method that is not predefined? That’s why we are coders, we are in charge of our universe.

“Education is a Treasure that follows you everywhere.” – Chines Proverb Syntax: public static void methodName(param_list) { // method body } public static retval methodName(param_list) { // method body } Where retval is some Java type When method is not void, there MUST be a return statement

“Education is a Treasure that follows you everywhere.” – Chines Proverb Really simple example: public static void sayWacky() { System.out.println(“Wacky”); } Now in our main program we can have: sayWacky(); for (int i = 0; i < 5; i++) sayWacky(); Note we are not using any parameters in this example

“Education is a Treasure that follows you everywhere.” – Chines Proverb Theparam_list is a way in which we pass values into our methods This enables methods to process different information at different points in the program Makes them more flexible In the method definition (header or signature): List of type identifier pairs, separated by commas Called formal parameters, or parameters In the method call (can be main or another method): List of variables or expressions that match 1-1 with the parameters in the definition Called actual parameters, or arguments

“Education is a Treasure that follows you everywhere.” – Chines Proverb Ex: public static double area(double radius) { double ans = Math.PI * radius * radius; return ans; } In main: double rad = 2.0; double theArea = area(rad); Note: If method is called in same class in which it was defined, we don’t need to use the class name in the call

17 Lecture 7: Parameters  Parameters in Java are passed by value The parameter is a copy of the evaluation of the argument Any changes to the parameter do not affect the argument Main Class 2.0 rad area method radius 2.0 main calls area method value passed from arg. to parameter double theArea = area(rad); theArea double ans = Math.PI * radius * radius; return ans; ans … result returned to main … answer calculated answer returned method completed

“Education is a Treasure that follows you everywhere.” – Chines Proverb Effect of value parameters: Arguments passed into a method cannot be changed within the method, either intentionally or accidentally Good result: Prevents accidental side-effects from methods Bad result: What if we want the arguments to be changed? Ex: swap(A, B) Method swaps the values in A and B - Discuss We can get around this issue when we get into object-oriented programming

“Education is a Treasure that follows you everywhere.” – Chines Proverb Variables declared within a method are local to that method They exist only within the context of the method This includes parameters as well Think of a parameter as a local variable that is initialized in the method call We say the scope of these variables is point in the method that they are declared up to the end of the method

“Education is a Treasure that follows you everywhere.” – Chines Proverb However, Java variables can also be declared within blocks inside of methods In this case the scope is the point of the declaration until the end of that block Be careful that you declare your variables in the correct block

“Education is a Treasure that follows you everywhere.” – Chines Proverb However, Java variables can also be declared within blocks inside of methods  In this case the scope is the point of the declaration until the end of that block  Be careful that you declare your variables in the correct block

22 References and Reference Types Recall primitive types and reference types  Also recall how they are stored With primitive types, data values are stored directly in the memory location associated with a variable With reference types, values are references to objects that are stored elsewhere in memory var1 100 s Hello There

“Education is a Treasure that follows you everywhere.” – Chines Proverb What do we mean by “references”? The data stored in a variable is just the “address” of the location where the object is stored Thus it is separate from the object itself Ex: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.) I can use that address to send something to Joe or to go visit him if I would like However, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located However, I can indirectly change the data in the object through the reference. So if reference variables are changed in a method It will also be changed in main.