Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Coding 4 David Davenport Computer Eng. Dept.,

Similar presentations


Presentation on theme: "Java Coding 4 David Davenport Computer Eng. Dept.,"— Presentation transcript:

1 Java Coding 4 David Davenport Computer Eng. Dept.,
Method madness David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last updated: 16/11/2016 ~ added lots of animated slides to aid explanation, reordered slides to make more logical presentation sequence! Previously: 07/11/2016, 30/10/2014, 06/11/2012 NOTICE: This presentation deals almost exclusively with STATIC methods & structured programming. We move on to INSTANCE methods in a following presentation on OOP.

2 IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

3 Using Java methods… answer = f( x, y, z ); output // in Scanner class
result type // in Scanner class public int nextInt() int i = scan.nextInt(); answer = f( x, y, z ); input Parameters & types // in … class public void println( String s) System.out.println( “Hello Java”); Method name // in Math class public static double sin( double d) double d = Math.sin( 0.5); Use ClassName.method(…) for “static” methods Reading … and applying … Java API documentation! for Math & String only (static + Strings which are weird objects!) - though lessons are generally valid. // in String class… public String substring( int beginIndex, int endIndex) String shortString = longString.substring( 1, 3); varName.method(…) for non-static methods

4 Don’t need to know HOW they work in order to use them
Methods Don’t need to know HOW they work in order to use them Methods are “Black” boxes that do something In Java methods have any no of named inputs “only” 1 output. f z a b c y = sin(x) z = f ( a, b, c) functions  methods in Java Having only a single output is something of a limitation, but Outputs can be any Java type, including object types, allowing lots of information to be passed out. Some inputs, non-primitive types, can actually be outputs too. In OOP there is another, “secret” form of output too!

5 Methods Meaningfully named blocks of commands
facilitate: reuse, structure & top-down design. Methods can be reused Easier to build, test & debug Rather than a long list of instructions that would be difficult to understand, debug, etc., break it up into small (7 +/- 2) pieces (=methods) Each method is short (7 ± 2 lines) and so easy to understand

6 Reusing code… Identical code… Almost identical… sum = 0;
aMethod() sum = 0; for ( int i = 5; i < 25; i++) sum = sum + i; Sys… ( sum); for ( int i = 19; i < 27; i++) main main aMethod() sum = 0; for ( int i = low; i < high; i++) sum = sum + i; Sys… ( sum); sumBtw( low, high)

7 Methods & Algorithms public static type f( type a, type b, type c) f
Output type or void f a b c z (i) (ii) (iii) (iv) Method name List of inputs & types Ask for and get x Compute y using x Print y (iii) Note: Keyboard input & console (screen) output are not considered as input/output for methods. (so, for example, “print y” has an input, but no output!) what form is Java’s main method? (so far used as (i) but in fact it has a single input, args, so it is of type (ii) ) rewrite pseudocode as Java methods… in main… x = askForAndGetValue(); y = computeFrom( x); print( y); (iv) (ii)

8 Formal parameters matched to actual parameter values at run-time
Declaring Methods Syntax modifiers resultType methodName( parameters) statement; where statement is any Java statement methodName is identifier (convention as for variables) resultType is any Java type or “void” parameters is comma separated list of 0 or more “type name” pairs, eg. int age, String s, … Formal parameters matched to actual parameter values at run-time

9 Modifiers Access Others final – cannot be changed!
coming next… Others final – cannot be changed! static – no need for object, only one copy, can be accessed via class name. y = Math.sin( x); str = Integer.toString( 5, 2); b = Character.isDigit( ‘3’); In Java, methods grouped into classes, classes into packages. Packages can also contain other packages. Seen Math class contains methods sin, abs & sqrt. These methods must be defined public & static or else your program (class) couldn’t use them! Math, Integer & Character are class names. All/some methods can be used without creating objects! Note, these modifiers can also be used with data declarations & (except for static) with classes too! e.g. public static double PI = 3.142; is defined in the Math class, along with E. public static double sin( double value) {…} public static String toString( int i, int radix) {…} public static boolean isDigit( char ch) {…} public static void main( String[] args) {…}

10 e.g. java.util.Scanner & java.lang.Math mypackage.MyMethods
Modifiers Access public – accessible/usable by all protected – package & inherited default – package only private – only in current class Methods are collections of statements Classes are collections of methods (+) Packages are collections of classes Packages can contain other packages Need full “path” to class to use its methods e.g. java.util.Scanner & java.lang.Math mypackage.MyMethods In Java, methods grouped into classes, classes into packages. Packages can also contain other packages. Seen Math class contains methods sin, abs & sqrt. These methods must be defined public & static or else your program (class) couldn’t use them! Math, Integer & Character are class names. All/some methods can be used without creating objects! Note, these modifiers can also be used with data declarations & (except for static) with classes too! e.g. public static double PI = 3.142; is defined in the Math class, along with E. Note: “Default” is when nothing is written… i.e. which is better than protected! see

