Inf1-OOP. Encapsulation and Collections. Perdita Stevens, adapting earlier version by Ewan Klein. March 2, School of Informatics

Size: px
Start display at page:

Download "Inf1-OOP. Encapsulation and Collections. Perdita Stevens, adapting earlier version by Ewan Klein. March 2, School of Informatics"

Transcription

1 Inf1-OOP Encapsulation and Collections Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics March 2, 2015

2 Encapsulation Accessing Data Immutability Enhanced for loop Collections ArrayList Maps Summary/Admin

3 Object Oriented Programming Procedural programming [verb oriented] tell the computer to do this, then tell the computer to do that. Alan Kay s philosophy: software is a simulation of the real world. We know (approximately) how the real world works; design software to model the real world. Object Oriented programming (OOP) [noun oriented] Programming paradigm based on data types. Identify things that are part of the problem domain or solution. Things in the world know things: instance variables. Things in the world do things: methods.

4 Encapsulation Data type: set of values and operations on those values. E.g., int, String, PrinterQueue, HotelRoom,... Encapsulated data type: hide internal representation of the data type. Separate implementation from design specification: Class provides data representation and code for operations. Client uses data type as black box. API specifies contract between client and class. Bottom line: You don t need to know how a data type is implemented in order to use it.

5 Intuition Client API adjust volume switch channel switch to standby Implementation cathode ray tube 20 screen, 22 kg Sony Trinitron KV20M10 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.

6 Intuition Client API adjust volume switch channel switch to standby Implementation HD LED display 37 screen, 10 kg Samsung UE37C5800 client needs to know how to use API implementation needs to know what API to implement Can substitute better implementation without changing the client.

7 TV Example Using the TV API TV mytv = new TV(); mytv.setvolume(up); mytv.setchannel(film4); mytv.standby();

8 Dalek Encapsulation: Unprotected Dalek public class Dalek { public double batterycharge = 5; public void batteryrecharge(double c) {...} public void move(int distance) {...} } Disabling the Dalek: Dalek d = new Dalek(); // start off with a // well-charged battery d.batterycharge = Double.NEGATIVE_INFINITY; d.batteryrecharge(1000); // battery charge still -Infinity!

9 Dalek Encapsulation: Protected Dalek! public class Dalek { private double batterycharge = 5; public void batteryrecharge(double c) {...} public void move(int distance) {...} } Disabling the Dalek: Dalek d = new Dalek(); // start off with a // well-charged battery d.batterycharge = Double.NEGATIVE_INFINITY; //Triggers compile-time Error Exception...: Unresolved compilation problem: The field Dalek.batteryCharge is not visible

10 Changing Internal Representation Encapsulation: Keep data representation hidden with private access modifier. Expose API to clients using public access modifier. Advantage: can switch internal representations without changing client. Encapsulated data types: Don t touch data to do whatever you want. Instead, ask object to manipulate its data.

11 Immutability Immutable data type: object s internal state cannot change once constructed. mutable Picture Dalek Java arrays immutable String primitive types

12 Immutability: Advantages and Disadvantages Immutable data type: object s value cannot change once constructed. Advantages: Makes programs easier to debug Limits scope of code that can change values Pass objects around without worrying about modification. Disadvantages: New object must be created for every value.

13 The final Modifier Final: declaring a variable to by final means that you can assign it a value only once, in initializer or constructor. E.g., Daleks come in three versions, Mark I, Mark II and Mark III. public class Dalek { private final int mark; private double batterycharge;... } this value can be change by invoking the instance method batteryrecharge() this value doesn't change once the object is constructed Advantages: Helps enforce immutability. Prevents accidental changes. Makes program easier to debug. Documents the fact that value cannot change.

