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

Similar documents
Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Introduction to Computer Science Unit 2. Notes

AP CS Unit 3: Control Structures Notes

Introduction to Computer Science Unit 2. Notes

STUDENT LESSON A7 Simple I/O

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

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

Chapter 5 Methods / Functions

Activity 3: Data Types

Lecture 5: Methods CS2301

CS111: PROGRAMMING LANGUAGE II

Java Classes: Math, Integer A C S L E C T U R E 8

CS110: PROGRAMMING LANGUAGE I

Pace University. Fundamental Concepts of CS121 1

Activity 1: Introduction

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

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

4. Java Project Design, Input Methods

Flow of Control. Chapter 3 Part 3 The Switch Statement

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary 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)

An overview of Java, Data types and variables

Activity 1: Introduction

A Foundation for Programming

Section 2.2 Your First Program in Java: Printing a Line of Text

Preview from Notesale.co.uk Page 2 of 79

2.8. Decision Making: Equality and Relational Operators


Claremont McKenna College Computer Science

Welcome to the Primitives and Expressions Lab!

( &% class MyClass { }

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

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

Full file at

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

JAVA Programming Concepts

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

Activity 9: Object-Oriented

Introduction to Programming (Java) 4/12

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Programming Practice (vs Principles)

LECTURE 2 (Gaya College of Engineering)

Java Reference Card. 1. Classes. 2. Methods. 3. Conditionals. 4. Operators

Activity 9: Object-Oriented

Chapter 6 Methods. Dr. Hikmat Jaber

Introduction to Java Unit 1. Using BlueJ to Write Programs

CS115 Principles of Computer Science

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

Controls Structure for Repetition

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Programming with Java

double float char In a method: final typename variablename = expression ;

Using API in Java. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Java Mr. Clausen Program 6A, 6B

Using Java Classes Fall 2018 Margaret Reid-Miller

Midterm Examination (MTA)

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Fundamentals of Programming Data Types & Methods

CS 106 Introduction to Computer Science I

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

Chapter 3. Selections

Full file at

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

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

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

Activity 7: Arrays. Content Learning Objectives. Process Skill Goals

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Methods and Functions

Loops. CSE 114, Computer Science 1 Stony Brook University

CS111: PROGRAMMING LANGUAGE II

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

CT 229 Java Syntax Continued

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Bytecode (binary file)

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

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

Section 2.2 Your First Program in Java: Printing a Line of Text

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1

Nested Loops. A loop can be nested inside another loop.

Selected Questions from by Nageshwara Rao

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Methods (Deitel chapter 6)

Introduction to Java Applications

CS113: Lecture 4. Topics: Functions. Function Activation Records

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Methods (Deitel chapter 6)

Transcription:

Activity 4: Methods Java programs are organized into classes, each of which has one or more methods, each of which has one or more statements. Writing methods allows you to break down a complex program into smaller blocks of reusable code. Content Learning Objectives After completing this activity, students should be able to: Apply methods from the Math class based on their documentation. Explain the syntax of a method declaration (parameters and return type). Draw a diagram that shows the call stack at a given point of execution. Process Skill Goals During the activity, students should make progress toward: Tracing the execution of methods to determine contents of memory. (Critical Thinking) Copyright 2017 Chris Mayfield. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Model 1 Math Methods Consider the following methods defined in the Math class: public static int abs(int a) public static double log(double a) public static double pow(double a, double b) public static double random() public static int subtractexact(int x, int y) Note this list isn t exhaustive; Math has over 70 methods in total. To invoke methods from another class (like Math), you must first specify the class name: value = abs(-5); value = Math.abs(-5); // Error: cannot find symbol // correct The period in this example is called the dot operator. When reading the above code out loud, you would say math dot abs. Here is the Java documentation for the methods listed above: Modifier and Type Method and Description static int abs(int a) Returns the absolute value of an int value. static double log(double a) Returns the natural logarithm (base e) of a double value. static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument. static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. static int subtractexact(int x, int y) Returns the difference of the arguments, throwing an exception if the result overflows an int. Questions (15 min) Start time: 1. What type of value does Math.random() return? Give an example of what it would look like.

2. When invoking a method, what do you need to specify before the method name and after the method name? 3. For each method, write a Java statement that invokes it and assigns the result to a variable. 4. When defining a method, what do you need to specify before the method name and after the method name? 5. Define a method named average that requires two integers x and y and returns a double. (Don t write any semicolons or braces.) What you wrote for the previous question is called the method s signature. The variables declared inside the parentheses are called parameters. When invoking the method, the values you provide are called arguments. Since arguments will be assigned to parameters, their types must be compatible. 6. How many parameters and arguments does each method have? In the table below, what is the relationship between the last two columns? Method # Params # Args abs log pow random subtractexact println

7. Consider the statement System.out.println("Price: " + price); where the value of price is 9.99. What is the argument that println receives? 8. Consider the statement System.out.printf("Price: %f", price); where the value of price is 9.99. Why does println use plus and printf use comma to specify the arguments? Model 2 Invoke and Return Each statement in this program invokes (or calls) a method. At the end of a method, Java returns to where it was invoked. The list of events on the right illustrates how the program runs. 1 public class Model { 2 3 public static void main(string[] args) { 4 System.out.println("First line."); 5 threeline(); 6 System.out.println("Second line."); 7 8 9 public static void newline() { 10 System.out.println(); 11 12 13 public static void threeline() { 14 newline(); 15 newline(); 16 newline(); 17 18 19 RETURN to line 5 INVOKE threeline INVOKE newline RETURN to line 11 RETURN to line 15 INVOKE newline RETURN to line 11 RETURN to line 16 INVOKE newline RETURN to line 11 RETURN to line 17 RETURN to line 6 RETURN to line 7

Questions (15 min) Start time: 9. How many lines of source code invoke the println method? 10. How many times is println invoked when the program runs? 11. For each INVOKE on the right, draw an arrow to the corresponding line of code. (Plan ahead so that crossing lines will still be legible.) 12. What is the output of the program? Please write \n to show each newline character. 13. When Java sees a name like x, count, or newline, how can it tell whether it s a variable or a method? (Hint: syntax) 14. What is the difference between a method and a variable? What do they have in common? 15. In your own words, describe what methods are for. Why not just write everything in main?

Model 3 Stack Diagrams Each method has its own area of memory to store parameters and other variables. When a method is invoked, Java allocates this memory on the call stack. For convenience, we draw stack diagrams upside down. Note: The signature for System.out.println is public void println(string x). public static void printtime(int hour, int minute) { System.out.println(hour + ":" + minute); public static void main(string[] args) { int hour = 11; int minute = 59; printtime(12, 15); Questions (15 min) Start time: 16. Based on the diagram, how many methods does the program call? 17. Based on the diagram, how many variables does the program have? 18. How do stack diagrams extend the memory diagrams we ve seen previously?

19. How is it possible that two variables with the same name can have different values? 20. Draw a stack diagram to show the state of memory just before println is called. Assume the user inputs the value 10. (You should be able to do this kind of math without a calculator.) public static void show(double c) { double f; String str; f = c * 1.8 + 32; str = String.format("%.1f C = %.1f F\n", c, f); System.out.println(str); public static void main(string[] args) { double c; Scanner in = new Scanner(System.in); System.out.print("Enter temperature in Celsius: "); c = in.nextdouble(); show(c); 21. What is the difference between the String.format method (used in the previous question) and System.out.printf?