Methods. Every Java application must have a main method.

Similar documents
INFO Object-Oriented Programming

Lesson 26: ArrayList (W08D1)

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

LECTURE 2 (Gaya College of Engineering)

More on Strings & Arrays

Lab Activity Plan. John Dalbey CPE /30/2013

Methods. Eng. Mohammed Abdualal

University of Palestine. Mid Exam Total Grade: 100

PROGRAMMING FUNDAMENTALS

CT 229 Fundamentals of Java Syntax

Technical Section. Lab 4 while loops and for loops. A. while Loops or for loops

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

01. Which of the following statement describes dynamic resizing as is applies to the ArrayList class?

Arrays. 1 Index mapping

Algorithms and Problem Solving

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

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

CS 231 Data Structures and Algorithms Fall 2018

1. Find the output of following java program. class MainClass { public static void main (String arg[])

Warmup : Name that tune!

Chapter 5: Methods. by Tony Gaddis. Starting Out with Java: From Control Structures through Objects. Fourth Edition

Lecture Set 4: More About Methods and More About Operators

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

1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 4, 2005

Nested Loops. A loop can be nested inside another loop.

CMPT 126: Lecture 6 Arrays

Chapter 2: Programming Concepts

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

Welcome to the Primitives and Expressions Lab!

13 th Windsor Regional Secondary School Computer Programming Competition

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Final Examination Semester 2 / Year 2011

Arrays. Eng. Mohammed Abdualal

Top-Down Program Development

Java Basic Programming Constructs

Lec 3. Compilers, Debugging, Hello World, and Variables

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Example: Monte Carlo Simulation 1

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

Lecture Set 4: More About Methods and More About Operators

CS 112 Introduction to Programming

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

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

Java Classes: Math, Integer A C S L E C T U R E 8

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

1.00 Lecture 13. Inheritance

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Lecture 5: Methods CS2301

COE318 Lecture Notes Week 4 (Sept 26, 2011)

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

Example Program. public class ComputeArea {

Array Based Lists. Collections

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CITS1001 week 4 Grouping objects

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

JAVA OPERATORS GENERAL

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

CS-201 Introduction to Programming with Java

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

Control Structures II. Repetition (Loops)

CS 211: Methods, Memory, Equality

A Foundation for Programming

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Some Sample AP Computer Science A Questions - Solutions

1) Consider the following code segment, applied to list, an ArrayList of Integer values.

Programming Basics. Digital Urban Visualization. People as Flows. ia

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

Abstract Data Types and Java Generics. Fundamentals of Computer Science

Fundamentals of Programming Data Types & Methods

Course Outline. Introduction to java

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

CSC324 Principles of Programming Languages

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

CS 11 java track: lecture 1

MODULE 6q - Exceptions

Methods. CSE 114, Computer Science 1 Stony Brook University

1.00 Lecture 34. Sorting 2. Reading for next time: Big Java Counting sort

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

Midterm Examination (MTA)

Introduction to Functional Programming in Java 8

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

CS171:Introduction to Computer Science II

Complexity, General. Standard approach: count the number of primitive operations executed.

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Week 2: Data and Output

CHAPTER 7 OBJECTS AND CLASSES

Introduction to Java Applications

What two elements are usually present for calculating a total of a series of numbers?

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Selected Questions from by Nageshwara Rao

Transcription:

Methods Every Java application must have a main method. The JVM calls main when it runs your program. When main finishes control goes back to the JVM. Up to now, we have always coded public static void main(string[] args){ We have used many methods developed by other programmers. For example Math.max, System.out.println, Character.isDigit, Now we write our own methods 1

Methods Methods are used to improve readability and to provide reusable pieces of code Methods can be designed to Return a value Return nothing Have parameters (for passing values into a method) 2

Methods Example Sieve of Eratosthenes 1. Background and the algorithm 2. straightforward implementation with main method 3. introduce 1 more method 4. introduce 2 more methods 3 versions: Sieve1 Sieve2 Sieve3 3

Methods Example Sieve of Eratosthenes 1. Background and the algorithm 2. straightforward implementation with main method 3. introduce 1 more method 4. introduce 2 more methods 4

Methods Sieve of Eratosthenes Sieve of Eratosthenes an algorithm for finding prime numbers. attributed to a Greek mathematician, Eratosthenes of Cyrene, who lived more than 2, 000 years ago Example of sieve in action see https://en.wikipedia.org/wiki/sieve_of_eratosthenes 5

Methods Sieve of Eratosthenes Sieve of Eratosthenes Begin with a list of integers ranging from 2 up to a limit, say 120 1. next 2 // begin crossing-off multiples starting with 2 2. for next ranging from 2 to limit in increments of 1 (a) if list next is not crossed-off // cross-off all multiples of next i. p 2*next ii. while p <= limit A. list p 0 // cross-off this multiple B. p p+next // next multiple 6

Methods Example: Sieve of Eratosthenes Sieve of Eratosthenes 1. Background and the algorithm 2. straightforward implementation with main method 3. introduce 1 more method 4. introduce 2 more methods 7

Methods Listing 7.1 Sieve with main method import javax.swing.joptionpane; import java.util.arraylist; public class Sieve1 One method, main { public static void main(string[] args){ // get limit from user String limitasstring = JOptionPane.showInputDialog("Enter upper limit:"); int limit = Integer.parseInt(limitAsString); // set up the list of integers // apply the sieve technique Code left out // display primes JOptionPane.showMessageDialog(null,"primes < "+limit+" are "+result); 8

Methods Listing 7.1 Sieve with main method Sieve1. Can be considered a well-written program Relatively easy to follow Some prefer the use of methods to break a program up into its component parts and make it more readable, and hence easier to see its overall construction 9

Methods Example: Sieve of Eratosthenes Sieve of Eratosthenes 1. Background and the algorithm 2. straightforward implementation with main method 3. introduce 1 more method 4. introduce 2 more methods 10

Methods Sieve with two methods, Listing 7.2 Sieve2 The program has 2 parts to it: 1. main 2. getlimitfromuser main Main calls getlimitfromuser getlimitfromuser 11

import javax.swing.joptionpane; import java.util.arraylist; Methods Sieve with two methods, Listing 7.2 public class Sieve2 { public static void main(string[] args){ int limit = getlimitfromuser(); // set up the list of integers ArrayList<Integer> list = new ArrayList<>(); main calls getlimitfromuser returns an int no parameters public static int getlimitfromuser(){ String limitasstring = JOptionPane.showInputDialog("Enter upper limit:"); int number = Integer.parseInt(limitAsString); return number; Control returns to main and the value of number replaces the call 12

Methods Example: Sieve of Eratosthenes Sieve of Eratosthenes 1. Background and the algorithm 2. straightforward implementation with a main method 3. introduce 1 more method 4. introduce 2 more methods 13

Methods Sieve with 3 methods, Listing 7.3 Move more code out into methods producing a trivial main method public static void main ( String [] args ) { int limit = getlimitfromuser () ; ArrayList < Integer > result = applysieve ( limit ) ; displayresults ( result ) ; main getlimitfromuser applysieve displayresults 14

Methods Example, Listing 7.3 This structure diagram shows which method calls which method and any parameters and/or return values main limit limit list of primes list of primes getlimitfromuser applysieve displayresults 15

import javax.swing.joptionpane; import java.util.arraylist; Methods Example, Listing 7.3 public class Sieve3 { public static void main(string[] args){ int limit = getlimitfromuser(); ArrayList<Integer> result = applysieve(limit); displayresults(result); public static void displayresults(arraylist<integer> listofprimes){ public static int getlimitfromuser(){ public static ArrayList<Integer> applysieve(int upperlimit){ 16

Methods - summary Methods can be designed to Return a value Return nothing With parameters (for passing values into a method) 17

Methods Value-returning methods Methods can be designed to return a value to the point where called. This is the usual way to return values to a calling method. Example. reverse the letters of a string Return type public static String reverseword(string w){ String r = ""; for (int i=w.length()-1; i>=0 ; i--){ r+=w.charat(i); return r; return statement causes execution of reverseword to terminate, and the value of r is returned to the point where reverseword was called Note: a value-returning method must have a return statement could have more than one. 18

Methods - void methods Methods can be designed to accomplish some task, and do not need to return anything Example. display a word in reverse Return type public static void displayreverse(string w){ String r = ""; for (int i=w.length()-1; i>=0 ; i--){ r+=w.charat(i); System.out.println( r ); Usually no return statement When execution of method reaches its end, the JVM automatically goes back to point where method was invoked 19

Methods - Parameters A method with parameters must be invoked with similar arguments. When invoked primitive arguments are passed in to primitive parameters, but nothing is passed back on return. objects are passed by address; any changes made to an object persist after the method call The common way to pass values back to a calling method is to use a valuereturning method Example. calculate the average of an integer ArrayList public static double average(arraylist<integer> list){ double sum = 0; for (Integer e : list) sum+=e; return sum/list.size(); 20

Methods - exercise Review the sample answer to the last lab Note the use of methods Exercise: Draw the structure diagram for the program showing the types of values passed into methods and the values returned. 21