11 Packages, Classes & Methods
Default package java package Math class lang package main(..) random() sin() String class abs() MyProg class swing package toUpperCase() Must specify full path to compiler, i.e. java.lang.Math, which is a pain so use import statement. Scanner *** not static*** is in java.util package, hence we import java.util.Scanner (or *) in order to use it. Math is in java.lang package which is imported by default so do not need explicit import. Some classes contain only static methods, others only non-static, and other both! util package charAt() cs1 package Scanner class Character class

12 Examples (1) Declare method to print fixed message
public static void showErrorMsg() { System.out.println( “Error, try again!”); } Use… (from inside same class) showErrorMsg(); … if ( x > 10) showErrorMsg(); else … … while ( !done) { showErrorMsg(); … } … Note: convention for package names is all lower case & no underscores! Use… (from outside class) mypackage.mysubpackage.MyClassName.showErrorMsg(); MyClass.showErrorMsg(); mypackage.MyClass.showErrorMsg();

13 Examples (2) Method to print any message in box Use…
public static void showMsg( String msg) { System.out.println( “************” ); System.out.println( “ “ + msg); System.out.println( “************” ); } Use… showMsg( “Hello”); … if ( x > 10) showMsg( “too big!”); else showMsg( “ok!”); …

14 Examples (3) Method to simulate a die throw Use…
public static int randomDieThrow() { return (int) (Math.random() * 6) + 1; } Use… Math.random() returns double value between 0.0 & 1.0 (exclusive). “return” tells Java what value to take as the result of the method. Notice how method name “randomDieThrow” makes the code much more readable than directly calling Math.random each time! int faceValue; faceValue = randomDieThrow(); if ( faceValue == 6) System.out.println( “free throw”); …

15 Return statement Used to indicate result of method/function
return value; if (… ) return 0; return -1; where value is Literal Variable or constant Expression Example with multiple return statements: --- if (…) return i; return -1; Type of value must match method return type! Execution of method stops immediately Can have multiple return statements

16 Examples (4) Method to find hypotenuse of triangle Use…
public static double hypotenuse( double side1, double side2) { return Math.sqrt( side1 * side1 + side2 * side2); } Actual & formal parameters are matched one-to-one in sequence, e.g side1 = 3, side2 = 4 Obviously, types of actual and corresponding formal parameter must match!! Use… double z = hypotenuse( 3, 4);

17 Definition & Use Static methods
// header // Author, date public class ClassName { public static void myMethod1( String s) { System.out.println( s); } private static int myMethod2( int i) { return i * 2 + 1; public static void main( String[] args) { myMethod1( “Hello”); int j = myMethod2( 5); System.out.println( j); Methods declared in class (but outside main) Return statement indicates what value will be considered the result of the method (function) Class is collection of methods. In Java, order of definition is not important. Add “package mypackage;” at top to put this into “mypackage” Use in main or other method

18 Examples (5) Method to find absolute difference Use…
public static int absDiff( int x, int y) { int z; z = x – y; if ( z < 0) z = -z; return z; } Any variables, like z, that are not parameters, should be defined locally. Actual & formal parameters are matched one-to-one in sequence, e.g x = 5, y = 3 Obviously, types of actual and corresponding formal parameter must match!! Defined “locally” means inside the method. Clearly, this particular example could be rewritten to avoid using the extra (temporary) variable z. Use… int a = absDiff( 5, 3);

19 Methods calling methods
public static boolean isLessThan( int a, int b) { boolean z; } Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched one-to-one in order, then values passed. a:-4, b:0 z:true public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); } x:5, y:9 z:-4 Clarify idea that methods are (should be) completely independent of each other Only connected when called… actual param values passed to corresponding formal params public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); … absDiff( y, x); ... isLessThan( x, y); } x:5, y:9

20 Methods calling methods
public static boolean isLessThan( int a, int b) { boolean z; } Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched one-to-one in order, then values passed. a:4, b:0 z:false public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); } x:9, y:5 z:4 Clarify idea that methods are (should be) completely independent of each other Only connected when called… actual param values passed to corresponding formal params public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); … absDiff( y, x); ... isLessThan( x, y); } x:5, y:9

21 Methods calling methods
public static boolean isLessThan( int a, int b) { boolean z; } a:5, b:9 z: true Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched one-to-one in order, then values passed. public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); } Clarify idea that methods are (should be) completely independent of each other Only connected when called… actual param values passed to corresponding formal params public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); … absDiff( y, x); ... isLessThan( x, y); } x:5, y:9

22 Parameter passing (1) a x z b y c main myMethod( x, y) a = 5; b = 3;
10 5 3 13 13 Notice that each method is entirely independent and has its own name & data space (exactly like Robo!) Note too, that these exist within a class which also has its own memory space. This may include static constants, Math.PI (and variables… caution!) a = 5; b = 3; c = myMethod( a, b); System.out.println( c); z = 2 * x; return z + y;

23 Parameter passing (2) a x z b y c main myMethod( x, y) a = 5; b = 3;
6 3 5 11 11 Notice that if inside myMethod we set x = 7; the corresponding actual parameter b does not change. IMPORTANT – include in example code too! a = 5; b = 3; c = myMethod( b, a); System.out.println( c); z = 2 * x; return z + y;

