Answer Key. 1. General Understanding (10 points) think before you decide.
|
|
- Clemence Lyons
- 6 years ago
- Views:
Transcription
1 Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset implement java.util.collection? (b) (2 points) Does the initializer Object o = new Integer(5); compile? (Assume o was not declared before?) (c) (2 points) Is branch coverage testing a white box technique? (d) (2 points) Does the expression (new Integer(11) == new Integer(11)) evaluate to true? (e) (2 points) Is String a reference type? Answer: (The explenations given here were not required.) (a) (2 points) no. (An interface never implements anything. It can only extend another interface.) (b) (2 points) yes. (The type Integer is compatible with the type Object.) (c) (2 points) yes. (To know the different branches of program execution, we have to know the implementation.) (d) (2 points) no. (Each new operator creates a different object and returns a reference to it. Therefore, == here compares two different references.) (e) (2 points) yes. (Strings are objects.) 2. Interfaces (10 points) 1
2 (a) (2 points) Please remind yourself of the Iterator interface, which is also documented in the enclosed API descriptions. Implement a small helper class IteratorPrinter, only providing a static method printelements(iterator it), which prints all elements you can get out of the iterator it to System.out (one element per line). (b) (6 points) The Iterator interface is meant to be used in combination with Collection types. Nevertheless, the task here is to write an implementation of this interface not for collections, but for arrays, more precisely for arrays the element type of which is a reference type (not a primitive type). Write a class ObjectArrayIterator implementing the Iterator interface ( implements Iterator ). Each ObjectArrayIterator object is bound to an underlying array. Using the next() method of an ObjectArrayIterator object, one can iterate over the elements of the underlying array. You have to carefully follow the contracts described in the MethodDetail section of the enclosed API description. This includes implementing what is required by the respective Throws: sections in the API description. The class should not support the remove() method. That means: you still have to implement remove(), but only in a certain way. (See the according Throws: section.) Beside the Iterator methods, you must implement a constructor public ObjectArrayIterator(Object[] a) which creates an ObjectArrayIterator for the array. (Hint: Store the array a in a field, and provide an additional nextelement field. In this exam, don t worry about independent iterations.) (c) (2 points) Now the ObjectArrayIterator class is to be used, in a very small (and silly) example. Implement a small class PrintArgs, the main method of which prints out all command line arguments, but only by calling the printelements method of the class IteratorPrinter. (So don t use a for or while in this class.) Hints: All arrays of type Type[], where Type is a reference type, are compatible with the array type Object[]. For example, you can pass an array of type String[] to a method with argument type Object[]. To throw an exception of type SomeException, use the following statement: throw new SomeException(); Both, the NoSuchElementException and the UnsupportedOperationException, are unchecked exception types, as they extend RuntimeException. Therefore, exceptions of both types neither have to be caught (using try catch) nor have to be declared in a method s head. Answer: (a) (2 points) 2
3 import java. util. ; public class IteratorPrinter { public static void printelements ( Iterator i ) { while ( i. hasnext ( ) ) System. out. println ( i. next ( ) ) ; (b) (6 points) import java. util. ; public class ObjectArrayIterator implements Iterator { (c) (2 points) private Object [ ] a ; private int nextelement ; public ObjectArrayIterator ( Object [ ] a ) { this. a = a ; nextelement = 0 ; public boolean hasnext ( ) { return nextelement < a. length ; public Object next ( ) { if (! hasnext ( ) ) throw new NoSuchElementException ( ) ; nextelement = nextelement + 1 ; return a [ nextelement 1 ] ; public void remove ( ) { throw new UnsupportedOperationException ( ) ; import java. util. ; public class PrintArgs { public static void main ( String [ ] args ) { Iterator it = new ObjectArrayIterator ( args ) ; IteratorPrinter. printelements ( it ) ; 3
4 3. Input/Output (10 points) Write a program LineAndColumn.java which seeks for the first occurrence of a particular character in a text file and prints out the line number and position within the line of that occurrence. The program in it s normal use takes two command line arguments, the first being the name of the text file, the second being the character to be searched. The program should complain if it gets to the wrong number of arguments, or if the second argument is a String longer than one character. Also, it should tell when there appears an input/output problem. (The program is assumed to be executed in the directory where the input file resides.) For example, consider a text file test.txt, containing just the following two lines: jw3xxv44js snnnms8@@lvdu Moreover, assume there is no file xxx.txt in the current directory. Here are example outputs: java LineAndColumn test.txt j prints out: the character j appears first in line 1 at position 0 java LineAndColumn test.txt m prints out: the character m appears first in line 2 at position 4 java LineAndColumn test.txt a prints out: the character a does not appear in the file java LineAndColumn test.txt prints out: wrong number of arguments java LineAndColumn test.txt bb prints out: second argument must be a single character java LineAndColumn xxx.txt j prints out: there appeared an input/output problem (It doesn t matter if your program considers the first line being line number 1 or line number 0. The same holds for the positions within the lines.) Hints: One can exit a void method at any point in the method body by using the statement return;. But use this only if you think it simplifies your code. Consider using a LineNumberReader. Consider the methods charat(i) and indexof(c) of the String class. (See Jia.) Answer: 4
5 import java. io. ; public class LineAndColumn { public static void main ( String [ ] args ) { if ( args. length! = 2 ) { System. out. println ( wrong number of arguments ) ; return ; if ( args [ 1 ]. length ( )! = 1 ) { System. out. println ( second argument must be + a single character ) ; return ; String file = args [ 0 ] ; char tofind = args [ 1 ]. charat ( 0 ) ; String line ; int indexinline ; boolean found = false ; try { LineNumberReader input = new LineNumberReader ( new FileReader ( file ) ) ; while ( ( ( line = input. readline ( ) )! = null ) &&! found ) { indexinline = line. indexof ( tofind ) ; if ( indexinline!= 1) { found = true ; System. out. println ( the character + tofind + appears first in line + input. getlinenumber () + at position + indexinline ) ; if (! found ) System. out. println ( the character + tofind + does not appear in the file ) ; input. close ( ) ; catch ( IOException e ) { System. out. println ( there appeared + an input/output problem ) ; 5
6 4. I/O and Collections (15 points) We consider a scenario where simple price lists are available in a text format. As an example, here is the content of the file pricelist.txt: butter 20 bread 18 jam 25 cola 15 milk 9 salami 30 (For simplicity, all prices are full SEK, so Öre are not considered.) You can assume all price lists having such a form. Each line starts with a word, followed by an arbitrary number of white spaces ( ), followed by digits representing a number. White spaces appear only between the words and the numbers. No TABs are used. Another form of text files are orders, such as the following file order.txt butter jam bread milk beer You can assume all orders having such a form. Each line contains one word, and the file does neither contain white spaces nor TABs. Moreover, for simplicity we assume that no word appears twice in an order. Write a java program which takes such a price list and an order and prints an according receipt ( kvitto ) to System.out. On our example files, it behaves like this: calling: java Receipt pricelist.txt order.txt results in the following output: bread for 18 jam for 25 butter for 2 0 beer not availabe milk for 9 = = = = = = = = total : 7 2 (The order in which items are listed in the output is not significant. Your program is allowed to list them in an arbitrary order.) To simplify your task, the program does not have to be robust this time. This means, you can receive full points even if your program does not react properly to unexpected situations, like a wrong number of arguments, non-existing files, or files having a different format than explained above. Nevertheless, the program has to compile. Therefore, you have to do as much exception handling as the compiler requires. 6
7 The program is not allowed to read through the input files again and again, whenever the price of an item has to be looked up. Instead, store items and prices in a suitable data structure. Hints: Consider using BufferedReader and StringTokenizer. The method readline() of the class BufferedReader returns a String, either containing the contents of the line, or null if the end of the stream has been reached. To iterate over a Collection (for example a Set), you can create an iterator by calling the iterator() method. The get(k) method of Map returns the value to which this map maps the specified key. It returns null if the Map contains no mapping for this key. The return type of get(k) is Object. The argument type of Integer.parseInt(str) is String. Answer: import java. io. ; import java. util. ; public class Receipt { public static void main ( String [ ] args ) throws IOException { String pricefile = args [ 0 ] ; String orderfile = args [ 1 ] ; BufferedReader pricereader = new BufferedReader ( new FileReader ( pricefile ) ) ; BufferedReader orderreader = new BufferedReader ( new FileReader ( orderfile ) ) ; // read the prices into the price map Map pricemap = new HashMap ( ) ; String line ; while ( ( line = pricereader. readline ( ) )! = null ) { StringTokenizer st = new StringTokenizer ( line ) ; pricemap. put ( st. nexttoken ( ), st. nexttoken ( ) ) ; pricereader. close ( ) ; // read the orders into the set of orders 7
8 Set orders = new HashSet ( ) ; while ( ( line = orderreader. readline ( ) )! = null ) orders. add ( line ) ; orderreader. close ( ) ; // iterate over the orders and sum up the prices int total = 0 ; Iterator it = orders. iterator ( ) ; while ( it. hasnext ( ) ) { Object item = it. next ( ) ; Object price = pricemap. get ( item ) ; if ( price == null ) System. out. println ( item + not available ) ; else { System. out. println ( item + for + price ) ; total = total + Integer. parseint ( ( String ) price ) ; System. out. println ( = = = = = = = = ) ; System. out. println ( total : + total ) ; 5. Threads (15 points) This assignment talks about print jobs, being produced by clients, collected in a print queue, and being printed by a print server. We represent the information to be printed by a (potentially very long) String. Consider the class PrintJob, wrapping stings which are going to be printed: class PrintJob { public String whattoprint ; public PrintJob followingjob ; public PrintJob ( String str ) { whattoprint = str ; followingjob = null ; As PrintJob objects have a reference to another PrintJob object, they can be chained up to a queue which is to be served by a print server. We now present an according class PrintQueue. This class allows to add strings, and to take them out again. It is 8
9 PrintQueue itself which does the wrapping and unwrapping of strings into (and from) print jobs. Therefore, it is appropriate to make PrintJob visible only in PrintQueue. Nobody else might use the class. This is achieved by moving the class PrintJob into the class PrintQueue, as a private static inner class. (private static inner classes act like normal classes, beside that they are visible only within code of their outer class.) Better ignore the critical point comments in the first reading. public class PrintQueue { private static class PrintJob { public String whattoprint ; public PrintJob followingjob ; public PrintJob ( String str ) { whattoprint = str ; followingjob = null ; private PrintJob firsttoprint = null ; private PrintJob lasttoprint = null ; private int length = 0 ; public void addtoqueue ( String str ) { PrintJob pjob = new PrintJob ( str ) ; if ( length == 0) firsttoprint = pjob ; else lasttoprint. followingjob = pjob ; lasttoprint = pjob ; //( critical point here?) length = length + 1 ; public String takefromqueue ( ) { while ( length == 0) { // waiting until no longer empty PrintJob forreturning = firsttoprint ; firsttoprint = firsttoprint. followingjob ; //( critical point here?) length = length 1; 9
10 if ( length == 0) lasttoprint = null ; return forreturning. whattoprint ; (a) (2 points) Describe briefly how addtoqueue and takefromqueue work. (b) (4 points) Now consider the PrintServer class: public class PrintServer extends Thread { private PrintQueue queue ; public PrintServer ( PrintQueue pq ) { queue = pq ; public void run ( ) { while ( true ) { String toprint = queue. takefromqueue ( ) ; // do the real printing... A PrintServer object stores a reference to its corresponding PrintQueue object. PrintServer extends Thread, because it is executed in parallel to clients. Implement a class Client, also extending Thread. Different clients run in parallel to each other and to the server. For simplicity, your Client should only add the same String again and again to the same PrintQueue. Both, the String and the PrintQueue, are given as arguments to the constructor. For not creating too many print jobs, execute Thread.sleep(100); after each adding. (sleep() is declared to possibly throw an InterruptedException, which is a checked exception! The same holds for wait(), see below.) (c) (3 points) Implement a tester class PrintTest, the main method of which creates a print queue, and starts three clients (with different strings to print) and one server. All clients and the server refer to the same print queue. (d) (3 points) With the given implementation, a PrintQueue can get corrupted, in at least two different ways. Explain how. What can be done to prevent this? Indicate clearly the necessary changes to the code. Hint: Look at the critical point comments now. (e) (3 points) The current implementation of takefromqueue potentially spends time in a exe- 10
11 cuting a waiting loop, if the queue is empty. This prevents other threads from executing immediately. In combination with synchronized, it can even lead to a deadlock. What should you do instead? Indicate clearly the necessary changes to the code. Answer: (a) (2 points) addtoqueue: takes a string as an argument it wraps the string into a PrintJob if there are no jobs in the print queue, this job becomes the front and end of the PrintQueue else this job is appended at the end of the PrintQueue the length is incremented takefromqueue: waits until jobs are in the queue remembers the first PrintJob, which is then discarded from the PrintQueue the length is decremented if the discarded job was the only one, then there is no last job left unwraps the string from the remembered job and returns it (b) (4 points) public class Client extends Thread { private PrintQueue queue ; private String toprintrepeatedly ; public Client ( PrintQueue pq, String str ) { queue = pq ; toprintrepeatedly = str ; public void run ( ) { while ( true ) { queue. addtoqueue ( toprintrepeatedly ) ; try { Thread. sleep ( ) ; catch ( InterruptedException e ) { 11
12 (c) (3 points) public class PrintTest { public static void main ( String [ ] args ) { PrintQueue pqueue = new PrintQueue ( ) ; Client cl1 = new Client ( pqueue, Sent from client 1. ) ; Client cl2 = new Client ( pqueue, Sent from client 2. ) ; Client cl3 = new Client ( pqueue, Sent from client 3. ) ; PrintServer server = new PrintServer ( pqueue ) ; cl1. start ( ) ; cl2. start ( ) ; cl3. start ( ) ; server. start ( ) ; (d) (3 points) The addtoqueue could be interrupted right after setting lasttoprint to the new job, without having increased the length. The queue then might seem to be empty but is not, which might cause this job being overwritten by another job. The takefromqueue could be interrupted right after discarding the so far first job, without having decreased the length. The queue then might seem to contain one more job but actually is empty, causing a NullPointerException if another server uses the same queue to take out jobs. To prevent this, both methods should be synchronized. See the code in the answer to (e). (e) (3 points) public synchronized void addtoqueue ( String str ) { System. out. println ( adding : + str ) ; System. out. println ( ) ; PrintJob pjob = new PrintJob ( str ) ; if ( length == 0) firsttoprint = pjob ; else lasttoprint. followingjob = pjob ; lasttoprint = pjob ; length = length + 1 ; notifyall ( ) ; 12
13 public synchronized String takefromqueue ( ) { while ( length == 0) try { wait ( ) ; catch ( InterruptedException e ) { PrintJob forreturning = firsttoprint ;
CS 61B Discussion 5: Inheritance II Fall 2014
CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation
More informationChapter 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 informationCS 251 Intermediate Programming Exceptions
CS 251 Intermediate Programming Exceptions Brooke Chenoweth University of New Mexico Fall 2018 Expecting the Unexpected Most of the time our programs behave well, however sometimes unexpected things happen.
More informationCSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?
CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7 Question 1. (2 points) What is the difference between a stream and a file? A stream is an abstraction representing the flow of data from one place to
More informationCourse Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski
CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule
More informationLab 5: Java IO 12:00 PM, Feb 21, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering
More informationJava Input/Output. 11 April 2013 OSU CSE 1
Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationProblem 1: Building and testing your own linked indexed list
CSCI 200 Lab 8 Implementing a Linked Indexed List In this lab, you will be constructing a linked indexed list. You ll then use your list to build and test a new linked queue implementation. Objectives:
More informationInput, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003
Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data
More informationQuestion 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.
CSE 143 Sp04 Midterm 2 Page 1 of 10 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference during the exam
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationCSE 143 Au04 Midterm 2 Sample Solution Page 1 of 7
CSE 143 Au04 Midterm 2 Sample Solution Page 1 of 7 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference
More informationTopics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)
Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types
More informationQuestion 1. (2 points) What is the difference between a stream and a file?
CSE 143 Sp03 Midterm 2 Page 1 of 7 Question 1. (2 points) What is the difference between a stream and a file? Question 2. (2 points) Suppose we are writing an online dictionary application. Given a word
More informationIntroduction Unit 4: Input, output and exceptions
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.
More information40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the
Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No
More informationException-Handling Overview
م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the
More informationCore Java Interview Questions and Answers.
Core Java Interview Questions and Answers. Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a default behavior. An Interface
More informationCS106A Final Exam Review Session. Saturday Dec. 10, 2016 Nick Troccoli
CS106A Final Exam Review Session Saturday Dec. 10, 2016 Nick Troccoli 1 Today s Topic List Primitives, Objects, and Heap/Stack Graphics + Animation Event-Driven Programs Strings + chars Classes + Interfaces
More informationThe University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003
The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled
More informationTo Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));
A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems
More informationRecreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));
A student adds a JUnit test: Recreation @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems to
More informationCS-152: Software Testing
CS-152: Software Testing Neal Holtschulte July 2, 2013 Software Testing Outline Terminology Assertions and when to use them Try-catch and when to use them What are Exceptions Further resources Practice
More informationExceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,
More informationProgramming Assignment Comma Separated Values Reader Page 1
Programming Assignment Comma Separated Values Reader Page 1 Assignment What to Submit 1. Write a CSVReader that can read a file or URL that contains data in CSV format. CSVReader provides an Iterator for
More informationCSCI-140 Midterm Review October 10, 2015 Presented by the RIT Computer Science Community
CSCI-140 Midterm Review October 10, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. In each of the following situations, would it be better to use array-backed storage or
More informationCS 351 Design of Large Programs Threads and Concurrency
CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level
More informationArray. Prepared By - Rifat Shahriyar
Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions
COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what
More informationExceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages
References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/
More informationCS 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 informationCS 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 informationPrinciples of Computer Science I
Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested
More informationA Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1
A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);
More informationLecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and
More informationPages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.
CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines
More informationFile I/O Array Basics For-each loop
File I/O Array Basics For-each loop 178 Recap Use the Java API to look-up classes/method details: Math, Character, String, StringBuffer, Random, etc. The Random class gives us several ways to generate
More informationExercise Session Week 8
Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle
Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the
More informationCS 251 Intermediate Programming Java I/O Streams
CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package
More informationData Types and the while Statement
Session 2 Student Name Other Identification Data Types and the while Statement In this laboratory you will: 1. Learn about three of the primitive data types in Java, int, double, char. 2. Learn about the
More information5/23/2015. Core Java Syllabus. VikRam ShaRma
5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5
More informationPrelim 1, Solution. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer
Prelim 1, Solution CS 2110, 13 March 2018, 7:30 PM 1 2 3 4 5 6 Total Question Name Short answer Exception handling Recursion OO Loop invariants Max 1 30 11 14 30 14 100 Score Grader The exam is closed
More informationWeek 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O
Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file
More informationWriting your own Exceptions. How to extend Exception
Writing your own Exceptions How to extend Exception When would you write your own exception class? When to write your own custom exception is a matter for discussion in your project design team. There
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More information1007 Imperative Programming Part II
Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be
More informationJava 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 informationCS61B Lecture #12. Today: Various odds and ends in support of abstraction.
CS61B Lecture #12 Today: Various odds and ends in support of abstraction. Readings: At this point, we have looked at Chapters 1 9 of Head First Java. Today s lecture is about Chapters 9 and 11. For Friday,
More informationExercises and Labs. Part I. Exercises
Exercises and Labs Part I Exercises 7 Exercises and Labs Exercise 1 Semaphores Answer the questions below: 1. Sometimes, multiple threads in a program write to the same file concurrently. One example
More informationExercise Session Week 8
Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones
More informationLab 2: File Input and Output
Lab 2: File Input and Output This lab introduces how to handle files as both input and output. We re coming back to Tracery (which you implemented in Lab 1) with this assignment but instead of always reading
More informationExceptions. Examples of code which shows the syntax and all that
Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationCOMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others
COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object
More informationArrayList. 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 informationHST 952. Computing for Biomedical Scientists Lecture 8
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java
More informationExceptions. CSE 142, Summer 2002 Computer Programming 1.
Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»
More informationExceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.
Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented
More informationDeclarations and Access Control SCJP tips
Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for
More informationChecked and Unchecked Exceptions in Java
Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by
More informationCmpSci 187: Programming with Data Structures Spring 2015
CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more
More informationExceptions and Error Handling
Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More informationLearning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference
CSI1102: Introduction to Software Design Chapter 5: Enhancing Classes Learning objectives: Enhancing Classes Understand what the following entails Different object references and aliases Passing objects
More informationProject #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.
Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationSri Vidya College of Engineering & Technology Question Bank
1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More information1B1b Classes in Java Part I
1B1b Classes in Java Part I Agenda Defining simple classes. Instance variables and methods. Objects. Object references. 1 2 Reading You should be reading: Part I chapters 6,9,10 And browsing: Part IV chapter
More informationExceptions in Java
Exceptions in Java 3-10-2005 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment?
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More information17. Handling Runtime Problems
Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationCSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.
Name The exam is closed book, closed notes, and closed electronics. Please wait to turn the page until everyone is told to begin. Score / 54 1. / 12 2. / 12 3. / 10 4. / 10 5. / 10 Bonus: 1. / 6 2. / 4
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationICOM 4015-Advanced Programming. Spring Instructor: Dr. Amir H. Chinaei. TAs: Hector Franqui, Jose Garcia, and Antonio Tapia. Reference: Big Java
ICOM 4015-Advanced Programming Spring 2014 Instructor: Dr. Amir H. Chinaei TAs: Hector Franqui, Jose Garcia, and Antonio Tapia Reference: Big Java By Hortsmann, Ed 4 Lab 7 Continuation of HTTP and Introduction
More information1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 19, 2004
1.00 Introduction to Computers and Engineering Problem Solving Final Examination - May 19, 2004 Name: E-mail Address: TA: Section: You have 3 hours to complete this exam. For coding questions, you do not
More informationWhat is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,
More informationCS 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 informationActive Learning: Streams
Lecture 29 Active Learning: Streams The Logger Application 2 1 Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text
More informationJava Exceptions Java, winter semester
Java Exceptions 1 Exceptions errors reporting and handling an exception represents an error state of a program exception = an instance of java.lang.throwable two subclasses java.lang.error and java.lang.exception
More informationCSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277
CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) 562-5800 x 6277 elsaddik @ site.uottawa.ca abed @ mcrlab.uottawa.ca http://www.site.uottawa.ca/~elsaddik/
More informationExceptions and Design
Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview Exceptions
More informationLecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8
Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How
More informationStreams and File I/O
Chapter 9 Streams and File I/O Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationChapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationWhat is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked
What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource
More informationCSCI 200 Lab 3 Using and implementing sets
CSCI 200 Lab 3 Using and implementing sets In this lab, you will write a program that manages a set of workers, using the Worker hierarchy you developed in Lab 2. You will also implement your own version
More information1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004
1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Section: You have 180 minutes to complete this exam. For coding questions, you do
More informationCSCI-142 Exam 2 Review November 2, 2018 Presented by the RIT Computer Science Community
CSCI-142 Exam 2 Review November 2, 2018 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Suppose we are talking about the depth-first search (DFS) algorithm. Nodes are added to
More informationException Handling. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer
More informationImplementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC
Implementing a List in Java CSC 143 Java List Implementation Using Arrays Updated with Java 5.0 Generics Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked
More informationImplementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.
Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete
More informationMore on Objects in JAVA TM
More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a
More information