CS-201 Introduction to Programming with Java

Similar documents
CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods

Lecture 5: Methods CS2301

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

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

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

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

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 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

Methods. CSE 114, Computer Science 1 Stony Brook University

CS110: PROGRAMMING LANGUAGE I

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

Chapter 5 Methods / Functions

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

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

CS115 Principles of Computer Science

Benefits of Methods. Chapter 5 Methods

Chapter 6 Methods. Dr. Hikmat Jaber

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

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

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

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Object Oriented Methods : Deeper Look Lecture Three

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CS171:Introduction to Computer Science II

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

CS110D: PROGRAMMING LANGUAGE I

JAVA Programming Concepts

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture #6-7 Methods

CS111: PROGRAMMING LANGUAGE II

Introduction to Programming Using Java (98-388)

Lecture 3: C Programm

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

CS111: PROGRAMMING LANGUAGE II

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

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

CS1150 Principles of Computer Science Methods

Introduction to Programming (Java) 4/12

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

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

CS-202 Introduction to Object Oriented Programming

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

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

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

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

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

CS240: Programming in C

Java Primer 1: Types, Classes and Operators

Chapter 6 Introduction to Defining Classes

G Programming Languages - Fall 2012

2.8. Decision Making: Equality and Relational Operators

In Java we have the keyword null, which is the value of an uninitialized reference type

Function Call Stack and Activation Records

CSI33 Data Structures

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

Defining Classes and Methods

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

SISTEMI EMBEDDED. Stack, Subroutine, Parameter Passing C Storage Classes and Scope. Federico Baronti Last version:

Functions BCA-105. Few Facts About Functions:

Chapter 7 User-Defined Methods. Chapter Objectives

Pace University. Fundamental Concepts of CS121 1

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

IT 374 C# and Applications/ IT695 C# Data Structures

CS110D: PROGRAMMING LANGUAGE I

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

1 Lexical Considerations

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

(Not Quite) Minijava

15. Arrays and Methods. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

A Foundation for Programming

Computer Programming

The return Statement

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CSC 2400: Computer Systems. Using the Stack for Function Calls

EECS168 Exam 3 Review

Computational Expression

Method. Why Write Methods? Overview. CS256 Computer Science I Kevin Sahr, PhD. Lecture 21: Writing Class Methods. ClassName.methodName(arguments)

Technical Questions. Q 1) What are the key features in C programming language?

Introduction to Java. Handout-1d. cs402 - Spring

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

CS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri

Lecture 1 Java SE Programming

Transcription:

CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture IX: Methods

Introduction method: construct for grouping statements together to perform a function write a piece of code one time and reuse over and over can be reused anywhere in the same program or even anywhere in different programs in other programming languages methods are called: functions procedures subroutines

Introduction Find the sum of integers from 1 to 10, 20 to 37, and 35 to 49. The naïve approach would be this:

Introduction The preceding code can be simplified:

Defining a Method