14 Enhanced for loop Enhanced for loop: more concise syntax for looping. int[] numbers = {2, 5, 6, 1, 0, 5}; Ordinary for loop for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } Enhanced for loop for (int num : numbers) { // num is the loop variable System.out.println(num); }

15 Enhanced for loop Enhanced for loop: more concise syntax for looping. Also called for-each loop Easier to use with arrays and other iterables. General form: for ( variable declaration : iterable ){... } NB the variable must have same type as elements in iterable.

16 Enhanced for loop for (int num : numbers) { System.out.println(num); } The colon (:) is often pronounced in. On each iteration, an element of the iterable gets assigned to the loop variable. Loop gets executed once for each element in the iterable. Don t need to initialize loop variable or set termination condition. But you can t keep track (via the loop counter) of where you are in the iteration (e.g., first, last, etc)

17 Enhanced for loop, 3 Another Example: Right String[] words = {"hello", "world", "yes", "we", "can"}; for (String w : words) { System.out.println(w); } Another Example: Wrong String[] words = {"hello", "world", "yes", "we", "can" }; for ( int w : words) { System.out.println(w); }

18 Squeezing into an array

19 Squeezing into an array Length of array is fixed at creation time. Can t be expanded. Can t be shrunk. Arrays are part of Java language uses special syntax. E.g., myarray[i] for accessing the ith element.

20 ArrayList ArrayList: Can grow and shrink as needed; provides methods for inserting and removing elements. Declaration ArrayList<String> cheers = new ArrayList<String>(); This is an array list of strings; counterpart to String[]. Angle brackets indicate that String is a type parameter. Can replace String with e.g. HotelRoom to get different array list type. In general: use ArrayList<E> to collect objects of type E; but E cannot be a primitive type.

21 ArrayList: Methods A newly constructed ArrayList has size 0. ArrayList has various methods, which allow us to: keep on adding new elements; remove elements. The size changes after each addition / removal.

22 ArrayList: Adding Adding Elements ArrayList<String> cheers = new ArrayList<String>(); cheers.add("hip"); cheers.add("hip"); cheers.add("hooray"); int n = cheers.size(); // n gets value 3 add() appends each element to the end of the list. Printing an ArrayList System.out.println(cheers); Output [hip, hip, hooray]

23 ArrayList: More methods Index of first occurrence int ind = cheers.indexof("hip"); // ind gets value 0 Adding element at an index cheers.add(1, "hop"); // 2nd "hip" gets shunted along Elements of cheers: ["hip", "hop", "hip", "hooray"]

24 ArrayList: More methods contains() boolean iship = cheers.contains("hip"); // iship is true remove() cheers.remove("hip"); // removes first occurrence of "hip" Elements of cheers: "hop", "hip", "hooray" get(int index) cheers.get(0); // get the first element // returns "hop"

25 ArrayList and Loops Looping over ArrayList: Standard for loop for (int i = 0; i < cheers.size(); i++) { System.out.println(cheers.get(i)); }

26 ArrayList and Loops Looping over ArrayList: Standard for loop for (int i = 0; i < cheers.size(); i++) { System.out.println(cheers.get(i)); } Enhanced for again for (String s : cheers) { System.out.println(s); }

27 ArrayList and Loops Enhanced for again for (String s : cheers) { System.out.print(s + "\thas index: "); System.out.println(cheers.indexOf(s)); } Output hop has index: 0 hip has index: 1 hooray has index: 2

28 Wrapper Classes Wrapper Classes: The type variable E in a generic type like ArrayList<E> must resolve to a reference type. So ArrayList<int> will not compile. All the primitive types can be turned into objects by using wrapper classes: Primitive Type boolean char double int long Wrapper Class Boolean Character Double Integer Long NB Wrapper class names are always capitalized, always complete words.

29 Auto-boxing Conversion between primitive types and corresponding wrapper classes is automatic. Process of conversion is called auto-boxing Auto-box example Double batterycharge = 2.75; double x = batterycharge; Auto-box example ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0);

