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

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

Lecture 5: Methods CS2301

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

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

Methods. Eng. Mohammed Abdualal

Chapter 6 Methods. Dr. Hikmat Jaber

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

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.

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

Arrays. Eng. Mohammed Abdualal

CS-201 Introduction to Programming with Java

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

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

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

Methods. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Methods

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

JAVA Programming Concepts

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

CS1150 Principles of Computer Science Methods

COMP-202 Unit 4: Programming with Iterations

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

Top-down programming design

Eng. Mohammed S. Abdualal

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

Lecture #6-7 Methods

Place your name tag here

Warmup : Name that tune!

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

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

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

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

AP COMPUTER SCIENCE A

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

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

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

CS-201 Introduction to Programming with Java

Public-Service Announcements

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

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Chapter 5 Methods / Functions

Chapter 3. Selections

Arithmetic Compound Assignment Operators

Computer Programming: C++

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

CONDITIONAL EXECUTION

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CS110: PROGRAMMING LANGUAGE I

CS111: PROGRAMMING LANGUAGE II

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Public-Service Announcements

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

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

Warm-Up: COMP Programming with Iterations 1

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

Example: Monte Carlo Simulation 1

Computational Expression

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

Administrivia. Last modified: Fri Aug 25 10:59: CS61B: Lecture #2 1

CS111: PROGRAMMING LANGUAGE II

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

JAVA OPERATORS GENERAL

Data Structure and Programming Languages

Practice Midterm 1. Problem Points Score TOTAL 50

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

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CS 101 Spring 2007 Midterm 2 Name: ID:

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

CS171:Introduction to Computer Science II

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

Lecture 1 Java SE Programming

IEEE Floating-Point Representation 1

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

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

H212 Introduction to Software Systems Honors

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

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

Java Simple Data Types

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)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Over and Over Again GEEN163

Computer Programming, I. Laboratory Manual. Final Exam Solution

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

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

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

Loops. GEEN163 Introduction to Computer Programming

A Foundation for Programming

Chapter 7 User-Defined Methods. Chapter Objectives

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

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

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA PROGRAMMING LAB Eng. Mustafa J. Dalloul Computer Programming Lab 25 October 2016

Methods can be used to define reusable code and organize and simplify coding Suppose that you need to find all prime number for custom range of numbers? We need to write a code (1) that test the prime number for each number in this range! boolean isprime = true; for(intdivisor = 2; divisor <= number / 2; divisor++) { if(number % divisor == 0) { isprime = false; So, how do you solve this problem? CODE 1 We can see the previous code will be wrote for each number check! So it be nice if we could write the common code once and reuse it? We can do so by defining a method and invoking it. The preceding code can be simplified as follows: public static boolean isprime(int number){ boolean isprime = true; for(intdivisor = 2; divisor <= number / 2; divisor++) { if(number % divisor == 0) { isprime = false; return isprime; 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; Let s look at a method defined to find the square of some integer. This method, named power, has one int parameter n, the square of n is returned by the method. Next figure illustrates the components of this method. 1

The method header specifies the modifiers, return value type, method name, and parameters of the method. The static modifier is used for all the methods in this chapter. The reason for using it will be discussed in later labs. Return OR Void Method: Void Method: Methods perform desired operations without returning a value. In this case, the returnvaluetype is the keyword void. For example, the returnvaluetype is void in the main method, as well as in System.exit(), and System.out.println(). Return Method: Methods may return a value. The returnvaluetype is the data type of the value the method returns after executing the methods. For example Math.random(). If a method returns a value, it is called a value-returning method; otherwise it is called a void method. So the power method is return type method that s return the square of number. Method Parameters: No Parameter: Parameters are optional; that is, a method may contain no parameters. For example, the Math.random() method has no parameters. One or more parameter: You can define a variables in method header which known as formal parameters, when you call the method, you will pass the value to the method parameter list. 2

Caution In the method header, you need to declare each parameter separately. For instance, max(int num1, int num2) is correct, but max(int num1, num2) is wrong. Calling a method executes the code in the method. In a method definition, you define what the method is to do. To execute the method, you have to call or invoke it. 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, boolean x = isprime(5); calls isprime(5) and assigns the result of the method to the variable x. Another example of a call that is treated as a value is System.out.println(isPrime(5)); Which prints the return value of the method call isprime(5). 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 ); 3

Example: Write a java program that s print a specific numbers of prime numbers. Code: import java.util.scanner; public class PrintPrime { public static void main(string[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number of prime output:"); // i acts as a prime number counter, // j the numbers from 1 to n. int n = scanner.nextint(),i=0,j=1; do{ if(isprime(j)){ i++; //Print 5 numbers each line System.out.print(j +(i%5==0?"\n":"\t")); j++; while (i<n); public static boolean isprime(int number) { boolean isprime = true; for (int divisor = 2; divisor <= number / 2; divisor++) { if (number % divisor == 0) { isprime = false; return isprime; 4

Suppose we have this method: public static int power(int n){ n *= n; return n; And we call the power method: int i = 5; int x = power(i); When the power method is invoked, variable i s value 5 is passed to n. The flow of control transfers to the power method, and the power method is executed. When the return statement in the power method is executed, the power method returns the control to its caller (in this case the caller is the main method). The value of i is not changed no matter what the method does. Caution A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compile error because the Java compiler thinks that this method might not return a value. 5

void Avoid method does not return a value. This section shows how to define and invoke a void method. Next example gives a program that defines a method named printgrade and invokes it to print the grade for a given score. public class PrintGradeClass { 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) { System.out.println('D'); else { System.out.println('F'); Overloading methods enables you to define the methods with the same name as long as their signatures are different. Return to our power method; if we need to improve this method to take a double number, we just create another method with the same name of original method and change the parameters as we need. Java will automatically pass the value to approperate method according to the number of parameters and parameter type. See the code: 6

public class Power { // One int n^2 public static int power(int n) { n *= n; return n; // One double n^2 public static double power(double n) { n *= n; return n; // Tow integers n^k public static int power(int n, int k) { int power = 1; for (int i = 1; i <= k; i++) { power *= n; return power; // Tow doubles n^k public static double power(double n, double k) { double power = 1; for (int i = 1; i <= k; i++) { power *= n; return power; // Calling the methods public static void main(string[] args) { System.out.println(power(2)); System.out.println(power(2.5)); System.out.println(power(2, 7)); System.out.println(power(3.5, 3)); 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

Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Sometimes there are two or more possible matches for the invocation of a method, but the compiler cannot determine the best match. This is referred to as ambiguous invocation. Ambiguous invocation causes a compile error. Consider the following code: public static double power(double n, int k) { double power = 1; for (int i = 1; i <= k; i++) { power *= n; return power; public static double power(int n, double k) { double power = 1; for (int i = 1; i <= k; i++) { power *= n; return power; And the main method: public static void main(string[] args) { System.out.println(power(2, 7)); Both power(int,double) and power(double,int) are possible candidates to match power(2,7). Because neither is better than the other, the invocation is ambiguous, resulting in a compile error. The scope of a variable is the part of the program where the variable can be referenced. A variable defined inside a method is referred to as a local variable. 8

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. You can declare a local variable with the same name in different blocks in a method, but you cannot declare a local variable twice in the same block or in nested blocks Notes: Do not declare a variable inside a block and then attempt to use it outside the block. Here is an example of a common mistake: for (int i = 0; i < 10; i++) { System.out.println("#"+i); System.out.println(i); The last statement would cause a syntax error, because variable i is not defined outside of the for loop. 9

null 10