Admin. CS 112 Introduction to Programming. Recap: OOP. Math.random() Design. Static Math.random() method vs Random Objects

Size: px
Start display at page:

Download "Admin. CS 112 Introduction to Programming. Recap: OOP. Math.random() Design. Static Math.random() method vs Random Objects"

Transcription

1 Admin CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: q PS7 (GuitarHero) Walkthrough Tuesday at 8 pm q Project Please start to work on teaming as soon as you can If you need to find a partner, please send me a note so that we can arrange meetings at office hours 2 Recap: OOP Recap: Side-by-Side Comparison q Identify objects that are part of the problem domain or solution q An object includes both state and behaviors Focus on external behaviors (more shortly) Func%on- oriented public class DrawRocket{ public static void main(string args[]){ for (int size = 3; size < 10; size++){ drawrocket(size); public static void drawrocket(int scale){ printcap(scale); public static void printcap(int scale){ Object- oriented public class RocketDrawing { public static void main(string args[]){ for (int size = 3; size < 10; size++){ Rocket currocket = new Rocket(size); currocket.draw(); public class Rocket{ public int rocketsize; public Rocket(int rocketsize){ this.rocketsize = rocketsize; public void drawrocket(){ printcap(); public void printcap(){ 3 4 Math.random() Design Static Math.random() method vs Random Objects public static double random() Returns a random number between 0 and 1 Most static methods that we encountered are deterministic methods: given the same input parameter, gives the same output But the random() method cannot be, i.e., it is non-deterministic 5 6 1

2 A Little Peek into Random Number Generation The random numbers generated by Java are actually pseudo-random numbers Suppose you get a random number R n, the next time you call it to get R n+1, it returns: R n+1 = R n * it then converts to the right range to you! This method is proposed by D. H. Lehmer in mathematical jargon, Java uses a type of linear congruential pseudorandom number generator Implication: the previously returned random number must be remembered. 7 The Random class A Random object generates random numbers as preceding slide Class Random is found in the java.util package. import java.util.random; Method name Example: Description Random(long seed) Create a random number using a seed (R 0 ) Random() setseed(seed) nextint(<max>) Create a random number using a seed derived from time Initialize the random number generator Returns a random integer in the range [0, max) in other words, 0 to max-1 inclusive nextdouble() Returns a random real number in [0.0, 1.0) Random rand = new Random(); // Default, seed by time int randomnumber = rand.nextint(10); // 0-9 Q: What is the state of a Random object? Using Random Numbers Math.random() Example: to get a random number from 1 to 20 int n = rand.nextint(20) + 1; // 1-20 inclusive To get a number in arbitrary range [min, max] inclusive: <name>.nextint(<size of range>) + <min> Where <size of range> is (<max> - <min> + 1) Example: A random integer between 4 and 10 inclusive: int n = rand.nextint(7) + 4; public static double random() When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.random() This new pseudorandom-number generator is used thereafter for all calls to this method. java/lang/math.html#random() 10 How May Math.random()be Implemented? Advantage and Issue of Using Math.random() A static variable, also called a singleton. Advantage Hide object-oriented programming, simplifying programming public class Math { static Random rand; public static double random() { if (rand == null) rand = new Random(); return rand.nextdouble();.. 11 Issue A single Random object: Every request for a random number is handled by one single random object, creating a bottleneck client 1 client 1 client 2 client 3 client 2 client

3 DrawingPanel Developed for the Back to Basics Textbook, using an OOP approach. Two key classes: StdDraw vs DrawingPanel DrawingPanel: A window on the screen. Not part of Java; provided by the textbook. Graphics: A "pen" to draw shapes and lines on a window. from Java standard class library 13 DrawingPanel Graphics A "Canvas" object that represents windows/drawing surfaces To create a window: DrawingPanel name = new DrawingPanel(width, height); Example: DrawingPanel panel = new DrawingPanel(300, 200); See SimplePanels.java DrawingPanel draws shapes / lines / characters /imagines using another object of type Graphics. Graphics: Your painting toolset: "Pen" or "paint brush" objects to draw lines and shapes; fonts for character, Access it by calling getgraphics on a DrawingPanel object. Graphics g = panel.getgraphics(); Draw shapes by calling methods on the Graphics object. g.fillrect(10, 30, 60, 35); g.filloval(80, 40, 50, 70); Graphics Coordinate System Some Graphics Methods Each (x, y) position is a pixel ("picture element"). Position (0, 0) is at the window's top-left corner. x increases rightward and the y increases downward. A rectangle from (0, 0) to (200, 100) looks like this: (0, 0) x+ (200, 100) y+ Method name g.setcolor(color); Description set Graphics to paint any following shapes in the given color g.drawline(x1, y1, x2, y2); line between points (x1, y1), (x2, y2) g.drawoval(x, y, width, height); outline largest oval that fits in a box of size width * height with top-left at (x, y) g.drawrect(x, y, width, height); outline of rectangle of size width * height with top-left at (x, y) g.drawstring(text, x, y); text with bottom-left at (x, y) g.filloval(x, y, width, height); fill largest oval that fits in a box of size width * height with top-left at (x, y) g.fillrect(x, y, width, height); fill rectangle of size width * height with top-left at (x, y) See SimplePanels.java 3

4 Benefit and Issue of StdDraw StdDraw Similar to Math.random() creating a single Random object, StdDraw creates a single drawing object Benefit Hides OOP programming complexity (No objects) Simplifies programming by converting the native Java coordinate system (up-side down) to a more intuitive coordinate system Adds additional methods such as square, point Potential issue Only 1 drawing surface in your program See SimplePanels.java Recap: The Complex Class: Design Question public class Complex { double re; double im; public Complex(double real, double imag) { re = real; im = imag; public?? plus(complex b) { - How to design the plus instance method? Recap: The Consistency (Familiarity) Design Principle Suppose a, b, and c are standard numbers (Complex numbers are numbers after all) What does a + b (think a.+(b) ) do? Returns the value of a + b so that we can write a + b + c; the value of a is not changed. public Complex plus(complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); 21 Complex.java public class Complex { double re; double im; public Complex(double real, double imag) { re = real; im = imag; public String tostring() { return re + " + " + im + "i"; public double abs() { return Math.sqrt(re*re + im*im); public Complex plus(complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); public Complex times(complex b) { double real = re * b.re im * b.im; double imag = re * b.im + im * b.re; return new Complex(real, imag); instance variables constructor refers to b's instance variable creates a Complex object, and returns a reference to it methods 22 Immutability: Advantages and Disadvantages A Simple Client Immutable data type. Object's state does not change once constructed. Complex is an example of Immutable objects. String defined by Java is another example. Advantages. Avoid aliasing bugs. Makes program easier to debug. Limits scope of code that can change values. Pass objects around without worrying about modification. Disadvantage. New object must be created for every value. public static void main(string[] args) { Complex a = new Complex( 3.0, 4.0); Complex b = new Complex(-2.0, 3.0); Complex c = new Complex( 2.0, 3.0); Complex d = a.plus(b).plus(c); System.out.println("a = " + a.tostring() ); System.out.println("b = " + b.tostring() ); System.out.println("c = " + c.tostring() ); System.out.println( d = " + d.tostring() ); % java TestClient a = i b = i c = i d = i 24 4

5 A Complex Client: Mandelbrot Set Mandelbrot set. A set of complex numbers. Plot. Plot (x, y) black if z = x + y i is in the set, and white otherwise. A Complex Client: Mandelbrot Set Mandelbrot set. Is complex number z 0 in the set? Iterate z t + 1 = (z t ) 2 + z 0. If z t diverges to infinity, then z 0 is not in set; otherwise z 0 is in set. t z t t z t 0-1/2 + 0i i 1-1/4 + 0i i 2-7/16 + 0i i Can be used to model complex rugged shapes such as uneven clouds, contours of mountains, winding riverbeds, arts, No simple formula describes which complex numbers are in set. - Instead, described using an algorithm / i / i / i z = -1/2 is in Mandelbrot set i i i z = 1 + i not in Mandelbrot set Testing Point in Mandelbrot Set Practical issues. Cannot iterate infinitely many times. Approximate solution. Fact: if z t > 2 for any t, then z not in Mandelbrot set. Pseudo-fact: if z then z "likely" in Mandelbrot set. Testing Point in Mandelbrot Set Our Mandelbrot test: Returns the number of iterations to check if z0 is in Mandelbrot public static int mand(complex z0) { final int max = 255; Complex z = z0; for (int t = 0; t < max; t++) { if (z.abs() > 2.0) return t; z = z.times(z).plus(z0); return max; z = z2 + z Plotting Mandelbrot Set Plotting Mandelbrot Set (DrawingPanel) Practical issues. Cannot plot infinitely many points. Display technique. User specifies center, size Program maps the points on the N-by-N drawing panel to center, size x c + y c i (x c -size/2) + (y c -size/2) i Each grid has length size/n 29 Plot the Mandelbrot set in gray scale. public static void main(string[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); DrawingPanel panel = new DrawingPanel(N, N); Graphics g = panel.getgrahics(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/n; double y0 = yc - size/2 + size*j/n; Complex z0 = new Complex(x0, y0); int gray = mand(z0); Color color = new Color(gray, gray, gray); g.setcolor( color ); g.drawline(i, N-1-j, i, N 1 - j); // end of for // end of for (0, 0) is upper left 30 5

6 Mandelbrot Set Mandelbrot Set % java MandelbrotDrawingPanel % java MandelbrotDrawingPanel % java MandelbrotDrawingPanel % java MandelbrotDrawingPanel Picture Data Type Raster graphics. Basis for image processing. Set of values. 2D array of Color objects (pixels). Plotting Mandelbrot Set (Picture) Plot the Mandelbrot set in gray scale. public static void main(string[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); Picture pic = new Picture(N, N); // NxN picture for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/n; double y0 = yc - size/2 + size*j/n; Complex z0 = new Complex(x0, y0); int gray = mand(z0); scale to screen Color color = new Color(gray, gray, gray); coordinates pic.set(i, N-1-j, color); API. // end of for // end of for (0, 0) is upper left 34 Mandelbrot Set Plot the Mandelbrot set in color using a color mapping table. % java ColorMandelbrot Mandelbrot Set Plot the Mandelbrot set in color using a color mapping table. % java ColorMandelbrot

7 Mandelbrot Set (-1.5, -1) Mandelbrot Set Outline q See video v=cxm9j77stl0 q Admin and recap q Defining classes o Motivation and basic syntax o Examples Ø The encapsulation principle Two Views of an Object The Encapsulation Principle You can take one of two views of an object: external (API) - the interaction of the object with its clients An object should be an encapsulated entity (a black box), providing an API (i.e., a set of external visible state and services/behaviors) The user, or client, of an object should not be aware of the internal representation of state or details of algorithms internal (implementation) - the structure of its data, the algorithms used by its methods Client can see only the external API (state and behaviors) Client Methods 41 Client should not see the internal state or behaviors Data/state 42 7

8 Encapsulation Analogy Encapsulation Analogy You don't understand the inner details of iphone, and you don't need to. Apple does not want to commit to any internal details so that Apple can continuously update the internal Client API Implementation client needs to know how to use API implementation needs to know what API to implement Implementation and client need to agree on API ahead of time. Examples What are some risks of allowing others to view/access the internal state of a class? The Coin class The Ball class The Point class The BankAccount class Why Encapsulating Data Consistency: so that we make it impossible for others to "reach in" and directly alter another object's state Protect object from unwanted access Example: Can't fraudulently increase an BankAccount balance. Maintain state invariants Example: Only allow BankAccounts with non-negative balance. Example: Only allow Dates with a month from Flexibility: so that you can change the state representation later without worrying about breaking others code Example: Point could be rewritten in polar coordinates (r, θ) so long you provide translation in the interface, clients will not see difference. Accomplish Encapsulation: Access Modifiers In Java, we accomplish encapsulation through the appropriate use of access modifiers An access modifier is a Java reserved word that specifies the accessibility of a method, data field, or class we will discuss two access modifiers: public, private we will discuss the other modifier (protected) later The public and private Access Modifiers access modifiers enforce encapsulation public members (data and methods: can be accessed from anywhere private members: can be accessed from a method defined in the same class Members without an access modifier: default private accessibility, i.e., accessible in the same package; otherwise, not accessible

9 Using Access Modifiers to Implement Encapsulation: Methods The Effects of Public and Private Accessibility Only service methods should be made public Support or helper methods created simply to assist service methods should be declared private variables methods public violate Encapsulation Use Caution provide services to clients private enforce encapsulation support other methods in the class Examples: Set the Access Modifiers Class Diagram Coin Ball BankAccount Point Coin - face : int + flip() : void + isheads() : boolean + tostring() : String class name attributes methods 51 Above is a class diagram representing the Coin class. - indicates private data or method + indicates public data or method 52 Ask, Don't Touch Encapsulated data types. Don't touch data and do whatever you want. Instead, ask object to manipulate its data. "Ask, don't touch." Adele Goldberg Former president of ACM Co-developed Smalltalk Lesson. Limiting scope makes programs easier to maintain and understand. "principle of least privilege" 9

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming User-Defined Data Types: Using static to hide OOP; Encapsulation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming User-Defined Data Types: Examples Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q PS6 (Sukoku)

More information

3.2 Creating Data Types

3.2 Creating Data Types 1 3.2 Creating Data Types Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

Building Java Programs

Building Java Programs Building Java Programs Graphics reading: Supplement 3G videos: Ch. 3G #1-2 Objects (briefly) object: An entity that contains data and behavior. data: variables inside the object behavior: methods inside

More information

3.2 Creating Data Types

3.2 Creating Data Types Data Types 3.2 Creating Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

10. Creating Data Types

10. Creating Data Types COMPUTER SCIENCE S E D G E W I C K / W A Y N E 10. Creating Data Types Section 3.2 http://introcs.cs.princeton.edu COMPUTER SCIENCE S E D G E W I C K / W A Y N E 10. Creating Data Types Overview Point

More information

Topic 8 graphics. -mgrimes, Graphics problem report 134

Topic 8 graphics. -mgrimes, Graphics problem report 134 Topic 8 graphics "What makes the situation worse is that the highest level CS course I've ever taken is cs4, and quotes from the graphics group startup readme like 'these paths are abstracted as being

More information

Garfield AP CS. Graphics

Garfield AP CS. Graphics Garfield AP CS Graphics Assignment 3 Working in pairs Conditions: I set pairs, you have to show me a design before you code You have until tomorrow morning to tell me if you want to work alone Cumulative

More information

10. Creating Data Types

10. Creating Data Types Overview Point charges Turtle graphics Complex numbers Section 3.2 Object-oriented programming (OOP) Implementing a data type Object-oriented programming (OOP). To create a data type, you need provide

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 2 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Computer Science. 9. Creating Data Types. Computer Science COMPUTER SCIENCE. Section 3.2.

Computer Science. 9. Creating Data Types. Computer Science COMPUTER SCIENCE. Section 3.2. COMPUTER SCIENCE S E D G E W I C K / W A Y N E PA R T I : P R O G R A M M I N G I N J AVA Computer Science Computer Science An Interdisciplinary Approach Section 3.2 ROBERT SEDGEWICK K E V I N WAY N E

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 2 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Building Java Programs

Building Java Programs Building Java Programs Graphics reading: Supplement 3G videos: Ch. 3G #1-2 Objects (briefly) object: An entity that contains data and behavior. data: Variables inside the object. behavior: Methods inside

More information

26/3/ Creating Data Types. Data Type. Defining Data Types in Java. Point Charge Data Type. Charge Data Type: A Simple Client

26/3/ Creating Data Types. Data Type. Defining Data Types in Java. Point Charge Data Type. Charge Data Type: A Simple Client Data Types 3.2 Creating Data Types Data type. Set of values and operations on those values. Basic types. Data Type boolean int String Set of Values true, false -2 31 to 2 31-1 sequence of Unicode characters

More information

Building Java Programs

Building Java Programs Building Java Programs Supplement 3G: Graphics 1 drawing 2D graphics Chapter outline DrawingPanel and Graphics objects drawing and filling shapes coordinate system colors drawing with loops drawing with

More information

Building Java Programs

Building Java Programs Building Java Programs Graphics Reading: Supplement 3G Objects (briefly) object: An entity that contains data and behavior. data: variables inside the object behavior: methods inside the object You interact

More information

A Foundation for Programming

A Foundation for Programming 3.1 Objects Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 7/28/2015 3:46:55 PM A Foundation for Programming any program you might

More information

Topic 8 Graphics. Margaret Hamilton

Topic 8 Graphics. Margaret Hamilton Topic 8 Graphics When the computer crashed during the execution of your program, there was no hiding. Lights would be flashing, bells would be ringing and everyone would come running to find out whose

More information

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012)

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012) 2/26/12 Object Oriented Programming CS 112 Introduction to Programming Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012) Lecture #21: Designing Data Types Tell the computer

More information

3.1 Objects 7/29/2014 1:49:50 PM

3.1 Objects 7/29/2014 1:49:50 PM 3.1 Objects Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 22 21 7/29/214 1:49:5 PM A Foundation for Programming any program you might want

More information

Admin. CS 112 Introduction to Programming. Recap: Encapsulating Data. Ask, Don't Touch. Recap: Encapsulating Data. Recap: Encapsulation/How

Admin. CS 112 Introduction to Programming. Recap: Encapsulating Data. Ask, Don't Touch. Recap: Encapsulating Data. Recap: Encapsulation/How Adin CS Introduction to Prograing q Updated class schedule Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Coputer Science Departent Yale University 308A Watson, Phone: 43-6400

More information

Using Graphics. Building Java Programs Supplement 3G

Using Graphics. Building Java Programs Supplement 3G Using Graphics Building Java Programs Supplement 3G Introduction So far, you have learned how to: output to the console break classes/programs into static methods store and use data with variables write

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #31: Software Reuse through Inheritance Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

Admin. CS 112 Introduction to Programming. Counting Down: Code Puzzle. Counting Down: Code Puzzle

Admin. CS 112 Introduction to Programming. Counting Down: Code Puzzle. Counting Down: Code Puzzle Admin CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness. Spring 2014 Student Responsibilities Reading: Textbook, Sections 6.1 6.3 Attendance Recall: Writing Methods Decomposition: break a problem down into smaller subproblems Use methods whenever you can in

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes Student Responsibilities Mat 2170 Week 9 Objects and Classes Spring 2014 Reading: Textbook, Sections 6.1 6.3 Lab 9 Attendance 1 2 Recall: Writing Methods 3 Decomposition: break a problem down into smaller

More information

Topic 9 More Graphics. Based on slides bu Marty Stepp and Stuart Reges from

Topic 9 More Graphics. Based on slides bu Marty Stepp and Stuart Reges from Topic 9 More Graphics Based on slides bu Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Clicker Question What happens if a graphics object is used to draw a shape that exceeds the

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q Issues on PS3 NumberCoolness:

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q Issues on PS3 NumberCoolness:

More information

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance Admin CS 112 Introduction to Programming q Class project Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu 2 Recap: OOP Analysis

More information

CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random. Adapted from slides by Marty Stepp and Stuart Reges CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random Adapted from slides by Marty Stepp and Stuart Reges Exercise: multiple parameters def main(): print_number(4, 9) print_number(17, 6) print_number(8,

More information

Designing data types. Fundamentals of Computer Science I

Designing data types. Fundamentals of Computer Science I Designing data types Fundamentals of Computer Science I 2 Overview Object Oriented Programming (OOP) Data encapsulation Important consideration when designing a class Access modifiers Getters and setters

More information

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality Designing data types Overview Object Oriented Programming (OOP) Data encapsulation Important consideration when designing a class Access modifiers Immutability, preventing change to a variable Checking

More information

CIT Special final examination

CIT Special final examination CIT 590-2016 Special final examination Name (please write your official name) PennID Number Note that your PennID number is the 8 digit bold number on your penn card. DO NOT START WRITING (aside from name

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CIS 110 Introduction to Computer Programming Summer 2014 Final. Name:

CIS 110 Introduction to Computer Programming Summer 2014 Final. Name: CIS 110 Introduction to Computer Programming Summer 2014 Final Name: PennKey (e.g., bhusnur4): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity

More information

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Admin. CS 112 Introduction to Programming. Recap. Example: Nested Loop. Example: Rewrite

Admin. CS 112 Introduction to Programming. Recap. Example: Nested Loop. Example: Rewrite Admin CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu q Issues on PS3 NumberCoolness:

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

More information

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts Admin CS 112 Introduction to Programming q PS6 (Sukoku) questions? q Planning of remaining of the semester User-Defined Data Types Yang (Richard) Yang Computer Science Department Yale University 308A Watson,

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

Recap: Assignment as an Operator CS 112 Introduction to Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming Recap: Assignment as an Operator CS 112 Introduction to Programming q You can consider assignment as an operator, with a (Spring 2012) lower precedence than the arithmetic operators First the expression

More information

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #7: Variable Scope, Constants, and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112

More information

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited Table of Contents Date(s) Title/Topic Page #s 11/6 Chapter 3 Reflection/Corrections 56 Chapter 4: Writing Classes 4.1 Objects Revisited 57 58-59 look over your Ch 3 Tests and write down comments/ reflections/corrections

More information

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types Classes and objects A foundation for programming any program you might want to write objects functions and modules build even bigger programs and reuse code http://www.flickr.com/photos/vermegrigio/5923415248/

More information

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012 CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012 Name: This exam consists of 6 problems on the following 7 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.

More information

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 4: Writing Classes Objects An object has: Presentation slides for state - descriptive characteristics Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus,

More information

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

Repetition. We might start out with the following program that draws only the left most object.

Repetition. We might start out with the following program that draws only the left most object. page 2 1 Chapter 2 Repetition 2.1 Repetition Methods with parameters Suppose we want to produce the following image. We might start out with the following program that draws only the left most object.

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

Unit 1 Lesson 4. Introduction to Control Statements

Unit 1 Lesson 4. Introduction to Control Statements Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use

More information

CS 312 Midterm 1 Spring 2013

CS 312 Midterm 1 Spring 2013 CS 312 Midterm 1 Spring 2013 Your Name Your UTEID Circle your TAs Name: VICKY LUIS Problem Number Topic Points Possible 1 Expressions 11 2 Loop Evaluation 6 3 Method Tracing 10 4 Method Tracing 3 5 Writing

More information

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with. 1 Outline TOPIC 3 INTRODUCTION TO PROGRAMMING Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return; doubles and casting reading: 3.2, 4.1 videos: Ch. 3 #2 Copyright 2009 by Pearson Education Finish Car example Lecture outline Returns Java Math library

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Java Primitive Data Types; Arithmetic Expressions Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example Admin CS 112 Introduction to Programming q Programming assignment 2 to be posted tonight Java Primitive Data Types; Arithmetic Expressions Yang (Richard) Yang Computer Science Department Yale University

More information

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables

More information

Multiple Choice Using Object Methods

Multiple Choice Using Object Methods Multiple Choice Using Object Methods 01. Consider the following statement: Blank is a computer science tool that involves using program features without knowledge of how the program features are implemented.

More information

Use the scantron sheet to enter the answer to questions (pages 1-6)

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

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

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

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name: CSC 1051 Algorithms and Data Structures I Midterm Examination March 2, 2017 Name: Question Value Score 1 10 2 10 3 20 4 20 5 20 6 20 TOTAL 100 Please answer questions in the spaces provided. If you make

More information

Week 1 Exercises. All cs121 exercise and homework programs must in the default package and use the class names as given.

Week 1 Exercises. All cs121 exercise and homework programs must in the default package and use the class names as given. Week 1 Exercises Monday: MLK Day Unclear about building access and lab access Best case: Lab is open with TAs: 4 6 pm (Binh), 6 8 (Hoang) Worst case: locked building, lab TAs at Piazza Week 1 exercise

More information

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs Lecture 7 Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs Reading: Skip Lists: A Probabilistic Alternative to Balanced Trees paper (Pugh);

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

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

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 5 problems on the following 7 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam.

More information

Introduction to Computers and Java

Introduction to Computers and Java Introduction to Computers and Java Chapter 1 Chapter 1 1 Objectives overview computer hardware and software introduce program design and object-oriented programming overview the Java programming language

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Mathematics 350 Section 6.3 Introduction to Fractals

Mathematics 350 Section 6.3 Introduction to Fractals Mathematics 350 Section 6.3 Introduction to Fractals A fractal is generally "a rough or fragmented geometric shape that is self-similar, which means it can be split into parts, each of which is (at least

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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

1. Which of the following is the correct expression of character 4? a. 4 b. 4 c. '\0004' d. '4' Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java

More information

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012 CS 302: Introduction to Programming in Java Lecture 11 Yinggang Huang 1 Review How do we call a method? What are method inputs called? How many values can be returned from a method? Write a method header

More information

CITS1001 week 6 Libraries

CITS1001 week 6 Libraries CITS1001 week 6 Libraries Arran Stewart April 12, 2018 1 / 52 Announcements Project 1 available mid-semester test self-assessment 2 / 52 Outline Using library classes to implement some more advanced functionality

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

The keyword list thus far: The Random class. Generating Random Numbers. Topic 16 Topic 16 Creating Correct Programs "It is a profoundly erroneous truism, repeated by all the copybooks, and by eminent people when they are making speeches, that we should cultivate the habit of thinking

More information

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

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. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.aspx?m=5507&c=618&mo=18917&t=191&sy=2012&bl... Page 1 of 13 Units: - All - Teacher: ProgIIIJavaI, CORE Course: ProgIIIJavaI Year: 2012-13 Intro to Java How is data stored by a computer system? What does a compiler do? What are the advantages of using

More information

Assignment 1 due Monday at 11:59pm

Assignment 1 due Monday at 11:59pm Assignment 1 due Monday at 11:59pm The heart of Object-Oriented Programming (Now it gets interesting!) Reading for next lecture is Ch. 7 Focus on 7.1, 7.2, and 7.6 Read the rest of Ch. 7 for class after

More information

COS 126 Midterm 1 Written Exam Fall 2011

COS 126 Midterm 1 Written Exam Fall 2011 NAME: login id: Precept: COS 126 Midterm 1 Written Exam Fall 2011 This test has 8 questions, weighted as indicated. The exam is closed book, except that you are allowed to use a one page cheatsheet. No

More information

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments. -Alfred North Whitehead Topic 16 Creating Correct Programs "It is a profoundly erroneous truism, repeated by all the copybooks, and by eminent people when they are making speeches, that we should cultivate the habit of thinking

More information

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with. 1 Outline 2 TOPIC 3 INTRODUCTION TO PROGRAMMING Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 ); Sample Final Exam 1. Evaluate each of the following expressions and show the result and data type of each: Expression Value Data Type 14 % 5 1 / 2 + 1 / 3 + 1 / 4 4.0 / 2.0 Math.pow(2.0, 3.0) (double)(2

More information

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics.

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics. Additional Controls, Scope, Random Numbers, and Graphics CS109 In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics. Combo

More information

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday

More information

Topic 27 classes and objects, state and behavior

Topic 27 classes and objects, state and behavior Topic 27 classes and objects, state and behavior "A 'class' is where we teach an 'object' to behave." -Rich Pattis Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

More information

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding Java Class Design Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Objectives Implement encapsulation Implement inheritance

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

EECS168 Exam 3 Review

EECS168 Exam 3 Review EECS168 Exam 3 Review Exam 3 Time: 2pm-2:50pm Monday Nov 5 Closed book, closed notes. Calculators or other electronic devices are not permitted or required. If you are unable to attend an exam for any

More information