Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

Similar documents
More on methods and variables. Fundamentals of Computer Science Keith Vertanen

The Command Shell, Libraries and Clients, Formatted Printing. Fundamentals of Computer Science

Libraries, clients, prin/

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Conditionals, Loops, and Style

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

A Foundation for Programming

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Lecture 5: Methods CS2301

AP CS Unit 3: Control Structures Notes

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

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

Introduction to Computer Science Unit 2. Notes

DATA TYPES AND EXPRESSIONS

JAVA OPERATORS GENERAL

Variables and data types

CS110: PROGRAMMING LANGUAGE I

Introduction to Computer Science Unit 2. Notes

1.1 Your First Program

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

MODULE 02: BASIC COMPUTATION IN JAVA

Chapter 5: Methods. by Tony Gaddis. Starting Out with Java: From Control Structures through Objects. Fourth Edition

Sta$cs and forma.ng numbers

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Methods. Eng. Mohammed Abdualal

Chapter 6 Methods. Dr. Hikmat Jaber

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

2.1 Functions. f (x, y, z)

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

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CONDITIONAL EXECUTION

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013

1.1 Your First Program

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

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

CSc 2010 Principles of Computer Science, Fall 2013 Practice Problems for Midterm 3* * 3 17 % 9-20 % (26 / 7) "2"

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Condi(onals and Loops

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

Lec 3. Compilers, Debugging, Hello World, and Variables

Excep&ons and file I/O

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Inheritance and objects

Inheritance and objects

CS115 Principles of Computer Science

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

CS110D: PROGRAMMING LANGUAGE I

Methods. CSE 114, Computer Science 1 Stony Brook University

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

Lecture 2: Intro to Java

CS171:Introduction to Computer Science II

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

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Java generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

1.5 Input and Output. Introduction to Computer Science Sedgewick and Wayne Copyright 2007

EXCEPTIONS. Fundamentals of Computer Science I

Last Name: Circle One: OCW Non-OCW

COMP 110/L Lecture 5. Kyle Dewey

INFO Object-Oriented Programming

4 Programming Fundamentals. Introduction to Programming 1 1

Chapter 4 Defining Classes I

Fundamentals of Programming Data Types & Methods

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

Java Socket Workshop. July Purpose of this workshop:

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CT 229 Methods Continued

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

CS1150 Principles of Computer Science Methods

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

University of Palestine. Mid Exam Total Grade: 100

Primitive Data, Variables, and Expressions; Simple Conditional Execution

JAVA Programming Concepts

2.1, 2.2 Functions and Libraries

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012

Input and output thus far. Graphics and sound Input. New input/output capabilities. Output. StdDraw overview. StdDraw. StdAudio

More types, Methods, Conditionals. ARCS Lab.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Computational Expression

Chapter 2: Programming Concepts

CS 231 Data Structures and Algorithms, Fall 2016

The Math Class. Using various math class methods. Formatting the values.

Using data types. Overview. Data types. Why custom data types? Using data types. A slight diversion: Methods. Data type. Data type

Methods. Bok, Jong Soon

2.1 Functions. 2.1 Functions. A Foundation for Programming. Functions (Static Methods) x y. f (x, y, z)

CONDITIONAL EXECUTION

Transcription:

Static methods http://xkcd.com/221/ Not actually a valid Java static method Fundamentals of Computer Science Keith Vertanen

One big main(): Programs thus far public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = (int) (Math.random() * 11) + 2; System.out.println("Rolling dice until I get " + target + "."); do int dice1 = (int) (Math.random() * 6) + 1; int dice2 = (int) (Math.random() * 6) + 1; sum = dice1 + dice2; System.out.println(dice1 + " + " + dice2 + " = " + sum); rolls++; while (sum!= target); System.out.println("It took " + rolls + " rolls."); 2

One big main(): Programs thus far public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = (int) (Math.random() * 11) + 2; % java DiceRolling Rolling dice until I get 4. System.out.println("Rolling dice until I get 6 " + + 1 target = 7 + "."); 3 + 3 = 6 5 + 5 = 10 do 5 + 1 = 6 int dice1 = (int) (Math.random() * 6) + 1; 3 + 3 = 6 int dice2 = (int) (Math.random() * 6) + 1; 6 + 2 = 8 sum = dice1 + dice2; 1 + 4 = 5 System.out.println(dice1 + " + " + dice2 4 + + " 3 = = " 7 + sum); rolls++; 5 + 5 = 10 5 + 4 = 9 while (sum!= target); 4 + 1 = 5 System.out.println("It took " + rolls + " rolls."); 1 + 6 = 7 6 + 4 = 10 2 + 2 = 4 It took 14 rolls. 3

Programs thus far Problems with one big main(): Doesn't scale to complex programs Often find ourselves repeating similar code public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = (int) (Math.random() * 11) + 2; "Repeated code is evil!" System.out.println("Rolling dice until I get " + target + "."); do int dice1 = (int) (Math.random() * 6) + 1; int dice2 = (int) (Math.random() * 6) + 1; sum = dice1 + dice2;... 4

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); int num double r int x = Integer.parseInt(args[0]); = Double.parseDouble(args[1]); = StdIn.readInt(); double rand = Math.random(); double v = Math.pow(10.0, -2.3582); StdDraw.setXscale(0.0, 10.0); 5

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); int num = Integer.parseInt(args[0]); double r = Double.parseDouble(args[1]); int x = StdIn.readInt(); double rand = Math.random(); Some methods return a value. double v = Math.pow(10.0, -2.3582); StdDraw.setXscale(0.0, 10.0); 6

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); Some methods return nothing int num double r int x = Integer.parseInt(args[0]); = Double.parseDouble(args[1]); = StdIn.readInt(); double rand = Math.random(); double v = Math.pow(10.0, -2.3582); StdDraw.setXscale(0.0, 10.0); Some methods return nothing 7

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); int num = Integer.parseInt(args[0]); double r = Double.parseDouble(args[1]); Some methods take a single parameter. int x = StdIn.readInt(); double rand = Math.random(); double v = Math.pow(10.0, -2.3582); StdDraw.setXscale(0.0, 10.0); 8

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); int num = Integer.parseInt(args[0]); double r = Double.parseDouble(args[1]); int x = StdIn.readInt(); double rand = Math.random(); double v = Math.pow(10.0, -2.3582); Some methods take no parameters StdDraw.setXscale(0.0, 10.0); 9

