Answer Key. 1. General Understanding (10 points)

Similar documents
Object-Oriented Programming in Java

Creating a Simple, Multithreaded Chat System with Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Class 32: The Java Collections Framework

Datastrukturer och standardalgoritmer i Java

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Data Structures in the Java API

D06 PROGRAMMING with JAVA

INPUT AND OUTPUT STREAMS

public static void main(string[] args) { System.out.println("hello, world"); } }

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Java from a C perspective. Plan

Lecture 2: Data Structures Steven Skiena. skiena

Explain the relationship between a class and an object. Which is general and which is specific?

What is an I/O Stream?

The Java Collections Framework

WRITING DATA TO A BINARY FILE

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Parallel Programming

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

What are exceptions? Bad things happen occasionally

Lecture J - Exceptions

D06 PROGRAMMING with JAVA

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

J a v a Quiz (Unit 3, Test 0 Practice)

Java Coding Practices for Improved Application Performance

CS506 Web Design and Development Solved Online Quiz No. 01

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Approach of Unit testing with the help of JUnit

16.1 DataFlavor DataFlavor Methods. Variables

Introduction to Data Structures

OBJECT ORIENTED PROGRAMMING LANGUAGE

Fundamentals of Java Programming

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

13 File Output and Input

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

JAVA COLLECTIONS FRAMEWORK

Lesson: All About Sockets

Stacks. Linear data structures

Stream Classes and File I/O

Quick Introduction to Java

Programming Methods & Java Examples

Division of Informatics, University of Edinburgh

Simple Java I/O. Streams

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Event-Driven Programming

Java SE 8 Programming

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

JAVA - FILES AND I/O

Hadoop Streaming coreservlets.com and Dima May coreservlets.com and Dima May

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Java Interview Questions and Answers

1 of 1 24/05/ :23 AM

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

C++ INTERVIEW QUESTIONS

CS11 Java. Fall Lecture 7

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Files and input/output streams

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Chapter 8 Implementing FSP Models in Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Programming Languages CIS 443

Concurrent programming in Java

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Assignment 4 Solutions

Software Development in Java

Hadoop WordCount Explained! IT332 Distributed Systems

AP Computer Science File Input with Scanner

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

ECE 122. Engineering Problem Solving with Java

Lecture 7: Class design for security

Working with Java Collections

Data Structures and Algorithms

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Performance Improvement In Java Application

Getting to know Apache Hadoop

Iteration CHAPTER 6. Topic Summary

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Object Oriented Software Design

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Hadoop + Clojure. Hadoop World NYC Friday, October 2, Stuart Sierra, AltLaw.org

core 2 Basic Java Syntax

Table of Contents. Java CGI HOWTO

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

7.1 Our Current Model

Threads 1. When writing games you need to do more than one thing at once.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Course Intro Instructor Intro Java Intro, Continued

Stack Allocation. Run-Time Data Structures. Static Structures

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Building a Multi-Threaded Web Server

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Transcription:

