Methods in Java Methods & Parameters.

Slides:



Advertisements
Similar presentations
Procedural programming in Java
Advertisements

Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 4: Writing Classes
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
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.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
The Java Programming Language
©Silberschatz, Korth and Sudarshan1 Methods Method Basics Parameters Void vs. Non-void Methods Recursion.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Methods OR HOW TO MAKE A BIG PROGRAM SEEM SMALLER.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes - Intermediate
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Week 4 – Functions Coding Functions. Purpose of Coding Functions A function is written to perform a well-defined task; rather than having all logic in.
Arrays Chapter 7.
Chapter VII: Arrays.
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Input/Output.
Chapter 7: User-Defined Functions II
Chapter 4: Writing Classes
Introduction to Computer Science / Procedural – 67130
Chapter 10: Void Functions
Data types and variables
Organization of Programming Languages
CompSci 230 Software Construction
Chapter 4: Writing Classes
Programmazione I a.a. 2017/2018.
Methods.
User-Defined Functions
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.
Methods and Parameters
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.
ATS Application Programming: Java Programming
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
MSIS 655 Advanced Business Applications Programming
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 4 Writing Classes.
Defining methods and more arrays
CS139 October 11, 2004.
Chapter 4 Topics: class declarations method declarations
Programs and Classes A program is made up from classes
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Chapter 6 – Methods Topics are:
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Classes and Objects Object Creation
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Methods in Java Methods & Parameters

void Methods wallBuilder Method to build a wall A method is a named, neatly packaged fragment of Java code A void method is a method that performs a task If we give the method a name (or identifier) then we can reuse the method All methods must therefore be given a name/identifier

terminology To use/reuse a void method we must call or invoke the method We call/invoke the method by using its identifier ALL of our void methods perform a small task or job for us Examples of void methods include: A method to print out some information A method to print out a ‘header’ method

parameters straw bricks wood Method to build a wall It might be that our method requires some ‘extra information’ to make it work properly? This ‘extra information’ helps to change a method from being specific to being more general (and typically more useful) More than 1 piece of extra information may be required Regardless, the extra information is often referred to as parameter(s) wood Method to build a wall

parameters Method to calculate the product of 3 integers 4 12 9 Method to calculate the product of 3 integers 3 7 11 Method to calculate the product of 3 integers -2 4 -7

example void methods A method that prints out a few blank lines for us The information required to make this method work properly might be an int value which specifies the precise number of blank lines to be printed out A method that draws a rectangle: The information required to make this method work properly might be values which specify the dimensions of the rectangle (i.e. length and breadth)

MORE ON THE “ADDITIONAL INFORMATION” This additional information: must be formally specified in the method heading must be actually supplied when we call (invoke) the method We say that we must ‘pass the information to the method’ Note that NO information is ‘passed back from’ a void method Void methods simply perform their tasks (prints out a few lines, draws a rectangle etc.) but do nothing else

value Methods “Yes” 1 -21.3 ‘A’ Value methods are used to BOTH: calculate/establish a single result or value and return the calculated value It is the return of the calculated value that is important The kind of value calculated/established and returned is referred to as “the nature of the method” e.g. The nature of the result / method might be an int value, a boolean value, a double value, a String value etc.

Returning a value In addition to calculating a single value, ALL value methods of capable of returning that value Recall that with void methods we said that NO information was ‘passed back’ from a void method With value methods the opposite is the case ALL value methods return (or pass) something back The ‘something returned’ is the result calculated/established The nature of the value returned MUST be identified within the method heading