24 Parameter passing (3) a x z b y c main myMethod( x, y) a = 5; b = 3;
Doesn’t change! 5 3 14 7 3 5 19 19 Notice that if inside myMethod we set x = 7; the corresponding actual parameter b does not change. IMPORTANT – include in example code too! a = 5; b = 3; c = myMethod( b, a); System.out.println( c); x = 7 z = 2 * x; return z + y;

25 Overloaded Methods Method signature…
public int anyMethod( parameters) Methods in same class must have different signatures! println( int i) println( double d) println( String s) anyMethod( parameters) Note: result type must be same! Same name, different parameter list

26 Be aware Want methods to be reusable
Methods that read inputs from keyboard or write output to console are difficult to reuse (e.g. in GUIs) So, pass inputs as parameters & return the output as the result User interaction is then done elsewhere, usually main method. E.g. if a sqrt method allows read its input from the keyboard, we could not use it to compute hypothenuse. Or if it prints output on console, we could not use it to output sqrt * 2 + 1, or some such. Ok, you can define methods specifically for getting data from user/keyboard, or for outputting data to the console in a neat form, but that is all they should do. Principle: each piece performs only one function… Cohesion & coupling… Method should do one task only & should rely on as few external methods/classes as possible (& should definitely not rely on their internal details!)

27 Beware a = 5; b = 3; d = 7; c = myMethod( a, b);
Sys… ( a + “, ” + b + “, ” + d); What is output? In Java, (primitive) parameters are inputs only ~ “pass by value”. In other languages, parameters can be outputs & input/outputs too (indeed, Java object parameters behave differently! ~ “pass by reference”) d is normally assumed not to be changed by the method… (if defined locally in method then (hopefully) no problem but if “global” –static class variable- then dangerous, all bets are off. Only way to be sure in such cases is to trace method.. But tracing is error prone, especially if 10,000 lines long!) Note: global constants are ok, indeed encouraged! Of course, assumes one more thing… only one thread! Naturally assume method parameters are inputs only & method doesn’t have side effects! Global variables!

28 Global, Local, Params… public class MethodPlay { static int d; } global Scope: if local use it, else look to outer (global) context. Rule: any variable used in a method, that is not a parameter, must be defined locally… otherwise need to trace everything to see whether any side-effects change its value! public static int myMethod(…) { d = 999; } assigns 999 to global variable public static void main( String[] args) { d = 7; c = myMethod(…); Sys..( d); } assigns 7 to global variable prints 999 from global variable

29 Global, Local, Params… public class MethodPlay { static int d; } global Scope: if local use it, else look to outer (global) context. Rule: any variable used in a method, that is not a parameter, must be defined locally… otherwise need to trace everything to see whether any side-effects change its value! public static int myMethod(…) { d = 999; } assigns 999 to global variable public static void main( String[] args) { int d; d = 7; c = myMethod(…); Sys..( d); } local Note: - need global d here otherwise won’t compile (missing d in myMethod) - can get value (=999) from global variable using “MethodPlay.d” assigns 7 to local variable prints 7 from local variable

30 Global, Local, Params… public class MethodPlay { static int d; } global Scope: if local use it, else look to outer (global) context. Rule: any variable used in a method, that is not a parameter, must be defined locally… otherwise need to trace everything to see whether any side-effects change its value! public static int myMethod(…) { int d: d = 999; } local assigns 999 to local variable public static void main( String[] args) { d = 7; c = myMethod(…); Sys..( d); } Note: - need global d here otherwise won’t compile (missing d in myMethod) - can get value (=999) from global variable using “MethodPlay.d” assigns 7 to global variable prints 7 from global variable …unless something else changed it!

31 assigned to param (input only!)
Global, Local, Params… public class MethodPlay { static int d; } global Scope: if local use it, else look to outer (global) context. Rule: any variable used in a method, that is not a parameter, must be defined locally… otherwise need to trace everything to see whether any side-effects change its value! public static int myMethod( int d) { d = 999; } param assigned to param (input only!) public static void main( String[] args) { int d; d = 7; c = myMethod(..); Sys..( d); } local

32 Global, Local, Params… public class MethodPlay { static int d; } global Scope: if local use it, else look to outer (global) context. Rule: any variable used in a method, that is not a parameter, must be defined locally… otherwise need to trace everything to see whether any side-effects change its value! public static int myMethod( …) { int d; d = 999; } local public static void main( String[] args) { int d; d = 7; c = myMethod(..); Sys..( d); } local

33 Example… static Scanner scan = new Scanner( System.in );
global public static int askForAndGetIntValue() { System.out.print( “Enter value: “); return scan.nextInt(); } Scanner scan ) { param Scanner scan = new Scanner( System.in ); local oops… undefined! Local: ok, but may be problem here due to shared resource? Param: ok, create in main & pass (but may have lots of params!) Global: um… for the really lazy!


Download ppt "Java Coding 4 David Davenport Computer Eng. Dept.,"

Similar presentations


Ads by Google