Static methods Using static methods Already seen loads of "helper" methods: System.out.println("Hello world"); StdDraw.setPenColor(StdDraw.GRAY); int num double r int x = Integer.parseInt(args[0]); = Double.parseDouble(args[1]); = StdIn.readInt(); double rand = Math.random(); double v = Math.pow(10.0, -2.3582); StdDraw.setXscale(0.0, 10.0); Some methods take two parameters. 10

Methods: Methods Like a mathematical function Given some inputs, produce an output value Methods allows building modular programs Reuse code, only invent the wheel once When a method is called: Control jumps to the method code Argument passed to method copied to parameter variables used in method Method executes and (optionally) returns a value Execution returns to calling code 11

Flow of control public class MethodJumping public static void printworld() System.out.print("world"); public static int addnums(int num1, int num2) int result = num1; result = num1 + num2; return result; public static void main(string [] args) System.out.print("Hello"); System.out.print(" "); printworld(); System.out.print(", 1 + 2 = "); int a = addnums(1, 2); System.out.println(a); % java MethodJumping Hello world, 1 + 2 = 3 12

Anatomy of a method Goal: helper method than can draw a random integer between start and end (inclusive) "Everybody can call me" "I promise to return a value of this type" "I need to know these things to do my job" public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; "All done, end this method and return the result to whoever called me" "The name I demand people use when they want my random goodness" 13

Terminology of a method Goal: helper method than can draw a random integer between start and end (inclusive) access modifier return type parameters / arguments public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; return statement method name Naming convention: start lowercase, uppercase each new word 14

Method signature Signature: a method's name plus the number and type of its parameters Note: does NOT include the return type! method's signature public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; 15

Calling our new method Use handy new method in DiceRolling Add somewhere inside public class 's public class DiceRolling public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; public static void main(string [] args) int rolls = 0; int sum = 0; int target = getrandomnum(2, 12); System.out.println("Rolling dice until I get " + target + "."); do int dice1 = getrandomnum(1, 6); int dice2 = getrandomnum(1, 6); sum = dice1 + dice2;... 16

Calling our new method Alternative: put method in new class Allows us to create a class with a bunch of helper methods (just like StdIn.java, StdDraw.java) public class RandomUtil // Return random integer in [start, end] inclusive public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; // Return random integer in [0, end] inclusive public static int getrandomnum(int end) return (int) (Math.random() * (end + 1)); getrandomint() is overloaded: Two methods with same name, but different signatures (i.e. different number or types of parameters) 17

Using our new class Put RandomUtil.java in same directory Methods qualified with RandomUtil. in front public class DiceRolling public static void main(string [] args) int rolls = 0; int sum = 0; int target = RandomUtil.getRandomNum(2, 12); System.out.println("Rolling dice until I get " + target + "."); do int dice1 = RandomUtil.getRandomNum(1, 6); int dice2 = RandomUtil.getRandomNum(1, 6); sum = dice1 + dice2; System.out.println(dice1 + " + " + dice2 + " = " + sum); rolls++; while (sum!= target); System.out.println("It took " + rolls + " rolls."); 18