Answer Key 1. General Understanding (10 points) (a) What is the difference between a List and a Set? (b) What is a checked exception? (c) What is the type of x after Collection x = new HashSet();? (d) What is the difference between an InputStream and a Reader? (e) Describe one (any) purpose of design patterns? (a) A Set is an unordered collection of objects. A List is an ordered collection of objects, where the objects are indexed subsequentially. (b) Every Throwable object which is neither an Error nor a RuntimeException is a checked exception. (c) Collection (d) InputStream is a byte stream, whereas Reader is a character stream. (e) One main purpose of design patterns is the reuse of designs. 2. Interface Stack (10 points) A Stack is a data structure where elements are added and removed at the same side, namely at the top. This is like a stack of boxes where you can only take away the topmost box, the one which is added at latest. Adding an element (necessarily at the top) is performed by the operation push. Removing an element (which necessarily was the topmost element then) is performed by the operation pop. One can always ask for the topmost element, with an operation called top. A stack is sometimes called Last-In-First-Out (FIFO) data structure. Here is the interface for a stack of characters: public interface Stack { / place c on top of this stack / public void push ( char c ) ; / remove the topmost entry of this stack ; throw a RuntimeException with detail message Tried to pop empty stack!, if the stack is empty / public void pop ( ) ; / return the topmost entry of this stack ; throw a RuntimeException with detail message Tried to get top of empty stack!, if the stack is empty / 1

public char top ( ) ; / return the current number of entries in this stack / public int size ( ) ; Your task is to write a class MyStack that implements the interface Stack. In MyStack, make use of the collections framework. (Hint: For how to construct a RuntimeException object with the specified detail message, see the appended javadoc pages. If you want to use LinkedList for your solution, then also see the appended javadoc pages.) import java. util. ; / Use LinkedList top of stack is first element of list / public class MyStack implements Stack { private LinkedList stack ; public MyStack ( ) { stack = new LinkedList ( ) ; public void push ( char c ) { stack. addfirst ( new Character ( c ) ) ; public void pop ( ) { if ( size ( ) > 0 ) stack. removefirst ( ) ; else throw new RuntimeException ( Tried to pop empty stack! ) ; public char top ( ) { if ( size ( ) > 0 ) return ( ( Character ) stack. getfirst ( ) ). charvalue ( ) ; else throw new RuntimeException ( Tried to get top of empty stack! ) ; public int size ( ) { 2

return stack. size ( ) ; 3. Input (10 points) Write a program CountPairs.java, which counts in a given input text file the number of characters which immediately follow an identical character. For example, consider a text file file.txt, containing just the following two lines: jw3xxv44js snnnms8@@lvdu Calling java CountPairs file.txt has the output: file.txt contains 4 characters immediately following an identical character In this example, the 4 counted characters are the second 4, the second and third n and the second @. Note that x is not the same as X, and that the second s immediately follows a newline character, not the first s. import java. io. ; class CountPairs { public static void main ( String [ ] args ) throws IOException { FileReader input = new FileReader ( args [ 0 ] ) ; char previous = ( char ) input. read ( ) ; char current ; int in ; int counter = 0 ; while ( ( in = input. read ( ) )! = 1 ) { current = ( char ) in ; if ( current == previous ) { counter++; previous = current ; System. out. println ( args [ 0 ] + contains + counter + characters immediately following + an identical character ) ; 4. Collections and Output (15 points) Consider the class Person: 3

public class Person { private String personnumber ; private String name ; // The argument persnum of the constructor is // assumed to be a String containing 6 digits, // followed by a, followed by 4 digits, // like the String 771224 8743. public Person ( String persnum, String aname ) { personnumber = persnum ; name = aname ; public String getpersonnumber ( ) { return personnumber ; public String getname ( ) { return name ; Suppose we have a database which contains several Sets of such Person objects. These Sets are not sorted. From time to time, we need to print such a set of Persons to a text file, in such a way that the persons appear sorted after their age, starting with the oldest. Each name is followed by the according person number. An example output file might look like: Petra Setterberg 670520-8746 Anna Lundborg 671118-9223 Lennart Augustsson 690113-2342 Anders Magnusson 710514-4271 Per Blomqvist 710529-8382 For printing out such an sorted listening of an unsorted set, we provide a helper class PrintSortedPersons, which contains nothing but a static method: public static void printsortedpersons(set s, String outputfile) printsortedpersons should print out the elements of s to the file outputfile, in a sorted way. (We assume that, whenever printsortedpersons is called with a certain Set s, then s contains only Person objects.) Your task is to implement the method printsortedpersons. (You may assume that all persons considered are born between 1900 and 1999.) 4

Hints: Looking at the above example output, you may realize that the order of person numbers reflects the standard ordering of Strings. For instance, "670520-8746" is a smaller String than "671118-9223", because the character 0 is smaller than the character 1, and both are the first characters which are different in both Strings. This means: The older a person is, the smaller is the person number (as a String). As the Persons in s are not sorted, the method has to sort them before printing them to outputfile. The suggestion is not to sort these objects directly, but to split them up into keys and values, and store this key-value pairs into a SortedMap, particularly a TreeMap. Printing out then means to iterate over the SortedMap and print values and keys. Adding a persnum/name pair to a TreeMap tmap could be done by: tmap.put( persnum, name ); where tmap is a reference to a sorted map object. Thereby, the person number strings are used as keys, while the names are used as values. Sorting is done automatically by the put-method, using the standard (alphabetical) order over String. (So you don t have to implement any order yourself.) The effect of the sorting becomes visible, when we iterate over the result of tmap.entryset();, as the iterator respects the ordering of the keys automatically. For how to iterate over an entry set, see slides of lecture 10, Map by Example. To write to a file, e.g. named text.txt, use a PrintWriter, like: PrintWriter out = new PrintWriter(new FileWriter("text.txt"));... out.println( somestring ); import java. io. ; import java. util. ; public class PrintSortedPersons { // The parameter s is assumed to contain only Person objects. public static void printsortedpersons ( Set s, String outputfile ) throws IOException { SortedMap smap = new TreeMap ( ) ; // sort s into smap : Iterator it1 = s. iterator ( ) ; while ( it1. hasnext ( ) ) { // ausprobieren ohne casten : Person p = ( Person ) it1. next ( ) ; smap. put ( p. getpersonnumber ( ), p. getname ( ) ) ; //print out smap, by iterating through all entries PrintWriter out = new PrintWriter ( new FileWriter ( outputfile ) ) ; Set entries = smap. entryset ( ) ; 5

Iterator it2 = entries. iterator ( ) ; while ( it2. hasnext ( ) ) { Map. Entry entry = ( Map. Entry ) it2. next ( ) ; String keystring = ( String ) entry. getkey ( ) ; String valuestring = ( String ) entry. getvalue ( ) ; out. println ( valuestring ) ; out. println ( keystring ) ; out. close ( ) ; 5. Threads (15 points) Consider the thread class MyThread: class MyThread extends Thread { private int whattoadd ; private int howoften ; static int shared = 0 ; // shared by all MyThread objects MyThread ( int toadd, int often ) { whattoadd = toadd ; howoften = often ; public void run ( ) { int temp = 0 ; for ( int i = 0 ; i < howoften ; i ++ ) { temp = shared + whattoadd ; shared = temp ; Any such thread adds howoften times the number whattoadd to the number shared. (Note that whattoadd can be negative.) shared is a shared field of all instances of MyThread, not because of its name, but because it is static. (a) (6 points) Write a class IncrAndDecr, such that the main method starts two threads. The first thread adds one million times +1 to shared, the second thread adds one million times -1 to shared. After starting both threads, the main method waits until both threads stop running, and then prints out the value of shared. Hint: Waiting until a thread t stops running is done by the statement: t.join(); See also join in the appended jacadoc pages. 6

(b) (2 points) java IncrAndDecrOneMillion will most certainly not output 0. Why? (c) (5 points) Modify MyThread such that java IncrAndDecrOneMillion will certainly output 0. The modification should still allow the threads to truly run in parallel, which means that the execution can switch back and forth between adding +1 and adding -1. Hint: You may use synchronized statements rather than a synchronized method for this. See also lecture 6 or Jia section 8.2.1. Note that the synchronized block can contain more than one statement. To use the same object lock for both threads, you may synchronize on a static object lockobj, which you can define by static Object lockobj = new Object();. (d) (2 points) Modify the class IncrAndDecrOneMillion such that the number of iterations both threads perform is given as a command line argument. (a) class IncrAndDecrOneMillion { public static void main ( String [ ] args ) { int iterations = Integer. parseint ( args [ 0 ] ) ; MyThread t1 = new MyThread ( + 1, iterations ) ; MyThread t2 = new MyThread ( 1, iterations ) ; t1. start ( ) ; t2. start ( ) ; // wait for both threads to complete before printing result try { t1. join ( ) ; t2. join ( ) ; catch ( InterruptedException e ) { System. out. println ( MyThread. shared ) ; (b) As nothing is synchronized here, two for-iterations of both threads could interfere. It might e.g. happen that the result of shared + +1 is not assigned to shared before shared + -1 is computed and assigned to shared. (c) class MyThread extends Thread { private int whattoadd ; private int howoften ; static int shared = 0 ; // shared by all MyThread static Object lockobj = new Object ( ) ; objects MyThread ( int toadd, int often ) { 7

whattoadd = toadd ; howoften = often ; (d) public void run ( ) { int temp = 0 ; for ( int i = 0 ; i < howoften ; i ++ ) { synchronized ( lockobj ) { temp = shared + whattoadd ; shared = temp ; class IncrAndDecrOneMillion { public static void main ( String [ ] args ) { int iterations = Integer. parseint ( args [ 0 ] ) ; MyThread t1 = new MyThread ( + 1, iterations ) ; MyThread t2 = new MyThread ( 1, iterations ) ;... 8