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

Similar documents
Methods. Eng. Mohammed Abdualal

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

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

Chapter 6 Methods. Dr. Hikmat Jaber

CS115 Principles of Computer Science

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

CS-201 Introduction to Programming with Java

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

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

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

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

JAVA Programming Concepts

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Top-down programming design

Lecture 5: Methods CS2301

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Eng. Mohammed S. Abdualal

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Methods. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Methods

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

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

CS1150 Principles of Computer Science Methods

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Computer Programming: C++

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

Computer Programming: C++

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

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

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Lecture #6-7 Methods

CS-201 Introduction to Programming with Java

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

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

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

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

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

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

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Methods CSC 121 Fall 2016 Howard Rosenthal

Computer Programming: C++

Arrays. Eng. Mohammed Abdualal

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Place your name tag here

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

Methods CSC 121 Spring 2017 Howard Rosenthal

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

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

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

Computational Expression

COMP102: Test. 26 April, 2006

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

Introduction to Programming Using Java (98-388)

Chapter 7 User-Defined Methods. Chapter Objectives

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

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

Advanced if/else & Cumulative Sum

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

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

Programming with Java

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

( &% class MyClass { }

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

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 );

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Arithmetic Compound Assignment Operators

CAT.woa/wa/assignments/eclipse

CS171:Introduction to Computer Science II

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

CS110: PROGRAMMING LANGUAGE I

CS111: PROGRAMMING LANGUAGE II

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

4. Java language basics: Function. Minhaeng Lee

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

++x vs. x++ We will use these notations very often.

Question: Total Points: Score:

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Static Methods. Why use methods?

CS111: PROGRAMMING LANGUAGE II

Java Simple Data Types

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Advanced Computer Programming

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Java Simple Data Types

Term 1 Unit 1 Week 1 Worksheet: Output Solution

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

1 Lexical Considerations

Programming Exercise 7: Static Methods

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

Benefits of Methods. Chapter 5 Methods

Transcription:

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #7 Methods

