CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Similar documents
CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

CS 302: Introduction to Programming

Lecture 5: Methods CS2301

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Primitive Data, Variables, and Expressions; Simple Conditional Execution

CS110: PROGRAMMING LANGUAGE I

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

class objects instances Fields Constructors Methods static

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

METHODS. CS302 Introduction to Programming University of Wisconsin Madison Lecture 15. By Matthew Bernstein

CS111: PROGRAMMING LANGUAGE II

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Programming Exercise 7: Static Methods

User Defined Functions

Introduction to Software Development (ISD) Week 3

CSE 143 Lecture 10. Recursion

AP CS Unit 3: Control Structures Notes

CS11 Java. Fall Lecture 1

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

Introduction to Programming (Java) 4/12

What does this program print?

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSE 230 Intermediate Programming in C and C++ Functions

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

PROGRAMMING STYLE. Fundamentals of Computer Science I

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Full file at

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Topic 5: Enumerated Types and Switch Statements

Introduction. C provides two styles of flow control:

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Coding Standards for Java

CS-201 Introduction to Programming with Java

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CIS 110: Introduction to Computer Programming

Example Program. public class ComputeArea {

Conditionals, Loops, and Style

Methods with Parameters and Return Values

CS 251 Intermediate Programming Coding Standards

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

Topic 6 loops, figures, constants

Program Fundamentals

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Computer Science is...

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

CS 351 Design of Large Programs Coding Standards

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Welcome to the Primitives and Expressions Lab!

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

CS111: PROGRAMMING LANGUAGE II

M e t h o d s a n d P a r a m e t e r s

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CIS 110 Introduction to Computer Programming 8 October 2013 Midterm

CSCI 161 Introduction to Computer Science

Object-Oriented Programming

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Name Section: M/W T/TH Number Definition Matching (8 Points)

Java Coding style guide 1. Java. Coding Style Guide. (July 2015)

COMP-202: Foundations of Programming

Chapter 5 Methods / Functions

About this exam review

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Recap: Assignment as an Operator CS 112 Introduction to Programming

CIS 110 Introduction to Computer Programming Summer 2014 Midterm. Name:

Condi(onals and Loops

CEN 414 Java Programming

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

CS Programming I: Primitives and Expressions

Name Section: M/W T/TH Number Definition Matching (6 Points)

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

CS-201 Introduction to Programming with Java

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Introduction to the course and basic programming concepts

Chapter 6 Methods. Dr. Hikmat Jaber

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 139 Practice Midterm Questions #2

Advanced Computer Programming

Introduction to Programming Using Java (98-388)

Assignment Marking Criteria

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Anatomy of a Java Program: Comments

Topic 4 Expressions and variables

CS 112 Introduction to Programming

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

CSE 11 Style Guidelines

Research Group. 2: More types, Methods, Conditionals

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Documentation Requirements Computer Science 2334 Spring 2016

Project 1: How to Make One Dollar

Transcription:

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA Chapter 5: Methods Lecture 10 1

PROBLEM What if I was using a lot of different arrays and often wanted to print out their contents? I would have to have that same for loop every time I wanted to print out the array contents Solution: Use Methods! 2

METHODS A method is a named sequence of instructions We have already seen many methods main Math.pow() in.next() System.out.println() Method Man loves methods etc. 3

METHOD CALLING CONVENTIONS [identifier].[methodname]([arguments]) System.out.println("Hello"); Math.pow(2, 4); System.out.println(x); Multiple arguments always seperated by commas (,) Identifiers can be class or variable names Variable Names if calling on a reference variable (like Strings) Class Names if calling a static method 4

METHOD BASICS Basic Idea break code down into simple building blocks Black Box when using methods other people have written, we don't need to know how they work TV example Math.pow Methods take in input (arguments) and give back output (return values) 5

CALLING METHODS Arguments = input Can have 0 or many arguments Go inside the parenthesis Ex.: Math.pow(2, 4) or rand.nextint() Defined by method parameters Return Value Can only have 0 or 1 return value Ex. Math.pow can only return 1 value, to do additional powers must call Math.pow multiple times with different parameters Specified by the "return" keyword 6

LUNCH EXAMPLE class Lunch { main { sandwich = makesandwich(bread, peanutbutter, jelly); drink = pourdrink(cup, water); turnontv(); eatlunch(sandwhich, drink); 7

MATH.POW /** Computes a base raised to a positive power @param base the base @param power the power to raise the base to, must be >= 0 @return base^power, or 1 if base < 0 */ public static double pow(double base, double power) { double sum = 1; for (int i = 1; i <= power; i++) { sum *= base; return sum; 8

IMPLEMENTING METHODS Methods go outside the main method but inside the class definition Methods have: Method Header public static modifiers like the main method (these will be explained eventually) Return type Name camelcase convention like variables Type and name for each parameter variable Method Body (code to execute) Lets make our own Math.pow method header: public static double mypow(double base, double exponent) 9

METHOD BODY The body of the method is defined by braces and that is the code that will execute when the method is called public static double mypow(double base, double exponent) { //method body //must return a double at the end of the method 10

METHOD COMMENTS Use javadoc comments /**...*/ above the method header /** */ Computes a base raised to a positive power @param base the base @param power the power to raise the base to, must be >= 0 @return base^power, or 1 if base < 0 public static double mypow(double base, double exponent) 11

COMMON ERRORS public static int mydivide(a, b) { return a/b; Forgot the parameter variable types public static mymultiply(int a, int b) { return a*b; Forgot the method return type 12

COMMON ERRORS public static int rectarea(double length, double width) { return length*width; Return type doesn't match what the method body returns 13

PRACTICE 1 Write a method to compute the area of a cube or a rectangular block Input: (validate input type) Height Width Depth Output: Volume = height * width * depth 14

WHY DO WE USE METHODS? Increase modularity Increase readability / maintainability Reduce redundancy Ex. P1: Multiple Validation loops -> a single validation method Multiple modes -> multiple methods (better style, easier debugging, etc.) 15

CALLING METHODS Yes Is method static? No ClassName.methodName(arguments) ex. Math.pow(2, 4); objectname.method(arguments) ex. in.nextline() or rand.nextint(10) For now, we will only create static methods If calling static methods that are defined within the same class that they are being called from, the ClassName. identifier can be dropped from the method call (just call the method using its name) 16

ARGUMENTS VS PARAMETERS Arguments (book calls them "parameter values") get passed to the method Parameters (book calls them "parameter variables") are defined in the method header Arguments must match the parameter definitions in type, order, and number Do not need to have the same name Argument values get COPIED into the parameter variables Changing the parameter does NOT change the original argument 17

ARGS VS PARAMETERS EXAMPLE int a = 4, b = 5; int area = rectarea(a, b);... public static int rectarea(int width, int height) {... Blue = arguments Red = parameters Arguments must match parameters in number, order, and type a's value is copied to width b's value is copied to height 18

WHAT IS THE VALUE OF X? int x = 4; double y = dosomething(x);... public static double dosomething(int z) { for (int i = 0; i < 3; i++) z = z + i; return z; 19

VARIABLE SCOPE Just like what we talked about in ifs and loops A variable declared within braces is ONLY valid within those braces That means you can't use variables defined in a method outside of that method!!! Can use the same variable name in different scopes Ex. public static double rectarea(int length, int width) public static double cubevolumn(int lenght, int width, int depth) 20

RETURN STATEMENT Immediatly exits the method Can return Literal return 4; Variable return x; Result of an expression return (x && y (3+z < 5)); Result of another method call return dosomething(x); Return type must match the type in the method header If the method returns nothing, it is of type void 21

VOID METHODS Ex. public static void main(string[] args) Used when the method doesn't return anything Often used for displaying things Can still use the return statement to exit the method immediatly In this case the statement is simply: return; printstars(3, 4);... public static void printstars(int width, int height) { for (int i = 0; i < width; i++) for (int j = 0; j < width; j ++) print("*"); print("\n"); 22

RETURN VS. BREAK for (int i = 0; i < 10; i++) { if (i == 5) break; Vs for (int i = 0; i < 10; i++) { if (i == 5) return; Break simply breaks out of the current loop What would happen in a nested loop? Return immediatly exits the method and returns the return value (if any) What would happen in a nested loop? 23

RETURN WITHIN CONDITIONALS public static String getday(int day) { if (day == 1) return "Sunday"; if (day == 2) return "Monday"; if (day == 3) return "Tuesday";... Note we don't need else ifs because the return statement exits the method immediately! If we do branch every possible traversal must have a return statement! 24

Practice 2 (take home) Remember we had a practice (refer to HopeAndChange.java on the course website under In-Class Example Code tab) Let s do the same thing but now we use a static method to calculate change given coin value (25 for quarter, 10 for dime, 5 for nickel, 1 for penny), coin name ( quarter, dime, nickel, penny ), change (centsleft defined previously). So the parameter values for this method should be coinvalue, coinname, centsleft with appropriate data types, respectively. The method should be able to print out number of coins (quarters, dimes, nickels or pence) AND return the remainder (centsleft). In the main method, call the method for the number of quarters, dimes, nickels, pennies. 25