Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

Similar documents
CS 112 Introduction to Programming

Building Java Programs

Topic 3 static Methods and Structured Programming

Building Java Programs

Static Methods & Decomposition

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

Entering the world of Javatar

Building Java Programs

Introduction to Computer Programming

Lecture 1: Basic Java Syntax

Building Java Programs

Building Java Programs Chapter 1

clicker question Comments Using comments Topic 3 static Methods and Structured Programming

CSc 110, Spring Lecture 2: Functions. Adapted from slides by Marty Stepp and Stuart Reges

Building Java Programs Chapter 1

CSE 142, Summer 2015

CSE 142, Summer 2014

CSc 110, Autumn Lecture 2: Functions

Procedural decomposition using static methods

Building Java Programs

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

CSE 201 Java Programming I. Smart Coding School website:

Building Java Programs. Introduction to Java Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs. Introduction to Programming and Simple Java Programs

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

A Foundation for Programming

Building Java Programs

CS 112 Introduction to Programming

Building Java Programs

CS 112 Introduction to Programming

Functions (or Static Methods) (Spring 2012)

Topic 7 parameters. Based on slides from Marty Stepp and Stuart Reges from

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

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Building Java Programs

2/15/12. CS 112 Introduction to Programming. Lecture #16: Modular Development & Decomposition. Stepwise Refinement. Zhong Shao

CSc 110, Autumn 2016 Lecture 6: Parameters. Adapted from slides by Marty Stepp and Stuart Reges

Lecture 5: Methods CS2301

CS 112 Introduction to Programming

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

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)

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

A Unicorn Named Sparkle Word Search. A New Friend for Sparkle Coloring Sheet. A Unicorn Named Sparkle s First Christmas Coloring Sheet

Getting Started With Java

Admin. CS 112 Introduction to Programming. Counting Down: Code Puzzle. Counting Down: Code Puzzle

CS 112 Introduction to Programming

The diagram below is only partially complete. Use the terms in the word list to complete the empty boxes. Make dinner

Building Java Programs

Topic 6 loops, figures, constants

CS 112 Introduction to Programming. (Spring 2012)

CS 112 Introduction to Programming. (Spring 2012)

Building Java Programs. Chapter 1: Introduction to Java Programming

Topic 4 Expressions and variables

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

Software and Programming 1

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

AP CS Unit 3: Control Structures Notes

2.1 Functions. f (x, y, z)

1.3 Conditionals and Loops

The CS job market. Building Java Programs Chapter 1. Programming languages. What is programming? Introduction to Java Programming

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

Java Programming. What is a program? Programs Recipes. Programs as Recipes 8/16/12. Pancakes In one bowl. mix: 1½ cup flour

Lecture 2: Operations and Data Types

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CS110D: PROGRAMMING LANGUAGE I

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

Introduction to Computer Science Unit 2. Notes

CS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused

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

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CSE 142. Lecture 1 Course Introduction; Basic Java. Portions Copyright 2008 by Pearson Education

COMPUTATIONAL THINKING

Program Development. Program Development. A Foundation for Programming. Program Development

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

1.3 Conditionals and Loops

Software and Programming 1

CS 251 Intermediate Programming Coding Standards

Chapter 1. Introduction

CS 112 Introduction to Programming

Outline. CIS 110: Introduction to Computer Programming. What is Computer Science? What is computer programming? What is computer science?

Midterms Save the Dates!

CS 106 Introduction to Computer Science I

Full file at

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

CS 351 Design of Large Programs Coding Standards

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

Primitive data, expressions, and variables

Creating a Program in JCreator. JCreator is then used to create our program. But the first step is to create a new file.

CIS 110: Introduction to Computer Programming

Transcription:

Recap: Structure of a Java program CS 112 Introduction to Programming A class: - has a name, defined in a file with same name Convention we follow: capitalize each English word - starts with {, and ends with - includes a group of methods (Spring 2012) Lecture #6: Static Methods and Decomposition Zhong Shao public class <class name> { <>; <>; <>; Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 A static method (a.k.a. function ): - has a name Convention we follow: lowercase first word, capital following - starts with {, and ends with - includes a group of s : - a command to be executed - end with ; Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp A Foundation for Programming Why Introduce Static Methods? q Algorithm: A list of steps for solving a problem. q An example algorithm: "Bake two batches of sugar cookies" any program you might want to write objects static methods & classes graphics, sound, and image I/O arrays primitive data types Preheat oven temperature to 375F. 2. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the timer for 8 min. Place 1st batch of cookies to oven. Allow the cookies to bake. Set the timer for 8 min. Place 2nd batch of cookies to oven. Allow the cookies to bake. Mix ingredients for frosting. Spread frosting and sprinkles. 3. 4. 5. 6. 7. conditionals and loops Math build bigger programs and reuse code 1. text I/O assignment s 8. 9. 10. 11. 12. 13. Readability of the specification? 1

Problem of the Specification Problem of the Specification q Lack of structure: Many tiny steps; tough to remember. A human being typically can only manage seven (plus or minus 2) pieces of information at one time q Redundancy: unnecessary repeat 1. Preheat oven temperature to 375F. 2. Mix the dry ingredients. 3. Cream the butter and sugar. 4. Beat in the eggs. 5. Stir in the dry ingredients. 6. Set the timer for 8 min. 7. Place the first batch of cookies into the oven. 8. Allow the cookies to bake. 9. Set the timer for 8 min. 10. Place the second batch of cookies into the oven. 11. Allow the cookies to bake. 12. Mix ingredients for frosting. 13. Spread frosting and sprinkles. Structured Algorithms q Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 3 Bake the cookies. Set the timer for 8 min. Place the cookies into the oven. Allow the cookies to bake. 4 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. Structured Algorithms q Structured algorithm provides abstraction (hide/ ignore the right details at the right time) 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 3 Bake the cookies. Set the timer. Place the cookies into the oven. Allow the cookies to bake. 4 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. 2

Removing Redundancy A Program with Redundancy q A well-structured algorithm can describe repeated tasks with less redundancy. 1 Preheat oven. 2 Make the cookie batter. 3a Bake the cookies (first batch). 3b Bake the cookies (second batch). 4 Decorate the cookies. // This program displays a delicious recipe for baking cookies. public class BakeCookies { System.out.println( Preheat the oven."); System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); Issue: How to turn the program into structured specification? Structured Algorithm? Static Methods // This program displays a delicious recipe for baking cookies. public class BakeCookies2 { // Step 1: preheat oven System.out.println( Preheat oven to 375F."); // Step 2: Make the cookie batter. System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 3a: Bake cookies (first batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 3b: Bake cookies (second batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 4: Decorate the cookies. System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); q Arrange s into groups and give each group a name. q Each such named group of s is a static method q Writing a static method is like adding a new command to Java. class method A method B method C 3

q Benefits of methods Static Methods denote the structure of a program allow code reuse to eliminate redundancy q A main task of programming is procedural decomposition: dividing a problem into methods class method A method B method C Gives your method a name so it can be executed q Syntax: public static void <name>() { <>; <>; <>; q Example: Declaring a Method public static void printwarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans."); Calling a Method Program with Static Method Executes the method's code q Syntax: <name>(); You can call the same method many times if you like. q Example: printwarning(); Output: This product causes cancer in lab rats and humans. public class FreshPrince { rap(); // Calling (running) the rap method rap(); // Calling the rap method again // This method prints the lyrics to my favorite song. public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down 4

Design and Use Static Methods 1. Design the algorithm. Look at the structure, look for repeated commands 2. Declare (write down) the methods. Arrange s into groups and give each group a name. 3. Call (run) the methods. The program's main method executes the other methods to perform the overall task. Final Cookie Program // This program displays a delicious recipe for baking cookies. public class BakeCookies3 { preheatoven(); makebatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); // Step 1: Preheat oven public static void preheatoven() { System.out.println( Preheat Oven to 375F."); // Step 2: Make the cake batter. public static void makebatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 3: Bake a batch of cookies. public static void bake() { System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 4: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); Summary: Why Methods? Summary: Why Methods? q Makes code easier to read by capturing the structure of the program main should be a good summary of the program q Eliminate redundancy public static () { public static () { Note: Longer code doesn t necessarily mean worse code public static () { 5

Summary: Static Methods Anatomy of a Java Static Method Java static methods ( functions ). Takes zero or more input arguments. Returns one output value or none. Side effects (e.g., output to standard draw). more general than mathematical functions Java static methods. Easy to write your own. input output 2.0 f(x) = x 1.414213 Applications. Scientists use mathematical functions to calculate formulas. Programmers use static methods to build modular programs. You use static methods for both. Examples. Built-in functions: Math.random(), Math.abs(), Integer.parseInt(). Our I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play(). User-defined static methods: main(). More Examples Method Calling Flow overloading q When a method A calls another method B, the program's execution "jumps" into method B, executing its s, then multiple arguments "jumps" back to method A at the point where the method was called. 6

Methods Calling Methods Methods Calling Methods public class MethodsExample { message1(); message2(); System.out.println("Done with main."); public static void message1() { System.out.println("This is message1."); public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); q Output: This is message1. This is message2. This is message1. Done with message2. Done with main. public class MethodsExample { public static void main(string[] public args) static { void message1() { message1(); System.out.println("This is message1."); message2(); public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with main."); System.out.println("Done with message2."); public static void message1() { System.out.println("This is message1."); Summary: Method Control Flow Key point. Static methods provide a new way to control the flow of execution. What happens when a function is called: Control transfers to the function code. Argument variables are assigned the values given in the call. Function code is executed. Return value is assigned in place of the function name in calling code. Control transfers back to the calling code. When NOT to use methods q You should not create static methods for: Only blank lines. (Put blank printlns in main.) Unrelated or weakly related s. (A metric of method design is called coherence.) Note. This is known as "pass by value." 27 7

Static Method Example Development Strategy q Write a program to print these figures using methods. First version (unstructured): Create an empty program and main method. Copy the expected output into it, surrounding each line with System.out.println syntax. Run it to verify the output. Program version 1 Development Strategy 2 public class Figures1 { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("\"); System.out.println(" \"); System.out.println("\"); System.out.println(" \"); System.out.println(""); System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(""); System.out.println("\"); System.out.println(" \"); System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(""); Second version (structured, with redundancy): Identify the structure of the output. Divide the main method into static methods based on this structure. 8

Output Structure Program version 2 The structure of the output: initial "egg" figure second "teacup" figure third "stop sign" figure fourth "hat" figure This structure can be represented by methods: egg teacup stopsign hat public class Figures2 { egg(); teacup(); stopsign(); hat(); public static void egg() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("\"); System.out.println(" \"); public static void teacup() { System.out.println("\"); System.out.println(" \"); System.out.println(""); Program version 2, cont'd. Development Strategy 3 public static void stopsign() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(""); System.out.println("\"); System.out.println(" \"); public static void hat() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(""); Third version (structured, without redundancy): Identify redundancy in the output, and create methods to eliminate as much as possible. Add comments to the program. 9

Output redundancy Program version 3 The redundancy in the output: egg top: reused on stop sign, hat egg bottom: reused on teacup, stop sign divider line: used on teacup, hat This redundancy can be fixed by methods: eggtop eggbottom line // Suzy Student, CSE 138, Spring 2094 // Prints several figures, with methods for structure and redundancy. public class Figures3 { egg(); teacup(); stopsign(); hat(); // Draws the top half of an an egg figure. public static void eggtop() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); // Draws the bottom half of an egg figure. public static void eggbottom() { System.out.println("\"); System.out.println(" \"); // Draws a complete egg figure. public static void egg() { eggtop(); eggbottom(); Program version 3, cont'd. A Word about Style // Draws a teacup figure. public static void teacup() { eggbottom(); line(); // Draws a stop sign figure. public static void stopsign() { eggtop(); System.out.println(""); eggbottom(); // Draws a figure that looks sort of like a hat. public static void hat() { eggtop(); line(); // Draws a line of dashes. public static void line() { System.out.println(""); q Structure your code properly q Eliminate redundant code q Use spaces judiciously and consistently q Indent properly q Follow the naming conventions q Use comments to describe code behavior 10

Why Style? q Programmers build on top of other s code all the time. You shouldn t waste time deciphering what a method does. q You should spend time on thinking or coding. You should NOT be wasting time looking for that missing closing brace. q So code with style! 11