procedural programming in java methods, parameters and return values

29
Procedural programming in Java Methods, parameters and return values

Upload: erick-morris

Post on 04-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Procedural programming in Java Methods, parameters and return values

Procedural programming in Java

Methods, parameters

and return values

Page 2: Procedural programming in Java Methods, parameters and return values

Recap from last lecture

• Variables and types– int count

• Assignments– count = 55

• Arithmetic expressions– result = count/5 + max

• Control flow– if – then – else– while – do– do –while– for

Page 3: Procedural programming in Java Methods, parameters and return values

Programming

• Programming consists of two steps: • design (the architects)• coding (the construction workers)

Page 4: Procedural programming in Java Methods, parameters and return values

A simple programming problem

Problem definition

A program is required which will take a string as a command line argument of any length and determineif the string represents a palindrome - i.e. a word whichreads the same backwards as forwards.

If the word is a palindrome, a message :- <command line argument> is a palindromeshould be displayed. If not, the message should be :- <command line argument> is not a palindrome

If the number of command line arguments is not equalto 1 an error message should be displayed.

Procedural programming in Java

Page 5: Procedural programming in Java Methods, parameters and return values

A simple programming problemProgram design word : string * represents command line argument length : integer *represents length of word if there is one command line argument then set word = command line argument set length = length of word for all characters at pos in the first half of the word if char at pos not equal to char at length-pos then exit for end if end for if premature exit from loop then display not a palindrome else display palindrome end if else display error message end if

Procedural programming in Java

Page 6: Procedural programming in Java Methods, parameters and return values

