Download presentation
Presentation is loading. Please wait.
Published byΑίγλη Χριστόπουλος Modified over 6 years ago
1
Java Coding 4 David Davenport Computer Eng. Dept.,
Method madness David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. 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
Methods f Meaningfully named blocks of commands
facilitate: reuse, structure & top-down design. In Robo: 4 fixed inputs & no output/result In Java: any no of named inputs & 1 output. f z a b c y = sin(x) z = f ( a, b, c) functions methods in Java
4
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, … Should know what methods are, why and how we use them from Robo. Parameter usage is exactly the same!
5
Modifiers Access Other public – accessible/usable by all
protected – in package or inherited private – only in current class Other final – cannot be changed! static – no need for object, only one copy, can be accessed via class name. In Java, methods grouped into classes, classes into packages. Packages can also contain other packages. // Seen cs1 package contains Keyboard class (with methods readString(), etc.) and StdIO class. Seen Math class contains methods sin, abs & sqrt. These methods must be defined public & static or else your program (class) couldn’t use them! Note, protected is default – sort of, but not exactly! 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) {…} y = Math.sin( x); str = Integer.toString( 5, 2); b = Character.isDigit( ‘3’); public static void main( String[] args) {…}
6
Packages, Classes & Methods
Default package Keyboard class cs1 package main(..) readChar() readString() StdIO class readInt() MyProg class 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. to(file) from(file) exists(file) Packages can contain other packages Packages are collections of classes Classes are collections of methods (+) Methods are collections of statements SimpleURL Reader class
7
Packages, Classes & Methods
Default package java package Math class lang package main(..) random() sin() String class abs() MyProg class swing package 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! toUpperCase() util package charAt() cs1 package Scanner class Character class
8
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.MyClassName.showErrorMsg();
9
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!”); …
10
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. … int faceValue; faceValue = randomDieThrow(); if ( faceValue = 6) System.out.println( “free throw”); …
11
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. Order of definition is not important. Don’t say “do method” as in Robo, but simply say name. Use in main or other method
12
Return statement Used to indicate result of method/function
return value; where value is Literal Variable or constant Expression Type of value must match method return type! Execution of method stops immediately Can have multiple return statements
13
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);
14
Examples (5) Method to find absolute difference triangle Use…
public static int absDiff( int x, int y) { int z; z = x – y; if ( z < 0) z = -z; return z; } 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. Actual & formal parameters are matched one-to-one in sequence, e.g x = 5, y = 3 Any variables, like z, that are not parameters should be defined locally. Use… int a = absDiff( 5, 3);
15
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;
16
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. a = 5; b = 3; c = myMethod( b, a); System.out.println( c); z = 2 * x; return z + y;
17
Method exercises isLessThan( x, y) - return boolean!
Right justify string in given field width. Return letter given grade. Determine if an int value isPrime or not. Method to find absolute difference. isPalindrome x to the power y PI, sin(x), e, e to the x… Convert binary string to int
18
Methods calling methods
public class Probability { public static int comb( int n, int r) return fact(n) / ( fact(r) * fact(n-r) ); } public static int perm( int n, int r) return fact(n) / fact(n-r); private static int fact( int n) int factn = 1; for ( int i = 2; i <= n; i++) factn = factn * i; return factn; Methods can call other sub/helper methods Provides top-down decomposition & abstraction Caution: method can call itself –useful problem solving technique known as recursion! We will look at recursion (method calling itself) next semester!
19
Be aware Want methods to be reusable
Methods that read inputs from keyboard or write output to console are difficult to reuse 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 outputing data to the console in a neat form, but that is all they should do. Principle: each piece performs only one function…
20
Beware a = 5; b = 3; d = 7 c = myMethod( a, b);
Sys… ( a + “, ” + b + “, ” + d); 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! What is output? Naturally assume method parameters are inputs only & method doesn’t have side effects! Global variables!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.