What are Methods? Methods can be used to define reusable code and organize and simplify coding. A method is a collection of statements grouped together to perform an operation. In previous labs, we have used a number of known methods like println and random, nextint, etc. These methods are defined the Java language, so we can directly call and use them, and it is clear this makes our work easier. In this lab we are going to learn how to define our own methods. Defining a Method A method definition consists of its method name, parameters, return value type, and body. The syntax for defining a method is as follows: modifier returnvaluetype methodname(list of parameters) { // Method body; Now, let's get a look at the following method that returns the maximum of two numbers: public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; Using public and static keywords are not part of the format, but right now, and as we will be calling our methods from the main method, we will use static in method definition. The method header specifies the modifiers, return value type, method name, and parameters of the method. The returnvaluetype is the data type of the value the method returns. Some methods perform desired operations without returning a value. In this case, the returnvaluetype is the keyword void. 2

If a method returns a value, it is called a value-returning method; otherwise it is called a void method. for example, Integer.parseInt() method returns integer data type, and println() method does not return anything, so we call it void method. Method name: the name we will use to call our method, this name must be a valid variable. The naming convention for method name is like variable name; first word starts with lower case letter, and rest of words start with upper case letters. Parameters list: the variables defined in the method header are known as formal parameters or simply parameters. A parameter is like a placeholder: provide an interface for providing input to method. The parameter list refers to the method s type, order, and number of the parameters. The method name and the parameter list together constitute the method signature. Method could take zero or more parameters, for example, println method takes one parameter as string and prints that string on the console, while Math.random method doesn t take any parameters Method body: statements of the method, these statements are executed when method is called. return keyword: when a method has return type (not void), we have to terminate it using return keyword followed by the variable, value or expression that represents the value which the method should return. Now, let's try to call the max method Calling a Method Calling a method executes the code in the method. There are two ways to call a method, depending on whether the method returns a value or not. If a method returns a value, a call to the method is usually treated as a value. For example, int larger = max(3, 4); Another example of a call that is treated as a value is 3

System.out.println(max(3, 4)); If a method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement: System.out.println("Welcome to Java!"); Note: A value-returning method can also be invoked as a statement in Java. In this case, the caller simply ignores the return value. Ex: Write a method that take two numbers, x and y, and returns the sum of number from x to y. Then use the method to print the sum of numbers in ranges [0,10], [1,100], [100, 150]. Solution: System.out.println(sumRange(0, 10)); System.out.println(sumRange(1, 100)); System.out.println(sumRange(100, 150)); public static int sumrange(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) { sum += i; return sum; void Method A void method does not return a value. We should use void keyword for the method when we do not want to return values from it. The following program defines a method named printgrade and invokes it to print the grade for a given score. 4

System.out.print("The grade is "); printgrade(78.5); System.out.print("The grade is "); printgrade(59.5); public static void printgrade(double score) { if (score >= 90.0) { System.out.println('A'); else if (score >= 80.0) { System.out.println('B'); else if (score >= 70.0) { System.out.println('C'); else if (score >= 60.0) { System.out.println('D'); else { System.out.println('F'); While the following method returns the value of a grade for a given score. System.out.println("The grade is " + getgrade(78.5)); System.out.println("The grade is " + getgrade(59.5)); public static char getgrade(double score) { char grade; if (score >= 90.0) { grade = 'A'; else if (score >= 80.0) { grade = 'B'; else if (score >= 70.0) { grade = 'C'; else if (score >= 60.0) { grade = 'D'; else { grade = 'F'; return grade; 5

Value-returning methods could be used directly in a statement like this: System.out.println("The grade is " + getgrade(78.5)); The value returned from the method is used in the statement. Also, we can assign the returned value to a variable then use that variable when needed. For example: char grade = getgrade(78.5); System.out.println("The grade is " + grade); Passing Arguments by Values The arguments are passed by value to parameters when invoking a method. The power of a method is its ability to work with parameters. When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method signature. This is known as parameter order association. When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. Consider the following code: int x = 1; System.out.println("Before the call, x is " + x); increment(x); System.out.println("After the call, x is " + x); public static void increment(int n) { n++; System.out.println("n inside the method is " + n); 6

If you compile and run the code above, the value of x will remain 1 after calling increment method, because the value of x was copied into n, then the value of n was incremented, but x itself had never affected, because we did not pass x, rather we passed its value. Overloading Methods In Java, two or more different methods can have the same name if their parameter types or number are different. That means that you can give the same name to more than one method if they have either a different number of parameters or different types in their parameters. Methods with same name and different signatures are called overloaded methods. Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int c = input.nextint(); int d = input.nextint(); double avg2 = avg(a, b); double avg3 = avg(a, b, c); double avg4 = avg(a, b, c, d); System.out.println(avg2); System.out.println(avg3); System.out.println(avg4); public static double avg(int a, int b) { return (a + b) / 2.0; public static double avg(int a, int b, int c) { return (a + b + c) / 3.0; public static double avg(long a, long b, long c, long d) { return (a + b + c + d) / 4.0; Overloading methods can make programs clearer and more readable. Methods that perform the same function with different types of parameters should be given the same name. 7

Ex: Write a function that returns the absolute value of a number. If the function was called without any arguments, it should return the absolute of 1. Solution: public static int abs(int x) { if (x < 0) return x * -1; return x; public static int abs() { return abs(1); The Scope of Variables Scope of a variable is the part of the program where the variable is accessible. A variable declared inside the class is called a global variable as it can be used by any method in the class. A variable defined inside a method is referred to as a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and assigned a value before it can be used. A parameter is actually a local variable. The scope of a method parameter covers the entire method. Any variables created inside of a loop are LOCAL TO THE LOOP. This means that once you exit the loop, the variable can no longer be accessed! 8

public class Scope { int globalvariable; // globalvariable can be accessed anywhere in the class int localvariable; for (int i = 0; i < 10; i++) { // i can only be accessed inside the loop // i can not be accessed here public static void othermethod(int parameter) { // parameter is a local variable. // Scope of a method parameter covers the entire method. int localvariable; // different variable that is local to this method only Lab Work Ex1: Write a method that prints the maximum of three variables. The variables may be integers, double, char or String. public static int max(int a, int b, int c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; public static double max(double a, double b, double c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; 9

public static char max(char a, char b, char c) { if (a > b && a > c) return a; else if (b > a && b > c) return b; else return c; public static String max(string a, String b, String c) { if (a.compareto(b) > 0 && a.compareto(c) > 0) return a; else if (b.compareto(a) > 0 && b.compareto(c) > 0) return b; else return c; Homework 1. Write a method, reversedigit, that takes an integer as a parameter and returns the number with its digits reversed. For example, the value of reversedigit(12345) is 54321. Also, write a program to test your method. 2. Write a method int count_vowels(string str) that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and u, and their upper case variants. Good Luck 10