Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

Similar documents
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Introduction to Java

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

COMP 110/L Lecture 13. Kyle Dewey

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

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

Introduction to Programming Using Java (98-388)

Chapter 6 Introduction to Defining Classes

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CMSC 202H. Classes and Objects: Reusing Classes with Composition

CHAPTER 7 OBJECTS AND CLASSES

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Introduction to Java

BM214E Object Oriented Programming Lecture 8

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Chapter 4 Defining Classes I

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Java Magistère BFA

Creating Classes and Objects

PROGRAMMING FUNDAMENTALS

CS 231 Data Structures and Algorithms, Fall 2016

Objects and Classes. Objects and Classes

CHAPTER 7 OBJECTS AND CLASSES

CS 11 java track: lecture 1

Instance Method Development Demo

*Java has included a feature that simplifies the creation of

Section 2.2 Your First Program in Java: Printing a Line of Text

Programming Language Concepts: Lecture 2

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Subclassing for ADTs Implementation

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Lecture 10 Declarations and Scope

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CMSC 132: Object-Oriented Programming II

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Common Misunderstandings from Exam 1 Material

Comments are almost like C++

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Selected Questions from by Nageshwara Rao

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Chapter 6 Lab Classes and Objects

Inheritance (Part 5) Odds and ends

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Object Oriented Modeling

Ohad Barzilay and Oranit Dror

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Java Memory Management

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Lecture 1: Overview of Java

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

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

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

ITI Introduction to Computing II

Certified Core Java Developer VS-1036

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

CS 101 Fall 2006 Midterm 3 Name: ID:

PIC 20A The Basics of Java

For this section, we will implement a class with only non-static features, that represents a rectangle

CS 302 Week 9. Jim Williams

Practice Questions for Chapter 9

Programming Language Concepts: Lecture 2

Class, Variable, Constructor, Object, Method Questions

Computer Programming, I. Laboratory Manual. Final Exam Solution

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

1. [3 pts] What is your section number, the period your discussion meets, and the name of your discussion leader?

Java Fundamentals (II)

II. Compiling and launching from Command-Line, IDE A simple JAVA program

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

ECOM 2324 COMPUTER PROGRAMMING II

Programming Languages and Techniques (CIS120)

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

C++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl

Final Exam Practice. Partial credit will be awarded.

Pointers and Memory 1

C Introduction. Comparison w/ Java, Memory Model, and Pointers

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

CSCI 1301: Introduction to Computing and Programming

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

Final CSE 131B Spring 2004

EECS2030 Fall 2016 Preparation Exercise for Lab Test 2: A Birthday Book

Vector and Free Store (Pointers and Memory Allocation)

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

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

Fundamentos de programação

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 6 Lab Classes and Objects

Selected Java Topics

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

COMP 2355 Introduction to Systems Programming

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

Transcription:

CMSC 131: Chapter 15 (Supplement) Arrays II Arrays of Objects Array of Objects: The base type of an array can be a class object. Example: Array of Strings. String[ ] greatcities = new String[5]; greatcities[2] = new String( "Paris" ); greatcities[0] = "Tokyo"; greatcities[4] = "Beltsville"; greatcities[1] = greatcities[2]; int k = 4; int x = greatcities[k].length( ); char c = greatcities[2].charat( 2 ); Arrays of Objects Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants). Example: Array of Strings String[ ] morecities = { "New York", "Boston", "Kathmandu" ; Example: Initializing using a non-constant expression. String[ ] citystate = { morecities[0] + ", NY", morecities[1] + ", MA" ; Example: Array of Dates (constructor is given month, day, year) Date[ ] birthdays = { new Date( 2, 12, 1809 ), new Date( 2, 11, 1731 ) ;

Command-Line Arguments Dissecting main: Recall the main method declaration: public static void main( String[ ] args ) public: externally visible. static: not associated with any one particular object instance. void: returns no type. String[ ] args: is called with an array of String command-line arguments. What are these arguments? Command-Line Arguments: On Unix- and DOS-style systems, when a program is run from the command prompt, options are included on the command line. For example, the Unix command: % emacs foobar.java runs the emacs program on the file foobar.java. The string foobar.java is a commandline argument to the program. Command-Line Arguments Command-Line Arguments: Provide a way for the user running your program to pass in runtime information. run-time options: affect how the program runs (e.g., run the program in debug mode with additional diagnostic output.) I/O file names: provide the names of files used for input and/or output. special definitions: define special values (e.g., paper size for a word processor). Java Command Arguments: If you run Java directly from the command prompt, these arguments are typed right after the name of your Java program: javac CommandArgTest.java (compile your program) java CommandArgTest f foo b bar (run it) Here f, foo, b, bar are the (4) command-line arguments.

Command-Line Arguments: Eclipse Java Command Arguments: If you run Java from Eclipse, these arguments can be specified when you select Run (rather than Run As ). [Image omitted from notes] Command-Line Arguments: Example public class CommandArgTest { public static void main(string[ ] args) { System.out.println( "Command line arguments:" ); for ( int i = 0; i < args.length; i++) System.out.println( " Argument[" + i + "] = " + args[i] ); Command line arguments: Argument[0] = -f Argument[1] = foo Argument[2] = -b Argument[3] = bar Arrays as Instance Variables We have discussed storing object references in an array. We can also have an array as an instance variable within a class object. Example: Email manager. Consists of: Helper class (EmailMessage) stores: Address field (e.g. bob@yahoo.com ) as a String Message body as a String State (private data): Array of email messages (msgs) of type EmailMessage, and The number of current messages (nmsgs). Behaviors (public methods): Constructor (given maximum number of allowed emails) Add an email to the list Delete an email from the list (given its index) Clear the entire list (and some others)

Email Manager: General Structure EmailMessage: A helper class to store email addresses and bodies. private String addr: email address private String body: email body MailManager: We utilize a partially filled array. We do not store values in all the entries, only in a specified number: private EmailMessage[ ] msgs: Array of Email messages private int nmsgs: Number of active messages Email Manager: EmailMessage EmailMessage: Stores a single email message. It provides the following public methods: EmailMessage( String a, String b ): Standard constructor is given the address a and body b. EmailMessage( EmailMessage e): Copy constructor is given an email message e. String tostring( ): Converts to string. From: <john@notreal.com> Body: [Hi Everybody] We omit the implementation details. MailManager (Part 1) MailManager: Stores the list of email messages and the current number of active messages. Let us investigate its various methods: public MailManager( int max ) : Constructor is given the maximum number of emails allowed. It allocates the array for the messages and sets the current number of messages to 0. msgs = new EmailMessage[max]; nmsgs = 0; public boolean isfull( ) : This tests whether the email array is full. return ( nmsgs >= msgs.length ); public boolean addmsg( EmailMessage m ) : Adds a given message to the end of the list (nmsgs) and increments the size (nmsgs++). If the list is full, it returns false, and otherwise it returns true. if ( isfull( ) ) return false; msgs[nmsgs++] = new EmailMessage( m ); return true;

MailManager: Class Definition (Part 1) public class MailManager { private EmailMessage[ ] msgs; private int nmsgs; // the messages // current number of messages public MailManager( int max ) { msgs = new EmailMessage[max]; nmsgs = 0; public boolean isfull( ) { return ( nmsgs >= msgs.length ); public boolean addmsg( EmailMessage m ) { if ( isfull( ) ) return false; msgs[nmsgs++] = new EmailMessage( m ); return true; // more to come MailManager (Part 2) MailManager: Next we consider the removal methods for deleting a single message and clearing the whole list. public boolean deletemsg( int d ) : This deletes a single email at index d. If d is out of range, we return false. Otherwise, we eliminate the entry by sliding the subsequent emails down by one. for ( int j = d+1; j < nmsgs; j++ ) msgs[j-1] = msgs[j]; nmsgs--; public void clear( ) : Clears the entire list. msgs[i] = null; nmsgs = 0; Q: Setting nmsgs to 0 would have been sufficient. Why go to the extra effort of setting them to null? Ans: By unlinking them, we make it possible for the garbage collector to remove them.

MailManager: Class Definition (Part 2) public class MailManager { private EmailMessage[ ] msgs; private int nmsgs; // the messages // current number of messages // construct and add omitted public boolean deletemsg( int d ) { if ( d < 0 d > msgs.length ) return false; for ( int j = d+1; j < nmsgs; j++ ) msgs[j-1] = msgs[j]; nmsgs--; return true; public void clear( ) { msgs[i] = null; nmsgs = 0; // more to come MailManager (Part 3) MailManager: Finally, consider tostring and an accessor, getmessages, which returns an array of email messages. public String tostring( ) : Converts the messages into a string. public EmailMessage[ ] getmessages( ) : Returns an array containing all the email messages. EmailMessage[ ] result = new EmailMessage[nMsgs]; { result[i] = new EmailMessage( msgs[i] ); return result;

MailManager: Class Definition (Part 3) public class MailManager { private EmailMessage[ ] msgs; private int nmsgs; // the messages // current number of messages // prior methods omitted public String tostring( ) { String result = "Mailbox: "; if ( nmsgs == 0 ) return result + "empty"; result = result + "\n " + msgs[i]; return result; public EmailMessage[ ] getmessages( ) { EmailMessage[ ] result = new EmailMessage[nMsgs]; { result[i] = new EmailMessage( msgs[i] ); return result; public static void main( String[ ] args ) { MailManager: Sample Driver MailManager mymail = new MailManager( 5 ); mymail.addmsg( new EmailMessage( "john@notreal.com", "Hi Everybody" ) ); mymail.addmsg( new EmailMessage( "rose@fantasy.com", "I hate spam" ) ); System.out.println( mymail ); Mailbox: From: <john@notreal.com> Body: [Hi Everybody] From: <rose@fantasy.com> Body: [I hate spam] mymail.addmsg( new EmailMessage( "pete@imaginary.com", "Me too" ) ); mymail.deletemsg( 0 ); System.out.println( mymail ); mymail.clear( ); Mailbox: From: <rose@fantasy.com> Body: [I hate spam] From: <pete@imaginary.com> Body: [Me too] System.out.println( mymail ); Mailbox: empty

Deep/Shallow Copying and Privacy Leaks Deep copying: Make a copy of all objects. This is what we implemented. This is always safe because changes to the copied data cannot affect the original object s integrity. EmailMessage[ ] mymessages = mymail.getmessages( ); EmailMessage[ ] result = new EmailMessage[nMsgs]; result[i] = new EmailMessage( msgs[i] ); Deep/Shallow Copying and Privacy Leaks Very shallow copy: What if we just copy the array reference? result = msgs; return result; // Shallow copy! Dangerous There are two problems with this: Minor problem: Gives the entire array, not just the current messages. Major problem: We give the class user a pointer directly to our private data (msgs). Now they can do whatever they want to it! This is called a privacy leak: private data is directly accessible to the outside world. Deep/Shallow Copying and Privacy Leaks Half-deep copy: Copy the array, but do not copy the underlying objects. EmailMessage[ ] result = new EmailMessage[nMsgs]; result[i] = msgs[i]; // Shallow: Copies a pointer to msgs[i] Not always bad: It is harmless if it is not possible to change the underlying objects (e.g., String). Otherwise it is harmful. Classes that cannot be changed after creation are immutable.