Methods. Eng. Mohammed Abdualal

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

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

Arrays. Eng. Mohammed Abdualal

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

Eng. Mohammed Alokshiya

Eng. Mohammed S. Abdualal

Eng. Mohammed S. Abdualal

Chapter 6 Methods. Dr. Hikmat Jaber

Reading Input from Text File

CS115 Principles of Computer Science

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

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

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

Top-down programming design

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

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

Lecture #6-7 Methods

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

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.

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

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

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

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

Computer Programming: C++

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

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

Lecture 5: Methods CS2301

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

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?

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 02: Using Data

Methods. Every Java application must have a main method.

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

Chapter 2: Using Data

JAVA Programming Concepts

Object Oriented Programming (II)

Programming Exercise 7: Static Methods

Java Programming Language. 0 A history

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

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

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

JAVA OPERATORS GENERAL

Fundamentals of Programming Data Types & Methods

Java Simple Data Types

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

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

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

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

CS111: PROGRAMMING LANGUAGE II

Java Simple Data Types

Computer Programming, I. Laboratory Manual. Final Exam Solution

CS-201 Introduction to Programming with Java

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

Abstract class & Interface

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

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

AP CS Unit 3: Control Structures Notes

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

CS 231 Data Structures and Algorithms, Fall 2016

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

CAT.woa/wa/assignments/eclipse

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

Methods CSC 121 Fall 2016 Howard Rosenthal

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

Oct Decision Structures cont d

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

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

Computational Expression

Chapter 2: Programming Concepts

H212 Introduction to Software Systems Honors

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

( &% class MyClass { }

coe318 Lab 2 ComplexNumber objects

CS 101 Spring 2007 Midterm 2 Name: ID:

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

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

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

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

Chapter 7 User-Defined Methods. Chapter Objectives

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Question: Total Points: Score:

Example Program. public class ComputeArea {

Chapter 1 Introduction to Computers, Programs, and Java

Final Exam 90 minutes Eng. Mohammed S. F. Abdual Al

Key Java Simple Data Types

Advanced Computer Programming

Methods CSC 121 Spring 2017 Howard Rosenthal

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Methods. CSE 114, Computer Science 1 Stony Brook University

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

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

Introduction to Java. Nihar Ranjan Roy.

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

3chapter C ONTROL S TATEMENTS. Objectives

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

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 8 Methods Eng. Mohammed Abdualal November 1, 2015

A method is a collection of statements that are grouped together to perform an operation. In the previous labs, we have introduced a number of known methods like println and random, nextint, etc. these methods are previously written by developers of Java, so we can directly call and use them, and it is clear this makes our work easier. To write a method, use the following definition format: Define a Method [public] [static] ReturnType methodname (param_1, param_2,..., param_n) { // Method Body return returnvalue; 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 contents of method definition are the following: static: because we will be calling our methods from the main method which is static, we should define our methods as static. Return type: data type of the value this method will return, for example, Integer.parseInt() method returns integer data type, and println method does not return anything, so we call it void method. To define a void method, use void keyword instead of return type in definition. 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. List of parameters: method parameters provide an interface for providing input to method, those parameters are variables specified by data type and name, separated by commas. Method could take zero to infinity parameters, for example, println method 2

takes one parameter as string and prints that string on the console. Method body: statements of the method, these statements are executed when method is called. return: 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 method should return. The following example shows how to find the maximum of two numbers using method calling. max Method public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; You can write the previous method in a class, before the main method of after it. Then you can call it by its name from any other methods like main method: Calling max Method from main method public static void main(string[] args) { Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int maxnum = max(a, b); System.out.println(maxNum); From the previous code, you can notice the following: No method is defined in the body of another one, so we define additional methods out of the block of main method, but is still in the block of the class. Method calling is simple and straightforward, all we have to do is to specify method name and pass the parameters. When method is called, the value of a is copied into matching method parameter which is num1, similarly, 3

the value of b is copied into num2, so when result is calculated, it contains the sum of num1 and num2. Another example to find the greatest common devisor of two number using the Euclidean algorithm (You should be familiar with Euclidean algorithm from Discrete Math Course) GCD Method public static int GCD(int a, int b) { int temp; while (b > 0) { temp = a % b; a = b; b = temp; return a; public static void main(string[] args) { int result = GCD(20, 30); System.out.println(result); void Methods 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 that defines a method named printgrade and invokes it to print the grade for a given score. void public static void main(string[] args) { 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) { 4

System.out.println('D'); else { System.out.println('F'); Passing Arguments by Values The arguments are passed by value to parameters when invoking a method. Consider the following code: Passing Arguments by Values public static void main(string[] args) { 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); 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. Overloaded Methods public static void main(string[] args) { Scanner input = new Scanner(System.in); int a = input.nextint(); int b = input.nextint(); int c = input.nextint(); 5

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(int a, int b, int c, int d) { return (a + b + c + d) / 4.0; Passing Arguments to the main Method The main method, like some other methods, takes arguments and returns nothing. You can pass arguments to it if you run your program from the console. Write your program using any text editor, like notepad++, and compile it using javac command, then run it using java command. Example: write a program that takes 5 words as arguments from the command line, then print each one using a JOPtionPane message. To accomplish this task, fellow the steps below: 1. Write the following code in a text editor, for example, notepad: Main.java import javax.swing.joptionpane; public class Main { public static void main(string[] args) { JOptionPane.showMessageDialog(null, args[0]); JOptionPane.showMessageDialog(null, args[1]); JOptionPane.showMessageDialog(null, args[2]); JOptionPane.showMessageDialog(null, args[3]); JOptionPane.showMessageDialog(null, args[4]); 6

2. Save your code in a file with the same name of the public class, and.java extension. For me, I will save it in D:\ drive. 3. Compile the previous file to convert the source code into byte code. Use javac filename.java command from the command line: Now you can notice a new file in the same folder: Main.class, which contains the compiled code: 7

4. Run the class file using java filename command and pass arguments to the program (to the main method). 5. Enjoy! ;) 8

Adding Java path to System Variables If you installed an earlier version of Java and tried to use javac command in the command line, you may face a problem like this: This is because that your system cannot locate where Java is installed. You just have to tell your system where to find javac tool, by adding the path of its folder to the environment variables. Like the following: 1. Go to the Java installation folder, by default it is: C:\Program Files\Java\jdkX.X.X_X\bin where X depend on the version of the installed java. I installed the latest version 1.8.0_20, so the folder path is C:\Program Files\Java\jdk1.8.0_20\bin 9

2. Copy the path of JDK bin folder: 3. Open environment variables. Right click on Computer and select Properties 10

4. Advanced system settings 11

5. Advanced >> Environment Variables: 12

6. Add new user variable with name Path and value of the Java bin folder path: 13

Alternatively, you can append the java path into Path variable in system variables. Separate two different paths with a semicolon (;). 14