30 Import Importing: To get full access to Java API, we need to import classes. Not necessary if class is in same folder, or part of java.lang (e.g., Math library). To use ArrayList, add the appropriate import statement at top of your file: Import example import java.util.arraylist;

31 Import Importing: To get full access to Java API, we need to import classes. Not necessary if class is in same folder, or part of java.lang (e.g., Math library). To use ArrayList, add the appropriate import statement at top of your file: Import example import java.util.arraylist; Import example Wrong! import java.util.arraylist<string>; // Don t use parameter

32 Java API Look at sample Javadoc web page.

33 Java API: Top Node

34 Java API: Entry for ArrayList

35 Maps

36 Associative Arrays Associative array: Associates a collection of unique keys with values. Ordinary arrays: keys can only be integers. Associative arrays allow keys of many types, most notably strings. Examples: 1. Given a person s name, look up a telephone number. 2. Given an internet domain, look up its IP address. 3. Given a geo-location, look up its GPS coordinates. 4. Given a word, look up its frequency in a text. Relationship between key and value: mapping. Java: associative arrays are implemented by type HashMap.

37 Map People to their Matric Nos. Keys Peter Michael Helen Mary John Values s s s s s

38 Map Words to Length Keys Values "this" "is" "the" "time" "and"

39 Map People to their Matric Nos: Wrong! Keys Peter Michael Peter Mary John Values s s s s s NB Keys must be unique.

40 Map People to their Telephone Nos: Wrong! Keys Peter Michael Helen Mary John Values A given key can only be mapped to one value. However, type of value can be array, or some other object.

41 HashMap Import HashMap import java.util.hashmap;

42 HashMap Import HashMap import java.util.hashmap; Declare HashMap HashMap<String, Integer> map = new HashMap<String, Integer>(); HashMap takes two type parameters. Here, String is type of key, Integer is type of value.

43 Mapping Words to their Lengths Goal: Given a string of words, derive an associative array that maps each word to its length. 1. Split the string on whitespace, to yield words. 2. For each word w, add it as a key, and associate it with value w.length(). 3. When we add the same key again, we overwrite the previous association wasteful but harmless in this case. split() method of String String sent = "this is the time and this is the record of the ti String[] words = sent.split(" "); // split on whitespace

44 HashMap: Add and retrieve mappings put(key, Value): put Value as the value of Key in wordlengths. HashMap<String, Integer> wordlengths = new HashMap<String, Integer>(); for (String word : words) { wordlengths.put(word, word.length()); } add a key-value pair to the mapping get(key): get the value of Key in wordlengths. int wl = wordlengths.get("record"); // value is 6

45 HashMap: Add and retrieve mappings wordlengths.keyset(): the set of keys in wordlengths. [of, record, time, is, the, this, and]

46 HashMap: Add and retrieve mappings wordlengths.keyset(): the set of keys in wordlengths. [of, record, time, is, the, this, and] Q How do we list all key-value pairs in a map? A Loop over the set of keys. for (String key : wordlengths.keyset()) { System.out.printf("%s => %s\n", key, wordlengths.get(key)); } Output of => 2 record => 6 time => 4 is => 2 the => 3 this => 4

47 HashMap: Printing Output System.out.println(wordLengths); Output {of=2, record=6, time=4, is=2, the=3, this=4, and=3} Format is {Key1 =Value1, Key2 =Value2,... }

48 Access Control Summary Encapsulation and visibility: All the instance variables and methods (i.e., members) of a class are visible within the body of the class. Access modifiers: control the visibility of your code to other programs. public: member is accessible whenever the class is accessible. private: member is only accessible within the class. default: amounts to public for current purposes. Benefits of encapsulation: Loose coupling Protected variation Exporting an API: the classes, members etc, by which some program is accessed any client program can use the API the author is committed to supporting the API