A simple programming problemProgram code public class Palindrome { public static void main(String [] args) { String word; int length, pos; if ( args.length == 1 ) { word = args[0]; length = word.length(); for (pos = 0; pos <= length / 2; pos++) { if ( word.charAt(pos) != word.charAt(length - 1 - pos)) break; } //end for if ( pos > length / 2 ) System.out.println(word + “ is a palindrome”); else System.out.println(word + “ is not a palindrome”); } else System.err.println(“One command line argument only”); } //end main } //end class Palindrome

Procedural programming in Java

Page 7: Procedural programming in Java Methods, parameters and return values

A simple programming problemProgram code public class Palindrome { public static void main(String [] args) { String word; int length, pos = 0; if ( args.length == 1 ) { word = args[0]; length = word.length(); while ( pos <= length / 2) { if ( word.charAt(pos) != word.charAt(length - 1 - pos)) break; pos++; } //end while if ( pos > length / 2 ) System.out.println(word + “ is a palindrome”); else System.out.println(word + “ is not a palindrome”); } else System.err.println(“One command line argument only”); } //end main } //end class Palindrome

Procedural programming in Java

Page 8: Procedural programming in Java Methods, parameters and return values

Procedural Programming in Java

The square root algorithm

The square root of a number can be calculated by taking a series of estimates. Each successive estimate is derived from the previous using the following formula :- new estimate = average of (old estimate + value/old estimate)

This can be expressed as pseudo-code as follows :-

value : integer *value who’s square root is requirede1 : real *first estimatee2 : real *next estimatee2 = value / 2 *a crude way to start off with a first guessdo set e1 to e2 set e2 to (e1 + value/e1)/2while positive difference between e1 and e2 > accuracy required

Note : In order to repeat the loop, the new estimate must become the old one next time round. Hence the need for - set e1 to e2

Page 9: Procedural programming in Java Methods, parameters and return values

Procedural Programming in Javapublic class SquareRoot { public static void main(String [] args) { int value; double e1, e2; value = Integer.parseInt(args[0]); if (value > 0){ //now we can calculate square root e2 = value / 2; do { e1 = e2; e2 = (e1 + value / e1) / 2;} while (Math.abs(e1 - e2) > 0.0001); System.out.println("Square root = " + e2); } else System.err.println("Only positive arguments allowed"); } //end main} //end class SquareRoot

Implementation of square-root program

Page 10: Procedural programming in Java Methods, parameters and return values

Procedural Programming in JavaSub-programs in Java

It is not desirable or practicable to place all code in one main program.As programs become larger and perhaps more people are working on themsimultaneously, it is necessary to subdivide the code into sub-programs.

These are called - subroutines (FORTRAN), procedures (PASCAL),functions (C) or methods (Java), but all refer to sub-programs.

Use of methods allow you to :- Subdivide a large program into smaller pieces - easier to understand.

Allow several people to work on different parts of the program at once.

Factor out commonly occurring pieces of code and write only once.

Avoid repetition and hence changes only made in one place.

Create sub-programs which can be re-used in other applications.

Minimise the amount of re-compilation when changes are made.

Page 11: Procedural programming in Java Methods, parameters and return values

Procedural Programming in JavaParameterless methods

public class Rabbit {

public static void main(String [] args) { chatter(); //all methods must have a parameter chatter(); //list () even if it is empty chatter(); } //end main

public static void chatter(){ System.out.println(“Hello and welcome to Java”); } //end chatter

} //end class Rabbit

Here, the method chatter() needs no additional information to do its job.Hence, nothing is passed to it as parameters and nothing is returned.

Page 12: Procedural programming in Java Methods, parameters and return values

Procedural Programming in JavaMethod with parameters

public class Rabbit {

public static void main(String [] args) { int x = 10; chatter(2 * x); //here an actual value (parameter) is passed chatter(5); //to tell the method how often to loop } //end main

public static void chatter(int repeat){ for (int i = 0; i < repeat; i++) System.out.println(“Hello and welcome to Java”); } //end chatter

} //end class Rabbit

In this version of chatter(), the method needs to be told how often to repeatthe message - the int repeat in the method header is a formal parameter,the 2 * x and the 5 in the method calls are actual parameters.

Page 13: Procedural programming in Java Methods, parameters and return values

Procedural Programming in JavaMethod with parameters

public class Rabbit {

public static void main(String [] args) { int x = 10; chatter(x % 3, “Hello there”); //must send both repeat chatter(5, args[0]); //amount and message string } //end main

public static void chatter(int repeat, String message){ for (int i = 0; i < repeat; i++) System.out.println(message); } //end chatter

} //end class Rabbit

Here, chatter() needs to be told what to say and how often. Formal parametersconsist of lists of data type followed by name - int repeat, String message Actual parameters consist of a corresponding set of values - 5 , args[0]

Page 14: Procedural programming in Java Methods, parameters and return values

Procedural Programming in JavaMethod which return results

public class Rabbit { public static void main(String [] args) { int val = Integer.parseInt(args[0]); System.out.println(“Square root = “ + squareRoot(val)); } //end main

public static double squareRoot(int value) { double e1, e2 = value / 2; //local variables known only to method do { e1 = e2; e2 = ( e1 + value / e1 ) / 2;} while (Math.abs(e1 - e2) > 1.0e-5); //use of scientific notation return e2; //result returned to calling program } //end squareRoot} //end class Rabbit

Here, chatter() needs to be told what to say and how often. Formal parametersconsist of lists of data type followed by name - int repeat, String message Actual parameters consist of a corresponding set of values - 5 , args[0]

Page 15: Procedural programming in Java Methods, parameters and return values

Important concept #1

• Divide and Conquer: Break large programs into a series of smaller modules

– Helps manage complexity

– Makes it easier to build large programs

– Makes it easier to debug programs

Page 16: Procedural programming in Java Methods, parameters and return values

Important concept #2

• Abstraction: Most of the time, you need to know what a method does, but not how it actually does it.– Also helps manage complexity

– You use other people’s code without knowing how it does it’s job.

Page 17: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

Methods Declarations

• Methods– Allow programmers to modularize programs

• Makes program development more manageable

• Software reusability

• Avoid repeating code

– Local variables• Declared in method declaration

– Parameters• Communicates information between methods via method calls

Page 18: Procedural programming in Java Methods, parameters and return values

Method Declarations

• A method declaration specifies the code that will be executed when the method is invoked (or called)

• When a method is invoked, the flow of control jumps to the method and executes its code

• When complete, the flow returns to the place where the method was called and continues

• The invocation may or may not return a value, depending on how the method is defined

Page 19: Procedural programming in Java Methods, parameters and return values

Method Header

• A method declaration begins with a method header

char calc (int num1, int num2, String message)

methodname

return type(primitive type,

class name, or void)

parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal argument

Page 20: Procedural programming in Java Methods, parameters and return values

Method Body

• The method header is followed by the method body

char calc (int num1, int num2, String message) {

int sum = num1 + num2; char result = message.charAt(sum);

return result;}

The return expression must beconsistent with the return type.

sum and resultare local data

They are created each time the method is called, and are destroyed when it finishes executing

Page 21: Procedural programming in Java Methods, parameters and return values

Data Scope

• The scope of data is the area in a program in which that data can be used (referenced)

• Data declared at the class level can be used by all methods in that class

• Data declared within a method can be used only in that method

• Data declared within a method is called local data

Page 22: Procedural programming in Java Methods, parameters and return values

22

The return Statement

• The return type of a method indicates the type of value that the method sends back to the calling location

• A method that does not return a value has a void return type

• A return statement specifies the value that will be returned

return expression;

• Its expression must conform to the return type

• It is good practice for a method to only have one return statement. (Unless things would become overly complex otherwise)

Page 23: Procedural programming in Java Methods, parameters and return values

Parameters• Each time a method is called, the actual parameters in the invocation are copied into the formal parameters• The types of the actual parameters must be consistent with the specified types of the formal parameters.

char calc (int num1, int num2, String message) {

int sum = num1 + num2; char result = message.charAt(sum);

return result;}

ch = obj.calc (25, count, "Hello");

Page 24: Procedural programming in Java Methods, parameters and return values

Local Data

• Local variables can be declared inside a method

• The formal parameters of a method create automatic local variables when the method is invoked

• When the method finishes, all local variables are destroyed (including the formal parameters)

– Meaning, a local variable does not exist outside the method in which it is declared.

• Keep in mind that instance variables, declared at the class level, exists as long as the object exists

• Any method in the class can refer to instance data

Page 25: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

Method Declarations (cont.)

• General format of method declaration:

modifiers return-value-type method-name( parameter1, …, parameterN ){ declarations and statements}

• Method can also return values: return expression;

Page 26: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

26

Naming your methods

• As with variables naming methods is important• You should give your methods names which

clearly describe what the function is doing– helps debugging

– helps others read your code

• Same rules as naming variables– E.g. public static float calculateTax( int sale )

• When you write about a method in an explanation use the parenthesis to indicate you are referencing a method (as opposed to a regular variable):– E.g. //call squareInteger() to calculate the square

Page 27: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

27

Good programming with methods

• A method should do one and only one useful action– If you see names for your method that suggest multiple

actions then it’s time to break it up into separate functions; for example,

calculateTaxAndPrintReturnAndSaveFile(); -ugh

• If you do something more than once in a program, you should write a method for that action.

Page 28: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

28

More Good Programming

• If you have written a method to do something in one project, and you need to do the same action in another project, you should reuse the method.– In Java this is usually accomplished by using classes which

we will not cover in this lecture.

Page 29: Procedural programming in Java Methods, parameters and return values

2003 Prentice Hall, Inc. All rights reserved.

Summary

• Methods allow programmers to modularize code– Divide and Conquer:

• Break large programs into a series of smaller modules

– Abstraction: • Most of the time, you need to know what a method does, but

not how it actually does it.

• Methods can have parameters and return values• Methods can have local variables• Methods can call other methods• When methods are called actual parameters are

copied to formal parameters