Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 1341 Topic 5 Methods © 2013 Ken Howard,

Similar presentations


Presentation on theme: "CSE 1341 Topic 5 Methods © 2013 Ken Howard,"— Presentation transcript:

1 CSE 1341 Topic 5 Methods © 2013 Ken Howard,
Southern Methodist University 1

2 Summary of topics covered:
Methods Java API java.lang.Math static methods static fields Method signature Return type, return statement Passing values between methods Casting/promotion Random numbers Method overloading 2

3 Making Stuff Happen Java Program Java Virtual Machine
Java program control must occur within a method. Methods must be contained within a class. All Java programs require a minimum of one method: public static void main(String[] args) Java Program Class Class Class method method method method main method Java Virtual Machine

4 Making Stuff Happen When methods get large and/or complex, they can be broken into more manageable pieces…more methods. Flow control is passed to another method, then returns to the place it left off. { } { } { }

5 main otherMethod 1 2a 2 2b 3 2c 4

6 We’ll learn about these later in the semester.
Making Stuff Happen Invoking a method requires the name of the method preceded by the name of the identifier where the method is located, separated by a period. (.) MethodLocation.method(optional parameters); The method location must be either: The name of a class A variable which refers to an object. Math.pow(5,2); These methods are declared as static. Ball b = new Ball(); b.bounce(); We’ll learn about these later in the semester.

7 Using What is Already Available
You can write your own methods. You can also use methods in classes that are provided to you. The Java Application Programming Interface (API) contains many of these that we will use. Many companies make money creating and selling Java class libraries for others’ use. Related classes are typically grouped into packages so that they can be imported into programs and reused import java.util.Scanner;

8 API Class Math Math.abs(-45);
All methods in the class Math are static methods You can call any static method by specifying its class name, followed by a dot (.) and the method name To use one of these methods in your Java program: Precede the name of the method with the class name Math and the dot (.) separator Math.abs(-45);

9 Popular static methods in class Math

10 static fields A class can also contain data constants
A field containing a constant value that may be needed by others Accessing the value of a static field requires the name of the field preceded by the name of the identifier where the field is located, separated by a period. (.) MethodLocation.fieldName; Class Math declares commonly used mathematical constants The ratio of a circle’s circumference to its diameter Math.PI Value is the base value for natural logarithms Math.E Value is

11 main is a static method When you execute the Java Virtual Machine (JVM) with the java command, the JVM attempts to invoke the main method of the class you specify Declaring main as static allows the JVM to invoke main without creating an object of the class JVM implicitly calls YourClassName.main();

12 Java Program JVM ClassA ClassB implicitly calls main static methodQ
static methodX static methodR static methodY static methodS Invoke other static methods in the same class using just the method name: methodX(); Invoke static methods in the another class using just the class and method name: ClassB.methodX();

13 Declaring Methods Class MaximumFinder (Fig. 5.3) has two methods—main (lines 8–25) and maximum (lines 28–41) The maximum method determines and returns the largest of three double values Most methods do not get called automatically You must call method maximum explicitly to tell it to perform its task { } main maximum

14 Parameter list is empty ()
Declaring Methods Format: Parameter list is empty () OR is one or more variable names preceded by its type, each separated by a comma. you name the method keywords keyword keyword public static void methodName(parameters) Examples: public static void doSomething() public static void doAnotherThing(int x) public static void doMore(double d, String s)

15

16

17

18 Anatomy of a Method Signature
public static void methodName(parameters) public Available for use by methods of this and other classes. For now, make all your methods public. static Method can be called using just the class name. MyClass.methodName(); For now, begin every method declaration with the keywords public and static We’ll learn about non-public and non-static methods in Chapter 7.

19 The Return Type public static void methodName(parameters); A method can optionally return something to its caller as its last step. Accomplished with a return statement. When a method returns something, the type of data being returned must be declared in the method signature. When nothing is returned, the method return type is declared as void.

20 The Return Type public static void displayYourName() {
String s = “Ken”; System.out.println(s); } public static String tellMeYourName() { String s = “Ken”; return s; } public static void main(String[] args) { String myString = tellMeYourName(); displayYourName(); }

21 Naming Methods A method name uses an identifier which contains: letters digits underscores dollar signs Name has no spaces and may not begin with a digit Convention (not rule): Begin with a lowercase letter, then capitalize the second word and each subsequent word in the name of a method. Java is cAse sEnSITive dog ≠ Dog

22 More About Methods If the parentheses after the method name are empty, the method does not require additional information to perform its task For a method that requires additional information to perform its task, one or more parameters represent that additional information Defined in a comma-separated parameter-list located in the parentheses that follow the method name Each parameter must specify a type and an identifier A method’s parameters are considered to be local variables of that method and can be used only in that method’s body

