Java Coding 4 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

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.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Java Coding 3 David Davenport Computer Eng. Dept.,
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
Introduction to Methods
Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Syntax for Variables & Constants Input,
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Information and Computer Sciences University of Hawaii, Manoa
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Java Coding – part 2 David Davenport Computer Eng. Dept.,
Lesson #6 Modular Programming and Functions.
COMP 170 – Introduction to Object Oriented Programming
Lesson #6 Modular Programming and Functions.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Data types and variables
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Chapter 4: Writing Classes
Lesson #6 Modular Programming and Functions.
CS139 – Fall 2010 How far we have come
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.
Introduction to C++ Programming
Java Coding 4 David Davenport Computer Eng. Dept.,
Chapter 6 Methods: A Deeper Look
Variables ICS2O.
Packages and Interfaces
Group Status Project Status.
IFS410 Advanced Analysis and Design
Defining methods and more arrays
Java Programming Function Introduction
CS2011 Introduction to Programming I Methods (I)
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
Lesson #6 Modular Programming and Functions.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Classes, Objects and Methods
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Java Programming Function Introduction
Visibilities and Static-ness
Corresponds with Chapter 5
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 4 David Davenport Computer Eng. Dept., Method madness David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr 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.

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 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… 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

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!

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

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)

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)

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

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) {…}

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 http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

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

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();

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!”); …

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”); …

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

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);

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

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);

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

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

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

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;

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;

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;

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

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!)

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!

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

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

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!

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

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

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!