• No results found

Lecture 2-Methods.ppt

N/A
N/A
Protected

Academic year: 2020

Share "Lecture 2-Methods.ppt"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

Lecture 1B- Methods

COMP2111 COMP2111: :

Object Oriented Programming Object Oriented Programming Ansif Arooj

(2)

Preparation

 Scene so far has been background material and experience

 Computing systems and problem solving

 Variables

 Types

 Input and output

 Expressions

 Assignments

 Using objects

 Standard classes and methods

 Decisions (if, switch)

 Loops (while, for, do-while)

 Next: Experience what Java is really about

 Design and implement objects representing information

(3)

Object-oriented programming

 Basis

 Create and manipulate objects with attributes and behaviors that the programmer can specify

 Mechanism

 Classes

 Benefits

 An information type is design and implemented once

 Reused as needed

(4)

Known Classes

 Classes we’ve seen

 String

 Rectangle

 Scanner

 System

 Classes we’ll be seeing soon

 BigDecimal

 But the first step is on creating methods…

(5)
(6)

Methods we’ve seen

 We’ve seen method (function) before

 System.out.println (“Hello world”);

 The way to name methods is the same as variables

 allTheWordsTogether

 With the first letter of each word capitalized

 Except the very first letter is lower case

(7)

Our first class with methods

public class Methods1 {

public static void main (String args[]) {

Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt();

if ( value == 1 ) validValue();

else if ( value == 2 ) validValue();

(8)

Our first class with methods, continued

public static void invalidValue() {

System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit.");

System.exit (0); }

public static void validValue() {

System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!");

System.out.println ("The program will now exit."); System.exit (0);

}

(9)

Program Demo

(10)

What’s happening there

public static void validValue() {

System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!");

System.out.println ("The program will now exit."); System.exit (0);

}

public static void main (String args[]) {

Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt();

if ( value == 1 ) validValue(); // ...

} Scanner 10

stdin

(11)

Notes on these methods

 None of those two methods return a value

 Notice the “void” before the method name

 And none take in any parameters

(12)

Return Values

(13)

The return keyword

 The return keyword immediately stops execution of a method

 And jumps back to whatever called that method

 And possibly returns a value (we’ll see this next)

 Consider the following method

public static void foo (int x) { if ( x == 1 )

return;

System.out.println (“x is not 1”); }

(14)

Return values

 At some point in those methods, Java must be told to take a value and “pass” it back

 Consider angleSin = Math.sin (90 * PI/180.0);

 At some point in the Math.sin() method, the sin has been computed

 And that value must be “passed back” to be stored in angle

 This is called “returning” a value from a method

 Note that some methods don’t return a value

 System.out.println(), for example

(15)

Return values (aka return types)

public class Methods2 {

public static int returnsAValue () { return 1;

}

public static double alsoReturnsAValue() { return 1.0;

}

public static void main (String args[]) { int value1 = returnsAValue();

System.out.println (value1);

double value2 = alsoReturnsAValue(); System.out.println (value2);

// The following line requires a cast

int value3 = (int) alsoReturnsAValue(); System.out.println (value3);

} }

(16)

Program Demo

 Methods2.java

(17)

Return types

 All a return statement does is take the value

 Which could be a number

 Or a value in a variable

 Or an expression (such as x+1)

(18)

Parameters

 Sometimes you need to pass in parameters to tell a method how to perform

 Consider Math.sin() – it needs to know the angle

 The parameters are listed between the parenthesis after the method name

 public static void main (String args[])

 The methods we will study next compute (and return) x2, x3,

and x4

(19)

The methods

public static int square (int x) { int theSquare = x * x;

return theSquare; }

public static int cube (int x) { return x * x * x;

}

public static int fourthPower (int x) { return square(x) * square(x);

(20)

A method with multiple parameters

public static int squareOrCube (int which, int value) { if ( which == 1 )

return value * value; else if ( which == 2 ) {

int cube = value * value * value; return cube;

} else

return 0; }

(21)

The main() method

import java.util.*;

public class Methods3 {

// the previous methods go here

public static void main (String args[]) {

Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt();

int theSquare = square(value);

System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value));

System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value));

System.out.println ("Fourth power is " + fourthPower (value)); }

}

(22)

Program Demo

 Methods3.java

(23)

Returning objects

 We can also return objects from methods

 What gets returned is the reference

to the object

public class Methods4 {

public static String getCourse () { String name = "CS 101";

return name; }

(24)

Program Demo

 Methods4.java

(25)

Modifying parameters

 Consider the following code

public class Methods5 {

public static void changeValue (int x) { x = 7;

}

public static void main (String args[]) { int y = 5;

changeValue(y);

System.out.println (y); }

}

(26)

Program Demo

 Methods5.java

(27)

Pass by value

 Java is a pass-by-value language

 This means that a COPY of the parameter’s value is passed into the method

 If a method changes that value, only the COPY is changed

 Once the method returns, the copy is forgotten

 And thus the change is not visible outside the method

 There are other manners of returning values that are used in other languages

 Pass by reference

(28)
(29)

Variable scoping

 A variable is visible within the block it is declared

 Called the “scope” of the variable

public class Scoping { static int z

public static void foo (int x) { // ...

}

public static void bar () { // ...

}

public static void main (String[] args) { int y;

// ... }

}

29 This local variable is visible until

the end of the main() method This variable is visible

anywhere in the Scoping class

(30)

More on parameter passing

(31)

Modifying parameters

 Consider the following code

public class Methods5 {

public static void changeValue (int x) { x = 7;

}

public static void main (String args[]) { int y = 5;

changeValue(y);

System.out.println (y); }

}

 What gets printed?

 5 is printed 31

5 y

(32)

Program Demo

 Methods5.java

(33)

Adding a Method That Takes

Parameters

class Box {

double width; double height; double depth;

double volume() {

return width * height * depth;}

void setDim(double w, double h, double d) {

width = w; height = h;

depth = d; }}

class BoxDemo5 {

public static void main(String args[]) {

Box mybox1 = new Box(); Box mybox2 = new Box(); double vol;

mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9);

vol = mybox1.volume();

System.out.println("Volume is " + vol);

vol = mybox2.volume();

System.out.println("Volume is " + vol);

} }

(34)

Program Demo

 Box2.java

(35)

Method notes summary

 You can put the methods in a class in any order

 Java doesn’t care which one is listed first

 Thus, you can call a method listed later in the method

 This is different than C/C++

 All methods must specify a return type

 If it’s void, then no value is returned

 Parameters can’t be changed within a method

References

Related documents

commitment to you for Quality Assurance & Project Management you will receive a call every week to go through the prior week’s inbound report. In these sessions, we will be

This article presents a framework and industry best practices allowing for the definition of usable metrics and intelligence that employ all the available operational

None of reference is invalid, drug information to opioids under the references from a group of the technologies we cannot show you already on our pdr.. Just some electronic access

We will pay for safety legislation costs , in respect of any bodily injury occurring during the period of insurance , in circumstances where there is also a claim or

1.3.4 The series compensation provides a means of regulating power flowing through two parallel lines by introducing series capacitance in one of the lines,

Insecure internal and cloud-based networks are the access point fraudsters use to seize control of communications accounts and sensitive corporate data.. These six steps

widespread use across England, was recently withdrawn, and a review undertaken 16 following alarming media reports and criticism of poor care. A 2016 Cochrane review found

From the above discussion considering all the parameters (growth, yield and quality) including economics of production it may be concluded that the combination of