Example void methods static void voidMethod1 ( ) { // Method that needs no additional information to work // WHY?? Answer: EMPTY SIGNATURE } static void voidMethod2 (int pNum) { // Method that requires some additional information to // work – in this case a single int value }

More Example void Methods static void voidMethod3 (int pNum1, int pNum2) { // Method that requires some additional information to // work – in this case 2 int values } static void voidMethod4 (int pNum1, int pNum2, String pString) { // Method that requires some additional information to // work – in this case 2 int values and 1 String value // NB ORDER IS HIGHLY SIGNIFICANT!!! }

More Detail The signature of the method Method name + parameters The name/identifier of the method The code of the method static void voidMethod4 (int pNum1, int pNum2, String pString) { // Method that requires some additional information to // work – in this case 2 int values and 1 String value // NB ORDER IS HIGHLY SIGNIFICANT!!! ………. }

Value Methods static int return20 ( ) { // Method that needs no additional information to work // Calculates and returns an int value return 20; } static int returnDouble (int pNum) { // Method that requires some additional information to // work – in this case a single int value // Calculates and returns an int value return (pNum * 2); }

More Value Methods static boolean isGreater (int pNum1, int pNum2) { // Method that requires some additional information to // work – in this case 2 int values return (pNum1 > pNum2); } static char nthChar (int pNum, String pString) { // Method that requires some additional information to // work – in this case 1 int value and 1 String value // NB ORDER IS HIGHLY SIGNIFICANT!!! return ( pString.charAt (pNum) ); }

A Good Tip! As value methods always return a value, they must have a return statement The return statement is the vehicle that allows the value to be returned The return statement must identify the (single) value to be returned What follows the word return must be the single value that is to be returned This value must be ‘of the same kind of information’ as indicated in the method heading Ensure that all possible routes through a method return a value GOOD TIP! Where possible make the return statement the LAST statement within the method

Invoking Methods You invoke a void method by simply stating its name We call/invoke value methods very differently Such methods are normally called either: On the right-hand-side of an assignment statement Where the value that is returned is assigned to (say) a variable that appears on the left-hand-side of the assignment statement Within (or as part of) a print or a println statement Where the value that is returned is being printed out and thus appears within a print or a println statement

Methods with different Signatures or Arguments Consider the following method heading: static void sillyMethod1 (int pNumber) { // Method whose signature includes an int } To fully appreciate how methods are called (or invoked) we must understand the purpose of the method’s signature

Signatures Revisited The signature of the previous method is underlined below: static void sillyMethod1 (int pNumber) { // Method whose signature includes an int } To call/invoke this method we MUST obey its signature and supply an int value in the form of: an explicit integer (e.g. 12, -34, 99 etc.) an int variable (e.g. myNumber, someValue etc.)

The body of sillyMethod1 Consider the following: static void sillyMethod1 (int pNumber) { System.out.println (“ ************************ ”); System.out.println (“Number passed in was: “ + pNumber); } We have a void method – no value is being returned We can invoke this method in a number of ways

Invoking/Calling sillyMethod Each of the following represents a valid call to (or invocation of) the method sillyMethod sillyMethod1 (12); sillyMethod1 (48); sillyMethod1 (20); sillyMethod1 (0); sillyMethod1 (-8); sillyMethod1 use 12

More examples invocations The following demonstrate different calls to sillyMethod Assuming the existence of an int variable called someNumber Assuming someNumber has previously been assigned a value 12 sillyMethod1 (someNumber); sillyMethod1 (someNumber * 4); sillyMethod1 (someNumber + 8); sillyMethod1 (someNumber - 12); sillyMethod1 (someNumber - 20);

More on Methods Methods are used to split problems into smaller tasks We can identify a method for each of these simpler, smaller tasks We can then reuse our method at different points in the program by ‘calling’ or ‘invoking’ the method No limit to the number of times we call/invoke the method Methods can have their own variables These may only be used/accessed within the method Used to perhaps support the method

SUMMARY The only role of some methods in life is to ‘return a value’! Performs a calculation based on available information and ‘return the result’ of this calculation Searches for a value within an array and ‘return the index’ at which this value was found We often refer to such methods as value method Other methods typically perform a task Very simple example – to print out a few lines They return nothing (as such) We often call such methods as void methods

Parameters Parameters allow us to ‘talk’ or ‘interact’ with the method If we had: A method that allowed us to paint a wall A much better method would allow us to paint a wall AND specify a colour of paint A method that allowed us to draw a line A much better method would allow us to specify a line colour, a line width and a line style Parameters provide methods with information that transforms them from being general to specific

Parameters static void method1 ( ) { …. } // Parameterless method static int method2 (int pAge, String pName) { … } // This method requires 2 parameters int myAge, someInt; String myName; // call methods method1 ( ); someInt = method2 (myAge, myName); Formal parameter list Actual parameter list

Parameters - Example Formal parameter Actual parameter // A value method for calculating age static int calcAge (int yearBorn) { int age; age = 2017 - yearBorn; return age; } // method calcAge public static void main (String args[ ]) { int birthYear; System.out.print (“Please, enter the year you were born: ”); birthYear = keyboard.nextInt(); System.out.print (“You are now roughly “ + calcAge (birthYear) ); System.out.println (“ years old.”); } // main Formal parameter Actual parameter

Passing Parameters When we call (or invoke) a method we pass the actual parameters from the call statement to the formal parameters within the method yearBorn = birthYear; If we update these formal parameters within the method do the changes get copied back into the actual parameters of the method call statement?? No! You should experiment to convince yourself of this!

Method Overloading We overload a method when we have more than 1 method within a given class that has the same identifier You should be familiar with this concept: The word ‘wind’ in English has more than one meaning The symbol + in Mathematics may mean integer addition or it might mean real number addition We work out its meaning according to its context The ‘context’ used in Java programming is that, if we choose the same identifier for a number of methods, we MUST ENSURE that there are difference(s) in the number, type and order of the parameters!

Method name + parameter list Signature Method name + parameter list We thus say (with respect to method overloading) that we can have methods with the same identifiers as long as they have different parameters

Same Method Identifier Different PARAMETERS ALL OF THESE METHODS ARE DIFFERENT! static void someMethod (int aParam); static void someMethod (String aParam); static void someMethod (double aParam); static void someMethod (int aParam, String bParam); static void someMethod (int aParam, double bPAram) static void someMethod (String aParam, int bParam);

Are these different Methods? Java cannot distinguish between these 3 methods static int someMethod (int aParam) { …. } static boolean someMethod (int aParam) { …. } static String someMethod (int aParam) { …. } static int someMethod (int aParam, String bParam) { …. } static String someMethod (int aParam, String bParam) { …. } static boolean someMethod (int aParam, String bParam) { …. } static double someMethod (int aParam, String bParam) { …. } Java cannot distinguish between these 4 methods

Application Classes Application classes have one static ‘main’ method They are executable through their main method It may also have other static methods All methods in the class follow the same syntax: MODIFIER static RETURN-TYPE ‘name’ (parameter-list) { statement; more statements; } // name

METHOD – FLOW OF CONTROL The main method is invoked by the system when you submit the bytecode to the interpreter Each method call returns to the place that called it! main method1 method2 method1(); method2();