23 Anatomy of a Method Method header Method body return Statement
Modifiers, return type, method name and parameters public static int myOtherMethod (int i, String s) { //method contents go here //variables i and s can be used within the method //the contents of i and s are passed in from //where the method is call. return 2010; } return Statement Returns a value (or just control) to the point in the program from which the method was called Method body Delimited by left and right braces. Contains one or more statements that perform the method’s task

24 Calling Methods public static void main(String[] args) {
//main method contents go here //call to myOtherMethod follows… int x = myOtherMethod(5,”Foo”); } A method call supplies arguments for each of the method’s parameters There must be one argument for each parameter Each argument must be “consistent with” the corresponding parameter’s type returned value here public static int myOtherMethod (int i, String s) { //method contents go here //variables i and s can be used within the method //the contents of i and s are passed in from //where the method is call. return 2010; }

25 Calling Methods Three ways to call a method:
Using a method name by itself to call another method of the same class Using a variable that represents an object, followed by a dot (.) and the method name to call a method of that object Using the class name and a dot (.) to call a static method of a class

26 What will display? public class PassingPractice {
public static void main(String[] args) int x = 5; String myString = “Foo”; methodAbc (x, myString); System.out.println(x); } public static void methodAbc(int x, String s) x++; System.out.println(s); System.out.println(x++); What will display?

27 int x = 1; int y = x + 5; int z = y + 10;
Could be a block for a method, an if, while, or for statement int x = 1; This won’t compile because y no longer exists at this point! int y = x + 5; int z = y + 10;

28 public static void main(String[] args)
public class MyClass public static void main(String[] args) 1 Passes the value 5 (not the variable y) int y =5; int z = tripleIt( y ); 4 Assigns z the value 15, returned from tripleIt method public static int tripleIt(int aNumber) 2 int aVal = aNumber * 3; return aVal; Sets variable aNumber to 5 3 Returns the value 15 (not the variable aVal)

29 Returning Flow Control
If the method does not return a result, control returns when the program flow reaches the method-ending right brace or when the statement return; executes If the method returns a result, the statement return expression; evaluates the expression, then returns the result to the caller

30 Casting/Promotion Remember this? May also be needed when passing data
int x = 5; int y = 10; double z = (double) x / y; Remember this? May also be needed when passing data between methods public static void myMethod(double d) { // do stuff } public static void myOtherMethod() { int x = 5; myMethod(x); } Instead, promote the int to a double: myMethod((double)x); Compilation error. Data type mismatch.

31 Casting/Promotion Argument promotion—converting an argument’s value, if possible, to the type that the method expects to receive in its corresponding parameter These conversions may lead to compilation errors if Java’s promotion rules are not satisfied The promotion rules specify which conversions are allowed—that is, which conversions can be performed without losing data The promotion rules apply to expressions containing values of two or more primitive types and to primitive-type values passed as arguments to methods Each value is promoted to the “highest” type in the expression

32 Java Application Programming Interface (API)
Java contains many predefined classes that are grouped into categories of related classes called packages Known as the Java Application Programming Interface (Java API), or the Java class library Some key Java API packages are described in Fig. 5.5 Overview of the packages in Java SE 6 Additional information about a predefined Java class’s methods Index link shows alphabetical list of all the classes and methods in the Java API Locate the class name and click its link to see the online description of the class METHOD link shows a table of the class’s methods Each static method will be listed with the word “static” preceding the method’s return type

33

34

35

36

37 Random Numbers Approach #1: java.util.Random //
import java.util.Random; Random r = new Random(); Methods: r.nextInt(int n) //Returns int from 0 to n-1 r.nextDouble() //Returns double between 0.0 and 1.0 r.nextBoolean() //randomly returns true or false r.nextInt() // Generates a random int value in the // range –2,147,483,648 to //+2,147,483,647, inclusive

38 Random Numbers Approach #2: java.lang.Math Static Method:
Math.random() //Returns double between 0.0 and 1.0 Math method random can produce only double values in the range 0.0 £ x < 1.0, where x is the value returned by method random

39 © 1992-2010 by Pearson Education, Inc. All Rights Reserved.

40 Random Numbers If truly random, then every value in the range should have an equal chance (or probability) of being chosen each time nextInt is called The numbers are actually pseudorandom numbers—a sequence of values produced by a complex mathematical calculation The calculation uses the current time of day to seed the random-number generator such that each execution of a program yields a different sequence of random values Class Random provides another version of method nextInt that receives an int argument and returns a value from 0 up to, but not including, the argument’s value

41

42

43 Recommended Approach with Random Numbers
number = shiftingValue randomNumbers.nextInt(scalingFactor); Where shiftingValue specifies the first number in the desired range of consecutive integers and scalingFactor specifies how many numbers are in the range Returns a random number from within the sequential range beginning with shiftingValue and ending with scalingFactor – 1.

44 Recommended Approach with Random Numbers
number = shiftingValue + differenceBetweenValues * randomNumbers.nextInt(scalingFactor); In this example, differenceBetweenValues represents the constant difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range.

45 Method Overloading Methods of the same name can be declared in the same class, as long as they have different sets of parameters Called method overloading Java compiler selects the appropriate method to call by examining the number, types and order of the arguments in the call Used to create several methods that perform the same or similar tasks on different types or different numbers of arguments Math methods abs, min and max are overloaded with four versions each: One with two double parameters One with two float parameters One with two int parameters One with two long parameters

46 Method Overloading

47 Method Overloading

48 Method Overloading square(5) square(5.0)
Literal integer values are treated as type int square(5) Literal floating-point values are treated as type double square(5.0) By default, floating-point values are displayed with six digits of precision if the precision is not specified in the format specifier. int double

49 public class MyClass { public static void main(String[] args) { doSomething( 5 ); //a literal int doSomething(5.0); //a literal double } public static void doSomething (double d) {//method contents } public static void doSomething (int i)  } //end class MyClass Calls this method Calls this method

50 Method Overloading Compiler distinguishes overloaded methods by their signature A combination of the method’s name and the number, types and order of its parameters Internally, the compiler uses longer method names that include the original method name, the types of each parameter and the exact order of the parameters to determine whether the methods in a class are unique in that class. Method calls cannot be distinguished by return type Overloaded methods can have different return types if the methods have different parameter lists Overloaded methods need not have the same number of parameters

51

52


Download ppt "CSE 1341 Topic 5 Methods © 2013 Ken Howard,"

Similar presentations


Ads by Google