Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Coding 4 Method madness David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: [email protected] IMPORTANT… Students… This presentation is designed to be used in class as part of a guided discovery sequence. It is not selfexplanatory! 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 email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David. Using Java methods… output result type // in Scanner class public int nextInt() int i = scan.nextInt(); answer = f( x, y, z ); // in … class public void println( String s) System.out.println( “Hello Java”); // in Math class public static double sin( double d) double d = Math.sin( 0.5); // in String class… public String substring( int beginIndex, int endIndex) String shortString = longString.substring( 1, 3); Method name input Parameters & types Use ClassName.method(…) for “static” methods varName.method(…) for non-static methods Methods Methods are Don’t need to know HOW they work in order to use them “Black” boxes that do something In Java methods have any no of named inputs “only” 1 output. abc f z y = sin(x) functions methods in Java z= f ( a, b, c) Methods Meaningfully named blocks of commands facilitate: reuse, structure & top-down design. Methods can be reused Easier to build, test & debug Each method is short (7 ± 2 lines) and so easy to understand Reusing code… Identical code… aMethod() main main aMethod() aMethod() aMethod() Almost identical… sum = 0; for ( int i = 5; i < 25; i++) sum = sum + i; Sys… ( sum); sum = 0; for ( int i = 19; i < 27; i++) sum = sum + i; Sys… ( sum); sumBtw( low, high) sum = 0; for ( int i = low; i < high; i++) sum = sum + i; Sys… ( sum); Methods & Algorithms public static type f( type a, type b, type c) Output type or void Method name List of inputs & types Ask for and get x (iii) Compute y using x (iv) Print y (ii) f (i) (ii) a b c (iii) (iv) a b c f f z f z Declaring Methods Syntax modifiers resultType methodName( parameters) statement; where Formal parameters matched to actual statement is any Java statement parameter values methodName is identifier at run-time (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, … Modifiers Access 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’); 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) {…} 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 Packages, Classes & Methods Default package java package lang package main(..) MyProg class cs1 package Math class random() swing package sin() String class abs() toUpperCase() util package charAt() Scanner class Character class 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(); … } … Use… (from outside class) mypackage.mysubpackage.MyClassName.showErrorMsg(); mypackage.MyClass.showErrorMsg(); MyClass.showErrorMsg(); Examples (2) Method to print any message in box 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!”); … Examples (3) Method to simulate a die throw public static int randomDieThrow() { return (int) (Math.random() * 6) + 1; } Use… … int faceValue; faceValue = randomDieThrow(); if ( faceValue == 6) System.out.println( “free throw”); … Return statement Used to indicate result of method/function return value; where value is Literal Variable or constant Expression ⋮ if (… ) return 0; ⋮ return -1; Type of value must match method return type! Execution of method stops immediately Can have multiple return statements Examples (4) Method to find hypotenuse of triangle public static double hypotenuse( double side1, double side2) { return Math.sqrt( side1 * side1 + side2 * side2); } Use… double z = hypotenuse( 3, 4); Actual & formal parameters are matched one-toone in sequence, e.g side1 = 3, side2 = 4 Definition & Use Static methods Methods declared in class (but outside main) // 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; } Return statement indicates what value will be considered the result of the method (function) public static void main( String[] args) { myMethod1( “Hello”); Use in main or other method int j = myMethod2( 5); System.out.println( j); } } Examples (5) Method to find absolute difference public static int absDiff( int x, int y) { int z; z = x – y; Any variables, like z, that are not if ( z < 0) parameters, should be defined locally. z = -z; return z; } Use… int a = absDiff( 5, 3); Actual & formal parameters are matched one-toone in sequence, e.g x = 5, y=3 Methods calling methods public static boolean isLessThan( int a, int b) { boolean z; ⋮ a:-4, b:0 } z:true public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); ⋮ } public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); x:5, y:9 … absDiff( y, x); ... isLessThan( x, y); } Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched oneto-one in order, then values passed. x:5, y:9 z:-4 Methods calling methods public static boolean isLessThan( int a, int b) { boolean z; ⋮ a:4, b:0 } z:false public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); ⋮ } public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); x:5, y:9 … absDiff( y, x); ... isLessThan( x, y); } Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched oneto-one in order, then values passed. x:9, y:5 z:4 Methods calling methods public static boolean isLessThan( int a, int b) { boolean z; ⋮ a:5, b:9 } z: true public static int absDiff( int x, int y) { int z; z = x – y; .. isLessThan( z, 0); ⋮ } public static void main( String[] args) { int x, y; x = 5; y = 9; ... absDiff( x, y); … absDiff( y, x); x:5, y:9 ... isLessThan( x, y); } Methods should be independent of each other Parameters & variables are different, even if same name Only connected when called… actual & formal params matched oneto-one in order, then values passed. Parameter passing (1) main a myMethod( x, y) 5 b 3 c 13 a = 5; b = 3; c = myMethod( a, b); System.out.println( c); 5 x 3 y 10 z 13 z = 2 * x; return z + y; Parameter passing (2) main a myMethod( x, y) 5 b 3 c 11 a = 5; b = 3; c = myMethod( b, a); System.out.println( c); 3 x 5 y 6 z 11 z = 2 * x; return z + y; Parameter passing (3) main Doesn’t change! a myMethod( x, y) 5 b 3 c 19 a = 5; b = 3; c = myMethod( b, a); System.out.println( c); 7 3 x 5 y 14 z 19 x=7 z = 2 * x; return z + y; Overloaded Methods Method signature… public int anyMethod( anyMethod(parameters) parameters) Methods in same class must have different signatures! println( int i) println( double d) println( String s) Same name, different parameter list Note: result type must be same! 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. Beware a = 5; b = 3; d = 7; c = myMethod( a, b); Sys… ( a + “, ” + b + “, ” + d); What is output? Naturally assume method parameters are inputs only & method doesn’t have side effects! Global variables! Global, Local, Params… public class MethodPlay { global static int d; 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) { assigns 7 to global variable d = 7; c = myMethod(…); Sys..( d); } prints 999 from } global variable Global, Local, Params… public class MethodPlay { global static int d; 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) { assigns 7 to int d; local variable d = 7; c = myMethod(…); Sys..( d); } prints 7 from local } local variable Global, Local, Params… public class MethodPlay { global static int d; 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(…) { local int d: } d = 999; assigns 999 to local variable public static void main( String[] args) { assigns 7 to global variable d = 7; c = myMethod(…); Sys..( d); } prints 7 from } global variable …unless something else changed it! Global, Local, Params… public class MethodPlay { global static int d; 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) { param } d = 999; assigned to param (input only!) public static void main( String[] args) { } } int d; d = 7; c = myMethod(..); Sys..( d); local 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; } local d = 999; public static void main( String[] args) { } } int d; d = 7; c = myMethod(..); Sys..( d); local Example… static Scanner scan = new Scanner( System.in ); global public static int askForAndGetIntValue()Scanner { scan ) { Scanner scan = new Scanner( System.in ); } param local System.out.print( “Enter value: “); return scan.nextInt(); 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!