Defining a Method method definition: the method name, parameters, return value type, and body. Syntax: modifier returnvaluetype methodname(list of parameters) { //Method Body }

Method Signature method signature: the method name and the parameter list make up the signature of the method.

Formal Parameters (Parameters) formal parameters (or parameters): local variables defined in the method signature refers to the data type of the parameters, order in which they appear, and number of parameters. are completely optional. each parameter needs its own data type. max(int num1, int num2) //correct max(int num1, num2) //incorrect Think of formal parameters like a placeholder for a value the method will accept in the future when the method is called.

Actual Parameters (Arguments) When a method is invoked you must pass a value to the parameter. This value is the actual parameter (or argument) of the method.

Return Value Type A method can return a value and the return value type is the data type of the value the method returns. Methods that do not return a value use the void keyword as the return value type. An example is the main method.

Calling a Method

Calling a Method method definition - defines what the method should do. does not execute the code. to actually use a method, you must call or invoke it. invoking a method (method invocation): the act of calling a method in your code: Math.pow() //calls the pow() method of the Math class in.nextint() //calls the nextint() method of the Scanner class same concept when you invoke a method you write.

Calling a Method Value Returning Method invoking this type of method is usually treated as a value int largernumber = max(3, 4); System.out.println(max(3, 4)); Void Method (Method does not return a value) invoking this type of method must be a statement cannot be assigned to a variable. System.out.println("Welcome to Java");

Calling a Method When a method is called, program control is transferred to the called method Control is transferred back to the caller when: the called method's statement is executed or its method ending closing brace is reached See Code: TestMax.java

TestMax.java Trace i is now 5

TestMax.java Trace j is now 2

TestMax.java Trace invoke method max(i, j)

TestMax.java Trace invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

TestMax.java Trace declare variable result

TestMax.java Trace (num1 > num2) is true since num1 is 5 and num2 is 2

TestMax.java Trace result is now 5

TestMax.java Trace return to where max(i, j) was called max(i, j) assigns the returned value to k

TestMax.java Trace Execute the print statement

A Word of Caution A return statement is required for methods that return a value. example below is logically correct, but there is a compilation error. compiler thinks it is possible that the method does not return any value since all cases of the if/else might be false. To fix this problem, delete if (n < 0) in (a) so that the compiler will see a return statement can be reached regardless of how the if statement is evaluated

Reusing Methods from Other Classes methods provide a way to reuse code Methods that have the public and static modifiers can be invoked using Classname.methodName(arguments) TestMax.max(x, y); same way you call methods from the Math class.

void Methods

void Methods A void method does not return a value it just performs some action. has a return type of void. A return statement is not required, but it can be used for terminate the method early. See Code: TestVoidMethod.java TestReturnGradeMethod.java

The Scope of Variables

Scope of Variables local variable: a variable defined inside a method A local variable must be declared before it can be used. (in CS-2012 you will learn about class-level variables, and instance variables) scope: the part of the program where a variable can be referenced / used. scope of a local variable starts from its declaration and ends at the end of the block that contains the variable. method blocks if/else blocks loop blocks

Scope of Variables method parameters are always local variable. the scope of the parameter is the entire method in which it is declared. the memory allocated for the parameter will be freed up after the method is completed and the variable will no longer be available.

Scope of Variables the scope of a variable declared in the initial-action part of a for loop header is the entire loop. the scope of a variable declared inside the body of a for loop starts from its declaration and ends at the closing curly brace of the loop that contains the variable

Scope of Variables you can declare a local variable with the same name in different blocks in a method. you CANNOT declare a local variable twice in the same block or in nested blocks.

The Call Stack

The Call Stack When a method is invoked: The JVM creates an activation record (a.k.a. activation frame) record which stores the data (variable values) for the method in a special area of memory known as the call stack. the call stack is also known as the execution stack, runtime stack, or machine stack (often shortened to "the stack")

The Call Stack calling method: a method which calls another method called method: the method being called by another method. when a method calls another method: the calling method's activation record is kept intact a new activation record is created for the method being called. when the new method is finished: control is returned to the caller the activation record is removed from the stack.

The Call Stack Stacks store elements in a last-in, first-out (LIFO) order The last item placed ON the stack, is the first item taken off of the stack. A stack is also a data structure, which you will learn about in CS-203. you always work with the item on the TOP of the stack. push onto the stack: place an item on the top of the stack. pop off the stack: remove an item from the top of the stack.

The Call Stack

Passing Arguments

Passing Arguments methods can accept outside information input to the method always provided by the calling method makes methods reusable since you can use the same method with different sets of data. outside information is passed as arguments to the parameters of the method.

Passing Arguments Recall: arguments are the actual values passed in the method call. parameters are the place holder variables in the method definition. Example: if I have a method with a header of: public static void mymethod(int x, double y, String s) and I call the method using mymethod(5, 12.6, "Java"); x, y, and s are the parameters 5, 12.6, and "Java" are the arguments passed to the parameters

Passing Arguments If a method header has parameters: you MUST pass arguments to the method call. if a method has no parameters: you CANNOT pass arguments to the method call. you MUST still include an empty set of parenthesis. Example: Math.pow(a, b) is method where you are required to pass two arguments, a base and an exponent. nextint() of the Scanner class is a method were you CANNOT pass arguments, but the empty ( ) are still required.

Passing Arguments parameter order association: arguments passed to parameters MUST: be passed in the correct order have the exact number of arguments (no more or no less than what the method defines) match the parameters based on compatible types Compatible type: you can pass an argument to a parameter without explicit casting i.e. passing an int value to a double value parameter is ok, but the reverse would not be.

Passing Arguments public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output?

Passing Values a copy of the VALUE of the argument is passed to the parameter: not the actual variable...but the VALUE changes made to a value inside a method will not affect the value outside of the method. primitives pass their values. Code Examples: Increment.java TestPassByValue.java

Passing Arguments by Values