CS 121 – Intro to Programming:Java - Lecture 6 Announcements Fourth programming assignment now up, due in Friday. OWL assignments due as indicated MidTerm:

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 More About Methods in Java CSC 1401: Introduction to Programming with Java Week 7 – Lecture 3 Wanda M. Kunkle.
Java Syntax Primitive data types Operators Control statements.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
ECE122 L8: More Conditional Statements February 7, 2007 ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
COMP More About Classes Yi Hong May 22, 2015.
CS 121 – Intro to Programming:Java - Lecture 3 Announcements Course home page: Owl due Friday;
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Writing Classes (Chapter 4)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 121 – Intro to Programming:Java - Lecture 7 Announcements A new Owl assignment is available. Programming assignment 4 is due on Thursday - hand in on.
GP3, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 3 We start at 13:00 Slides are available from the course home page Feel free to.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
CS 121 – Intro to Programming:Java - Lecture 5 Announcements Course home page: Owl due Thursday at 11; another one up today. Third programming assignment.
Methods We write methods in our programs for many reasons:
February ,  2/16: Exam 1 Makeup Papers Available  2/20: Exam 2 Review Sheet Available in Lecture  2/27: Lab 2 due by 11:59:59pm  3/2:
1 CS161 Introduction to Computer Science Topic #17.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Chapter 2 topics Concept # on Java Subset Required for AP Exam print and println10. Testing of output is restricted to System.out.print and System.out.println.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
A: A: double “4” A: “34” 4.
Written by: Dr. JJ Shepherd
Department of Computer Engineering Methods Computer Programming for International Engineers.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Lecture 10. Review (Char) Character is one of primitive data types of variable (such as integer and double) –Character variable contains one character.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CS180 Recitation Chapter 7: Defining Your Own Classes II.
CS 121 – Intro to Programming:Java - Lecture 4 Announcements Course home page: Owl due soon; another.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Topics introduced today (these topics would be covered in more detail in later classes) – Primitive Data types Variables Methods “for” loop “if-else” statement.
Objects Real and Java COMP T1 3
Functions + Overloading + Scope
CprE 185: Intro to Problem Solving (using C)
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Type Conversion, Constants, and the String Object
CS 302 Week 11 Jim Williams, PhD.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Type Conversion, Constants, and the String Object
Creating Objects in a Few Simple Steps
Group Status Project Status.
Chapter 2 Programming Basics.
February , 2009 CSE 113 B.
Peer Instruction 4 Control Loops.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Corresponds with Chapter 5
Presentation transcript:

CS 121 – Intro to Programming:Java - Lecture 6 Announcements Fourth programming assignment now up, due in Friday. OWL assignments due as indicated MidTerm: Monday, 10/17, , Thompson 104 Sample exam now available at course web site Office hours - now posted; held in LGRT 220; Lab time in 213 as indicated

Principal theme today: methods Methods organize (sub)jobs at the statement level They’re the fundamental mechanism for combining elementary operations together to make reuseable, more complex operations You can build an entire “world” with methods: very complex chores rely on complex chores, which rely on elementary chores, which rely on primitives.. and so on.

public class SimpleCoins { static final int HEADS = 1; static final int TAILS = 0; public int flip(){ if (Math.random() < 0.5) return TAILS; else return HEADS; } public int multiFlip(int flips) { int total = 0; for(int j = 0; j < flips; j++) { total += flip(); } return total; } }

public int multiFlip(int flips) { int total = 0; for(int j = 0; j < flips; j++) { total += flip(); } return total; } Parameter list: type followed by formal parameter Header line Method name Return type Visibility qualifier Method body Return statement

Common Errors public int multiFlip(int flips) { int total = 0; for(int j = 0; j < flips; j++) { total += flip(); } System.out.println( total); } public int multiFlip(int flips) { int total = 0; for(int j = 0; j < flips; j++) { total += flip(); } return “total”; }

Another example: let’s imagine we’ve created a WordStudy class, and we want to write a method that checks to see if the first character in a word or phrase is duplicated later in the phrase. Ignore case in your analysis. Return type? Parameter? Story of the algorithm?

Return type: boolean! Parameter: String: phrase Story: “First, turn the phrase into all lower case. Then, if there isn’t a first char, return false. Otherwise grab that first char. Now walk through all the other chars, looking for that first guy” Note: how do you “walk through” things?

public boolean firstRepeat(String s){ if (s.length() == 0) return false; else{ String t = s.toLowerCase(); char ch = t.charAt(0); boolean found = false; for(int j = 1; j < t.length(); j++){ if (t.charAt(j) == ch) found = true; } return found; } }

Until now: methods are passed, then return primitives, or maybe Strings We need to study parameter passing more carefully, look at how parameter values can, cannot change. Let’s look first at methods that return objects

Infant kid = new Infant("Jill",1); Infant kidTwin = kid.makeTwin("Ivan"); public Infant makeTwin(String name){ int myAge = getAge(); Infant i = new Infant(name,myAge); return i; } int myAge = getAge(); // troubling! int myAge = this.getAge(); this = “calling object”

public class infant{.. public Infant makeTwin(St..n) myAge = this.age; Or myAge = this.getAge();.. p.s.v main(…){ myKid = new Infant(“jill”, 1); myTwin = myKid.makeTwin(“fred”);

class SimplePt{ private int x; private int y; public SimplePt(int xx, int yy){ x= xx; y = yy; } public int getX(){ return x;} public int getY(){ return y;} public double dist(SimplePt other){ double deltaX = (this.getX() - other.getX()); double deltaY = (this.getY() - other.getY()); return Math.sqrt(deltaX*deltaX + deltaY*deltaY); }

(x,y) (x,0) SimplePt p Projection of p onto x axis

public SimplePt xProject(){ SimplePt q = new SimplePt(this.getX(), 0); return q; } }

Parameter passing in Java Consider this method: public void change(int x){x = x + 1;} int a = 3; change(a); System.out.println(a); What’s the value of a?

3 a change 3/4 x Value of a copied to x. Copy works just in one direction!

myKid class: Infant name: Ted age : 3 -> 4 ….. memory address Remember this: method increments age by 1 myKid.anotherMonth();

The key example: public class Flight{ String id; String start; String end; boolean arrived; public Flight(String i, String st, String e,boolean here) { id = i; start = st; end = e; arrived =here; } myFlight = new Flight("CE777","JFK","LAX",false);

airportLAX.landFlight(myFlight); public void landFlight(Flight f){ f.setArrived(true); } We want the landFlight method to change the attributes of myFlight - and we can do it, because myFlight is literally a reference to data, and we aren’t changing that reference (that address). We’re jumping to that address and changing information there.

myFlight landFlight Address of myFlight object information

myFlight class: Flight name: CE777 arrived: false ->true ….. memory address The landFlight parameter does not change - it’s the address of the Flight object information. So our calling principle is not violated. But the referenced object itself does change state: The plane has arrived.