Methods and Functions

Similar documents
Arrays. Theoretical Part. Contents. Keywords. Programming with Java module 3

Objects. Theoretical Part. Contents. Keywords. Programming with Java Module 5. 1 Module Overview 3

Control structures and logic

Lecture 5: Methods CS2301

Loops. CSE 114, Computer Science 1 Stony Brook University

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

AP CS Unit 3: Control Structures Notes

Java Coding 3. Over & over again!

( &% class MyClass { }

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

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

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

Variables and data types

Programming with Java

CS1150 Principles of Computer Science Loops (Part II)

CT 229 Methods Continued

Chapter 7 User-Defined Methods. Chapter Objectives

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

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

Pace University. Fundamental Concepts of CS121 1

Mr. Monroe s Guide to Mastering Java Syntax

Advanced Computer Programming

CS110: PROGRAMMING LANGUAGE I

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

4. Java language basics: Function. Minhaeng Lee

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

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

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

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

CSE 114 Computer Science I

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

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

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

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

Conditional Execution

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

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

Example: Monte Carlo Simulation 1

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

Computer Science is...

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

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

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

CS 231 Data Structures and Algorithms, Fall 2016

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

Controls Structure for Repetition

Condi(onals and Loops

Lecture #6-7 Methods

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

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

Decisions in Java IF Statements

Introduction to Programming Using Java (98-388)

Introduction to Computer Science Unit 2. Exercises

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Programmierpraktikum

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

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

Chapter 3. Selections

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

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

Arrays and Basic Algorithms

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Midterm Examination (MTA)

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

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

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

static String usersname; public static int numberofplayers; private static double velocity, time;

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

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

CS-201 Introduction to Programming with Java

Term 1 Unit 1 Week 1 Worksheet: Output Solution

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

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

1 Short Answer (10 Points Each)

Tutorial 3: Conditionals and Iteration COMP 202: Intro to Computing 1

CMPT 125: Lecture 4 Conditionals and Loops

Introduction to Java

Java+- Language Reference Manual

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)

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Methods. Bok, Jong Soon

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

A Foundation for Programming

The return Statement

Methods (Deitel chapter 6)

CS171:Introduction to Computer Science II

Introduction to the Java Basics: Control Flow Statements

Methods (Deitel chapter 6)

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

Object-Oriented Programming

Iteration statements - Loops

Write a program which converts all lowercase letter in a sentence to uppercase.

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Getting started with Java

CS111: PROGRAMMING LANGUAGE II

CS 101 Spring 2007 Midterm 2 Name: ID:

4. If the following Java statements are executed, what will be displayed?

An overview of Java, Data types and variables

Transcription:

Programming with Java Module 4 Methods and Functions Theoretical Part Contents 1 Module overview 3 2 Methods 3 2.1 Methods without return value (procedures).............. 3 2.2 Functions with return value (functions)................. 4 2.3 Methods with parameters......................... 5 3 Methods of the class Math 6 4 Method Overloading 7 4.1 Scope: visibility of variables........................ 8 5 Recursion 9 5.1 Example 1: Factorial............................. 9 5.2 Example 2: Fibonacci............................ 9 6 Error handling with exceptions 10 6.1 Throwing exceptions............................ 11

Keywords Methods Subroutine Procedure Function Parameter Return value Return Type Visibility of Variables Overloading Recursion Exception Random Number Modularity Authors: Lukas Fässler, Barbara Scheuner, David Sichau E-Mail: et@ethz.ch Date: 18 July 2018 Version: 1.1 Hash: d2eb005 The authors try the best to provide an error free work, however there still might be some errors. The Authors are thankful for your feedback and suggestions. This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ 2

1 Module overview An entire problem is broken down into separate parts by the modular concept. In this module, you will learn how commands can be combined into subprograms (or subroutines). Subroutines are functional units which can be invoked from several positions in a program. This way, a program part only has to be developed and tested once whereby the programming effort is reduced and the program code is shortened. If data are passed by invoking the subroutine, they are called parameters. In many programming languages, two variants of subroutines are distinguished: those with a return value (functions) and those without a return value (procedures). In Java, all subroutines that can have parameters and return values are referred to as methods. 2 Methods A method in Java consists of a head (or signature) with the modification public static 1, the return type, the name, the parameters and the body in the curly brackets {. The execution of a Java application usually starts in the main method which often only invoke other methods. 2.1 Methods without return value (procedures) You have already used functions without return value: for example the function System.out.println() which inserts a line break. However, you can also write your own methods which fulfil a task determined by you. Methods without return value looks as follows: Notation: void methodname() { //Signature of the method // Commands The word void indicates that no return value is expected. The empty brackets () means that no paramters are passed. 1 The meaning of the modifications results from the object-orientation of Java and will not be discussed in this book. 3

The following class contains the main method with the name main and the method output which is invoked in the main method: public class ProcedureTest{ public static void main(string[] args){ output(); public static void output(){ //Signature of the method System.out.println("the method was executed"); 2.2 Functions with return value (functions) Methods with return value are used to win a result of the commands in the function. The data type of the return value is directly in front of the method name. It must be ensured that a value of the corresponding type is returned in the method. To return a value, the word return is used. Notation: return type methodname() { //Signature of the method // Commands The following class contains a main method and a further method getanswerthat is invoked in the main method: public class ProcedureTest{ public static void main(string[] args){ int value = getanswer(); public static int getanswer(){ //Signature of the method return 42; The return value in the example above is of type Integer. It has to be taken into account that it is mandatory to return a value in each case. 4

boolean hello(){ int i = 1; if (i == 1){ return true; else { System.out.println("will never occur"); Even if the else-case will never occur, you have to bear in mind that something would also be returned in this case. Correct would be: boolean hello(){ int i=1; if (i==1){ return true; else { System.out.println("will never occur"); return false; 2.3 Methods with parameters We can also pass values to functions. Such values passed to a function are called parameters. We have to declare the variables received (input variable) in the header of the function definition to be able to pass values to your function. When calling the function, the parameter is passed to the input variable. Both types of methods (i.e. procedures and functions) can demand parameters in the signature. Parameters are variables whose initializing happens when the methods is invoked and which are necessary for executing the task of the method. void addandoutput(int x, int y){ int z = x + y; System.out.println("Sum: "+z); This method can be invoked, for example, with the values 3 and 2: 5

addandoutput(3,2); Methods with return value can now also return a value. int add(int x, int y){ int z = x + y; return z; This method can be invoked as follows: int resultat = add(3,2); The return value is stored in the variable result whose data type is equal to the return type. 3 Methods of the class Math The class Math provides some methods which realize mathematical functions. All these methods are functions since they have a return value (the result of the calculation). They usually except one or two numbers as parameters. public class TestMath{ public static void main(string[] args){ double x= 19.7; double y= 20.3; double largernumber = Math.max(x,y); double smallernumber = Math.min(x,y); double rounddown = Math.ceil(x); A method without parameter of the class Math is the function Math.random(). This function returns a random number between 0 and 1 whereby the number can be equal to 0 but it is always smaller than 1. This function enables us to generate a random integer between 1 and x. This can be done as follows: 1. Generating a random number between 0 and 1. 6

2. Multiplication of this number with x. This results in a floating-point number between 0 and x. 3. Rounding. // Generating a random number between 0 and 99 by rounding down int randomnumber1 = (int)(math.random()*100); // Generating a random number between 0 and 100 by rounding long randomnumber2 = Math.round(Math.random()*100); 4 Method Overloading Method Overloading is a feature that allows a class to have two or more methods having same name, if their parameters are different. However, different returns values alone are not sufficient. If two methods have the same name but they contain different types or numbers of parameter, the method is called overloaded. A popular example that you have often used are the methods print() and println(), respectively. We can pass values of type string, int, double, etc. to this method. For you as a user it looks like as you always invoke the same methods. However, you invoke different methods corresponding to the data type. Therefore, we can write the two following methods with identical name line in the same class: // Signature with one parameter public static void line(int x){ for (int i=0; i<x; i++){ System.out.print( - ); // Signature with two parameters public static void line(int x, char c){ for (int i=0; i<x; i++){ System.out.print(c); If you invoke the method with only one parameter value, the first method is used and with two values, the second one: line(8); line(19, - ); 7

4.1 Scope: visibility of variables Variables have a limited lifetime. Some variables are only deleted when the program is terminated, others are already deleted at an earlier point. A variable is always visible in the command block (see module 2) or class in which it was declared. A variable declared at the beginning of the method is also deleted when the program ends. If the value of these variables is required later on, it needs to be returned to the invoking function. public class visibilityvariables{ public static int global = 20; public static void main(string[] args){ System.out.println("Values between 1 and "+ global); output(); public static void output(){ int random = 0; for (int i=0; i<30; i++){ random = (int) (Math.random() * global) + 1; The variable global is visible within the whole class. The variable random is only visible within the method output and the variable i only within the loop. If we used the commented line, the following code would result in an error message because the variable random is not visible in the main method: public class VisibilityVariables2{ public static void output(){ int random = (int) (Math.random() * global) + 1; public static void main(string[] args){ output(); // System.out.println("Values between 1 and "+ zufall); 8

5 Recursion A recursion is a method which calls itself. To avoid that the method calls itself infinitely, which has the same consequences as an infinite loop, a termination condition which stops the self-invoking is necessary. To programme a recursion, you have to determine two elements: Basic case: in this case, the result of the calculation is already known. This case corresponds to the termination condition of the recursion. Recursive call: you have to determine how the recursive call shall be done. 5.1 Example 1: Factorial The calculation of the factorial f(x) = x! of x can be realized by using a recursive method. Basic case: the factorial of the values 0 and 1 is 1. Recursion: x! = x (x 1)! for x > 1 int factorial(int x){ if ((x == 0) (x == 1){ // Basic case return 1; else { return x * factorial(x-1); // Recursive call 5.2 Example 2: Fibonacci A further popular example is the recursion of the Fibonacci sequence. This infinite sequence of integers starts with 0 and 1. The next number results from the sum of the two preciding numbers: Therefore, the sequence is 0, 1, 1, 2, 3, 5, 8,... For the Fibonacci sequence, two recursive calls are necessary in each step: f(n) = f(n 1) + f(n 2) for n 2 with the start values f(1) = 1 and f(0) = 0. Basic case: for the case that n is equal to 1 or 0, we know that 0 and 1, respectively, has to be returned. Recursion: we call the function again for all the other case whereby we decrease the passed values by 1 and 2. 9

int fibonacci(int n) { if (n == 0){ // Basic case 1 return 0; else if (n == 1){ // Basic case 2 return 1; else { // recursive call twice return (fibonacci(n-1) + fibonacci(n-2)); Note that the function fibonacci in example 2 calls itself twice. We also call it cascading recursion. In example 1, only a single self-invoking call occurs what is also referred to as a linear recursive. 6 Error handling with exceptions Exceptions are caused by exceptional situations during the program execution. Exception handling shall prevent abnormal program terminations. Try-catch-commands enable us to catch and handle exceptions within a method. Maybe you wanted to convert a text into a number by mistake or access an array index that was outside the bounds of the array. Exceptions do not need appear on the console. One also can catch them and search for a solution to the problem. Exceptions can be catched as follows: try { // anything that might cause an error catch (Exception c) { // Solution of the problem 10

Here, the user might enter a character instead of an integer. This incorrect input can be handled as follows: public static void main(string[] args) { Scanner scan = new Scanner(System.in); int number = 0; System.out.println("Please enter an integer."); String value = scan.nextline(); try { number = Integer.parseInt(value); catch (Exception e){ System.out.println("This is not an integer"); number = 0; 6.1 Throwing exceptions You also can use the construct of exception yourself. If you want to communicate an error in your own method, you can throw an exception. The command throw new Exception() provokes an error. The signature of a method that is able to provoke an exception has to be extended by throw Exception. public class ExceptionTester{ public static void main(string[] args) { try { tester(-3); catch (Exception e) { System.out.println(e.getMessage()); public static void tester(int x) throws Exception{ if (x < 0){ throw new Exception(); 11