49 For-each, ArrayList & HashMap Use enhanced for loops whenever you don t need access to the loop variable; fewer opportunities for typos. Use ArrayList when you want your arrays to be able to grow, or you want to easily insert and remove items in the middle of an array. Use HashMap when you want to use keys other than a predetermined list of integers. For more on ArrayList and HashMap, look at the Java API:

50 Reading Zakhour Encapsulation has been discussed on the way, but for references, pp pp : Generics, covering more than we did today pp : Collections, covering a lot more than we did today Java collections not discussed in Sedgewick & Wayne text. Eck or Cay Horstmann (2008) Java Concepts, Sections 6.6, 10.5

Inf1-OOP. Encapsulation. Object Oriented Programming. Encapsulation Accessing Data Immutability. Encapsulation and Collections.

Inf1-OOP. Encapsulation. Object Oriented Programming. Encapsulation Accessing Data Immutability. Encapsulation and Collections. Inf1-OOP Encapsulation and Collections Ewan Klein, Perdita Stevens School of Informatics January 12, 2013 Encapsulation Accessing Data Immutability Enhanced for loop Collections ArrayList Maps Summary/Admin

More information

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics Inf1-OP Collections Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics January 9, 2016 Rigidity of arrays Length of array is fixed at creation time. Can t be expanded. Can t

More information

Rigidity of arrays. Inf1-OP. ArrayList. ArrayList: Methods. Declaration. Collections

Rigidity of arrays. Inf1-OP. ArrayList. ArrayList: Methods. Declaration. Collections Rigidity of arrays Inf1-OP Collections Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics Length of array is fixed at creation time. Can t be expanded. Can

More information

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

Inf1-OP. Collections. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 6, School of Informatics Inf1-OP Collections Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 6, 2017 Rigidity of arrays Length of array is fixed at creation time. Can

More information

Class Foo. instance variables. instance methods. Class FooTester. main {

Class Foo. instance variables. instance methods. Class FooTester. main { Creating classes Inf1-OP Creating Classes Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 Last time we saw how to use a class: create a

More information

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics Inf1-OP Creating Classes Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 Creating classes Last time we saw how to use a class: create a

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

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

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

Inf1-OP. Classes and Objects. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. November 23, School of Informatics

Inf1-OP. Classes and Objects. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. November 23, School of Informatics Inf1-OP Classes and Objects Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics November 23, 2017 Software engineering as managing change The computer doesn

More information

Software engineering as managing change. Inf1-OP. Data representation. How can we make change easier and cheaper?

Software engineering as managing change. Inf1-OP. Data representation. How can we make change easier and cheaper? Software engineering as managing change Inf1-OP Classes and Objects Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 13, 2017 The computer doesn

More information

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein Inf1-OP Arrays 1 Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein Arrays School of Informatics February 26, 2018 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays:

More information

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1. Overview Inf1-OOP Creating Data Types 1 Circle Class Object Default Perdita Stevens, adapting earlier version by Ewan Klein Format Strings School of Informatics January 11, 2015 HotelRoom Class More on

More information

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics Inf1-OP Arrays 1 Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays Arrays:

More information

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics Inf1-OP Arrays 1 Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics January 30, 2017 1 Thanks to Sedgewick&Wayne for much of this content Arrays Arrays:

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

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) COMP-202 Unit 7: More Advanced OOP CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) Managing a big project Many times, you will need to use an Object type that someone else has created. For example,

More information

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming s SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177 Programming Time allowed: THREE hours: Answer: ALL questions Items permitted: Items supplied: There is

More information

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing Inf1-OOP Using Data Types 1 Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics January 11, 2014 Overview Image Processing String Processing Summary/Admin 1 Thanks to Sedgewick&Wayne

More information

CS 302: Introduction to Programming in Java. Lecture 12

CS 302: Introduction to Programming in Java. Lecture 12 CS 302: Introduction to Programming in Java Lecture 12 1 Review What is the 3-step processing for using Objects (think Scanner and Random)? Do objects use static methods or non-static (how do you know)?

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

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

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists 1 A programming problem Consider the following task: Double values representing grades are read until the user enters a negative