A safer version Problem: What if caller sends in start > end? public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; while (true) System.out.print(RandomUtil.getRandomNum(3, 1) + " "); 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3... 19

A safer version public static int getrandomnum(int start, int end) if (start < end) return (int) (Math.random() * (end - start + 1)) + start; return (int) (Math.random() * (start - end + 1)) + end; As soon as a return is hit, method done while (true) System.out.print(RandomUtil.getRandomNum(3,1) + " "); 3 1 1 1 2 2 3 1 1 1 3 2 3 1 2 1 3 3 2 2 2 2 1 3 1 3 1 3 3 3 1 3 2 1 2 3 1 2 2 3 2 1 1 3 2 2 2 1 3 2 2 2 3 3 1 1 1 3 3 3 1 3 2 1 3 3 1 3 3 3 3 1 1 2 1 1 3 1 1 3 1 1 2 2 2 2 2 1 2 3 2 2 3 3 3 3 2 1 2 2... 20

Pass by value Java passes parameters by value (by copy) Changes to primitive type parameters do not persist after method returns Primitive types: int, double, char, long, boolean public static int sum(int a, int b) int result = a + b; a = 0; b = 0; return result; int c = 2; int d = 3; System.out.println("sum = " + sum(c, d)); System.out.println("c = " + c); System.out.println("d = " + d); % java PassByVal sum = 5 c = 2 d = 3 21

Pass by value, puzzler #2 public static int sum(int c, int d) int result = c + d; c = 0; d = 0; return result; int c = 2; int d = 3; System.out.println("sum = " + sum(c, d)); System.out.println("c = " + c); System.out.println("d = " + c); % java PassByVal sum = 5 c = 2 d = 3 Variables c & d in main program are not the same as c & d in sum()! 22

Array parameters Arrays can be passed as arguments public class AverageArray public static double average(int [] nums) long total = 0; for (int i = 0; i < nums.length; i++) total += nums[i]; return (double) total / (double) nums.length; public static void main(string [] args) int [] vals = new int[1000]; for (int i = 0; i < vals.length; i++) vals[i] = RandomUtil.getRandomNum(1, 10); System.out.println("avg " + average(vals)); % java AverageArray avg 5.508 23

Quiz: variable scope What lines are the following variables in scope? nums total vals i 4-7 4-7 12-15 5-6, 13-14 00 public class AverageArray 01 02 public static double average(int [] nums) 03 04 long total = 0; 05 for (int i = 0; i < nums.length; i++) 06 total += nums[i]; 07 return (double) total / (double) nums.length; 08 09 10 public static void main(string [] args) 11 12 int [] vals = new int[1000]; 13 for (int i = 0; i < vals.length; i++) 14 vals[i] = RandomUtil.getRandomNum(1, 10); 15 System.out.println("avg " + average(vals)); 16 17 24

Quiz: variable scope What is the value of total printed at the end of main()? 123 What if we remove line 4? Compile error: total cannot be resolved to a variable 00 public class AverageArray 01 02 public static double average(int [] nums) 03 04 long total = 0; 05 for (int i = 0; i < nums.length; i++) 06 total += nums[i]; 07 return (double) total / (double) nums.length; 08 09 10 public static void main(string [] args) 11 12 long total = 123; Added line 13 int [] vals = new int[1000]; 14 for (int i = 0; i < vals.length; i++) 15 vals[i] = RandomUtil.getRandomNum(1, 10); 16 System.out.println("avg " + average(vals)); 17 System.out.println("total " + total); 18 19 Added line 25

Quiz: variable scope What if we remove line 12? Compile error: total cannot be resolved to a variable 00 public class AverageArray 01 02 public static double average(int [] nums) 03 04 long total = 0; 05 for (int i = 0; i < nums.length; i++) 06 total += nums[i]; 07 return (double) total / (double) nums.length; 08 09 10 public static void main(string [] args) 11 12 long total = 123; 13 int [] vals = new int[1000]; 14 for (int i = 0; i < vals.length; i++) 15 vals[i] = RandomUtil.getRandomNum(1, 10); 16 System.out.println("avg " + average(vals)); 17 System.out.println("total " + total); 18 19 26

Static methods Helper functions Summary Perform calculations Output data Consolidate similar code to one location Methods have: 0 or more input parameters An (optional) return value We're already experts at using them StdDraw.show(100), StdIn.readInt(), Math.abs() Now we can make our own methods! 27