More information

Garbage Collection (1)

Garbage Collection (1) Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion

More information

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

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

Introduction to Computer Science I

Introduction to Computer Science I Introduction to Computer Science I Iterators ArrayList Janyl Jumadinova October 31, 2016 Iterators One of the most useful operations for any collection is the ability to run through each of the elements

More information

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass Encapsulation Again Inheritance Encapsulation and Inheritance Inf1-OOP Inheritance and Interfaces Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics March 9, 2015 The Object

More information

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing

Inf1-OOP. Data Types. A Foundation for Programming. type value set operations. Overview. Using Data Types 1. Image Processing Inf1-OOP Using Data Types 1 Ewan Klein, Perdita Stevens School of Informatics January 10, 2013 Overview Image Processing String Processing Summary/Admin 1 Thanks to Sedgewick&Wayne for much of this content

More information

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics Inf1-OOP OOP Exam Review Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics March 16, 2015 Overview Overview of examinable material: Lectures Topics S&W sections Week 1 Compilation,

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

Java Coding 6. Collections

Java Coding 6. Collections Java Coding 6 Collections Arrays of Objects Arrays of objects Array contains only references to objects Track[] tracks; tracks = new Track[5]; Still need to create actual objects tracks[0] = new Track(

More information

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2013/2014 CI101/CI101H. Programming

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2013/2014 CI101/CI101H. Programming s SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2013/2014 CI101/CI101H Programming Time allowed: THREE hours Answer: ALL questions Items permitted: Items supplied: There is no

More information

Main loop structure. A Technical Support System. The exit condition. Main loop body

Main loop structure. A Technical Support System. The exit condition. Main loop body Main concepts to be covered More sophisticated behavior Using library classes Reading documentation Using library classes to implement some more advanced functionality 5.0 2 The Java class library Thousands

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Grouping objects. The requirement to group objects

Grouping objects. The requirement to group objects Grouping objects Introduction to collections 4.0 The requirement to group objects Many applications involve collections of objects: Personal organizers. Library catalogs. Student-record system. The number

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Arrays, Part 2 of 2 Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 1331 Arrays, Part 2 of 2 1 / 16 A few more array topics Variable

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

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

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics Inf1-OP Inf1-OP Exam Review Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 20, 2017 Overview Overview of examinable material: Lectures Week 1

More information

Working with arrays. ArrayLists. Abstraction. Arrays

Working with arrays. ArrayLists. Abstraction. Arrays Working with arrays ArrayLists COMP4 Week 7 Common actions we want to do with arrays: adding and deleting copying looking for a particular element counting the elements Arrays Arrays are intrinsically

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

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Flowcharts [15 points]

Flowcharts [15 points] Flowcharts [15 points] Draw a flowchart that receives some positive integer numbers and calculates and prints how many odd and how many even numbers it has received. The program stops, when it receives

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software

More information

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12 ArrayLists COMP1400 Week 8 Working with arrays There are a number of common actions we want to do with arrays: adding and deleting copying looking for a particular element counting the elements Arrays

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens Organizational Issues Inf1-OOP Course Overview Ewan Klein, Perdita Stevens School of Informatics January 12, 2013 Why Java? Hello, World! in Java Built-in Types Integers Floating-Point Numbers Type Conversion

More information

1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1

1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1 Ba Arrays Arrays A normal variable holds value: An array variable holds a collection of values: 4 Naming arrays An array has a single name, so the elements are numbered or indexed. 0 3 4 5 Numbering starts

More information

Computational Expression

Computational Expression Computational Expression ArrayList Iterators Janyl Jumadinova 7-14 November, 2018 Janyl Jumadinova Computational Expression 7-14 November, 2018 1 / 11 Collections Collection: an object that stores data;

More information

Grouping objects. Main concepts to be covered

Grouping objects. Main concepts to be covered Grouping objects Collections and iterators 3.0 Main concepts to be covered Collections Loops Iterators Arrays Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling

More information

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics Inf1-OOP Inheritance and Interfaces Ewan Klein, Perdita Stevens School of Informatics January 12, 2013 Encapsulation Again Inheritance Encapsulation and Inheritance The Object Superclass Flat vs. Nested

More information

Dynamically sized arrays. Overview. The problem with arrays. Java library. The Java Library. Dynamically sized arrays. Normal Java arrays:

Dynamically sized arrays. Overview. The problem with arrays. Java library. The Java Library. Dynamically sized arrays. Normal Java arrays: Dynamically sized arrays The Java Library Overview Many handy classes and methods Importing a package Dynamically sized arrays Java ArrayList Wrapper classes for primitive types CSCI 135: Fundamentals

More information

CSSE 220 Day 8. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysAndLists from SVN

CSSE 220 Day 8. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysAndLists from SVN CSSE 220 Day 8 Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop Check out ArraysAndLists from SVN Questions? Exam 1 is October 1, 7-9 PM! Over chapters 1-7 You'll have a chance to ask

More information

Processing/Java Syntax. Classes, objects, arrays, and ArrayLists

Processing/Java Syntax. Classes, objects, arrays, and ArrayLists Processing/Java Syntax Classes, objects, arrays, and ArrayLists 1 Processing and Java Java is relentlessly object-oriented Among other things, this means that all methods must occur within classes Processing

More information

CS 211: Using ArrayList, Implementing Arraylist

CS 211: Using ArrayList, Implementing Arraylist CS 211: Using ArrayList, Implementing Arraylist Chris Kauffman Week 12-1 Collections Java has a nice library of containers, Collections framework Interfaces that provide get, set, add methds, conversion

More information

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1 Tutorials Inf1-OP Conditionals and Loops 1 Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein Start this week please let the ITO know if you need to switch tutorial groups. Labs

More information

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang Object Oriented Programming and Design in Java Session 2 Instructor: Bert Huang Announcements TA: Yipeng Huang, yh2315, Mon 4-6 OH on MICE clarification Next Monday's class canceled for Distinguished Lecture:

More information

Mobile App:IT. Methods & Classes

Mobile App:IT. Methods & Classes Mobile App:IT Methods & Classes WHAT IS A METHOD? - A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. -

More information

Computer Science 210 Data Structures Siena College Fall 2018

Computer Science 210 Data Structures Siena College Fall 2018 Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: The ArrayList Arrays are a very common method to store a collection of similar items. Arrays work very well for a lot of situations,

More information

CS Programming I: ArrayList

CS Programming I: ArrayList CS 200 - Programming I: ArrayList Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455 ArrayLists

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

STUDENT LESSON A15 ArrayList

STUDENT LESSON A15 ArrayList STUDENT LESSON A15 ArrayList Java Curriculum for AP Computer Science, Student Lesson A15 1 STUDENT LESSON A15 - ArrayList INTRODUCTION: It is very common for a program to manipulate data that is kept in

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs. Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java

More information

ArrayLists. Chapter 12.1 in Savitch

ArrayLists. Chapter 12.1 in Savitch ArrayLists Chapter 12.1 in Savitch Using arrays to store data q Arrays: store multiple values of the same type. q Conveniently refer to items by their index q Need to know the size before declaring them:

More information

Week 7 - More Java! this stands for the calling object:

Week 7 - More Java! this stands for the calling object: Week 7 - More Java! Variable Scoping, Revisited this Parameter Encapsulation & Principles of Information Hiding: Use of public and private within class API, ADT javadoc Variables of class Type Wrapper

More information

Collections of Objects. Object Oriented Programming Camilo López

Collections of Objects. Object Oriented Programming Camilo López Collections of Objects Object Oriented Programming 2016375-5 Camilo López Outline What are Collections? Arrays as Simple Collections ArrayList HashMap TreeMap Simultaneous References Revisiting the Student

More information

Review: Array Initializer Lists

Review: Array Initializer Lists More on Arrays Review of Arrays of ints, doubles, chars Arrays of objects Command line arguments The ArrayList class Javadoc Review Lecture 8 notes and L&L 7.1 7.2 Reading for this lecture: L&L 7.3 7.7,

More information

Dynamically sized arrays

Dynamically sized arrays Dynamically sized arrays CSCI 135: Fundamentals of Computer Science Keith Vertanen Copyright 2013 The Java Library Overview Many handy classes and methods Importing a package Dynamically sized arrays Java

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

CS1083 Week 2: Arrays, ArrayList

CS1083 Week 2: Arrays, ArrayList CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects CS200: Computer Science I Module 19 More Objects Kevin Sahr, PhD Department of Computer Science Southern Oregon University 1 Class API a class API can contain three different types of methods: 1. constructors

More information

Interfaces, collections and comparisons

Interfaces, collections and comparisons תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name

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

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

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 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper

More information

Topic 3 Encapsulation - Implementing Classes

Topic 3 Encapsulation - Implementing Classes Topic 3 Encapsulation - Implementing Classes And so, from Europe, we get things such as... object-oriented analysis and design (a clever way of breaking up software programming instructions and data into

More information

CS 106A, Lecture 19 ArrayLists

CS 106A, Lecture 19 ArrayLists CS 106A, Lecture 19 ArrayLists suggested reading: Java Ch. 11.8 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights

More information

JAVA GUI PROGRAMMING REVISION TOUR III

JAVA GUI PROGRAMMING REVISION TOUR III 1. In java, methods reside in. (a) Function (b) Library (c) Classes (d) Object JAVA GUI PROGRAMMING REVISION TOUR III 2. The number and type of arguments of a method are known as. (a) Parameter list (b)

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 14 Array Wrap-Up Outline Problem: How can I store information in arrays without complicated array management? The Java language supports ArrayLists

More information

Java Fall 2018 Margaret Reid-Miller

Java Fall 2018 Margaret Reid-Miller Java 15-121 Fall 2018 Margaret Reid-Miller Reminders How many late days can you use all semester? 3 How many late days can you use for a single assignment? 1 What is the penalty for turning an assignment

More information

Lecture 6: ArrayList Implementation

Lecture 6: ArrayList Implementation Lecture 6: ArrayList Implementation CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Programming Assignment Weak AI/Natural Language Processing: Generate text by building frequency lists based

More information

Formatting Output & Enumerated Types & Wrapper Classes

Formatting Output & Enumerated Types & Wrapper Classes Formatting Output & Enumerated Types & Wrapper Classes Quick review of last lecture September 8, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed 1 1 COMP200 GENERICS OOP using Java, from slides by Shayan Javed 2 ArrayList and Java Generics 3 Collection A container object that groups multiple objects 4 Collection A container object that groups multiple

More information

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static,

More information

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1 Today: Java Library Classes for lists. Iterators, ListIterators CS61B Lecture #7 Last modified: Fri Sep 12 14:41:31 2008 CS61B: Lecture #7 1 Abstracting Listness So far, we ve seen fairly primitive types

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java Organisational issues Inf1-OOP Course Overview Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics January 11, 2014 Why Java? Hello, World! in Java Built-in Types Integers Floating-Point

More information

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

More information

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

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

write the functions inside as well as outside the class. So in C++, they are called member functions and not methods.

write the functions inside as well as outside the class. So in C++, they are called member functions and not methods. 1. Q. Why pointers are eliminated from java? 1)Pointers lead to confusion for a programmer. 2)Pointers may crash a program easily, for example, when we add two pointers, the program crashers immediately.

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information