15-214: Principles of Software Construction 8 th March 2012



Similar documents
Exceptions and their interpretation

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Sample CSE8A midterm Multiple Choice (circle one)

Part I. Multiple Choice Questions (2 points each):

Lecture J - Exceptions

Java Programming Language

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

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

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

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CS 111 Classes I 1. Software Organization View to this point:

AP Computer Science Java Subset

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

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

Konzepte objektorientierter Programmierung

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Iteration CHAPTER 6. Topic Summary

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CS170 Lab 11 Abstract Data Types & Objects

C++FA 5.1 PRACTICE MID-TERM EXAM

Object-Oriented Programming in Java

Inheritance, overloading and overriding

The Needle Programming Language

Chapter 1 Java Program Design and Development

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

PostgreSQL Functions By Example

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Unit Testing. and. JUnit

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Programming Languages CIS 443

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

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

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

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

Moving from CS 61A Scheme to CS 61B Java

The following program is aiming to extract from a simple text file an analysis of the content such as:

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Java CPD (I) Frans Coenen Department of Computer Science

Software Construction

Computer Programming I

Software Engineering Techniques

JUnit. Introduction to Unit Testing in Java

CS 106 Introduction to Computer Science I

Introduction to Java. CS 3: Computer Programming in Java

Introduction: Abstract Data Types and Java Review

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introducing Variance into the Java Programming Language DRAFT

Basic Programming and PC Skills: Basic Programming and PC Skills:

History OOP languages Year Language 1967 Simula Smalltalk

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

Java Interview Questions and Answers

Java Classes. GEEN163 Introduction to Computer Programming

Java from a C perspective. Plan

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

CS193j, Stanford Handout #10 OOP 3

Evaluation of AgitarOne

Arrays in Java. Working with Arrays

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING. The Design-Code-Debug Cycle. Divide and Conquer! Documentation is Code

Unit 6. Loop statements

CS 121 Intro to Programming:Java - Lecture 11 Announcements

C++ INTERVIEW QUESTIONS

Crash Course in Java

Decision-making Computer Science Lesson to Prepare for UIL Computer Science Contest

Chapter 2 Introduction to Java programming

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

Realizing Enterprise Integration Patterns in WebSphere

CS506 Web Design and Development Solved Online Quiz No. 01

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Programmation 2. Introduction à la programmation Java

ECE 122. Engineering Problem Solving with Java

Unit Testing & JUnit

Design Patterns. Advanced Software Paradigms (A. Bellaachia) 1

Curriculum Map. Discipline: Computer Science Course: C++

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Part 1 Foundations of object orientation

Habanero Extreme Scale Software Research Project

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Course Intro Instructor Intro Java Intro, Continued

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java Basics: Data Types, Variables, and Loops

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Arrays. Introduction. Chapter 7

Statements and Control Flow

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

jmonitor: Java Runtime Event Specification and Monitoring Library

El Dorado Union High School District Educational Services

Continuous Integration Part 2

Transcription:

15-214 Midterm Exam Andrew ID: SOLUTIONS 1 / 13 15-214: Principles of Software Construction 8 th March 2012 Name: SOLUTIONS Recitation Section (or Time): Instructions: Make sure that your exam is not missing any sheets (it should contain 13 pages). Write your full name on this page and Andrew ID on the header of all. Write your answers in the space provided below the problem. If you make a mess, clearly indicate your final answer. The problems are of varying difficulty. The point value of each problem is indicated. Ideally you should take one minute per point. So pace yourself accordingly. This exam is CLOSED BOOK. You may not use a calculator, laptop or any other electronic or wireless device. Write concise and focused answers (long ramblings will hurt your grade). If anything is unclear, just make and state your (reasonable) assumptions. Make sure your handwriting is READABLE. You have 80 minutes to complete this Exam. Good luck! Question Points Score Java 15 Unit Testing 10 Method Dispatch 16 Design Patterns 16 Verification 22 TOTAL: 79 Keep in mind that there may be other, valid, solutions to a particular question.

15-214 Midterm Exam Andrew ID: SOLUTIONS 2 / 13 Java [15 points] Q1. [5 points] Fill in the blanks: a) Polymorphism is the feature that allows different implementations of the same interface to behave differently. b) Inheritance is the capability of a class to manifest the properties and methods of another class while adding its own functionality. c) Java permits a class to replace the implementation of a method that it has inherited. It is called Method Overriding. d) private keyword assigned to a class member to hide that member from all other classes. e) The main method is defined to be static because it is not a property of an instance but of the class. Q2. [2 points] Print out the result: String a = new String( 4 ); String b = new String( 4 ); System.out.print( a.equals(b) ); true - System.out.print( a == b ); false - Q3. [4 points] Find two things that cause this code not to compile? Mark the errors. public final abstract class Animal{ public void speak(){ System.out.println("My name is " + getname() + "."); abstract public String getname(); public class Dog extends Animal{ public String getname(){ return "Tommy"; public static void main(string[] args){ Animal d = new Dog(); d.speak(); d.getname(); Q4. [4 points] Given below is a portion of the inheritance hierarchy of the various errors and exceptions. Please use this to answer the following questions. class java.lang.throwable (implements java.io.serializable) class java.lang.error class java.lang.assertionerror class java.lang.linkageerror class java.lang.classcircularityerror class java.lang.classformaterror class java.lang.unsupportedclassversionerror class java.lang.exceptionininitializererror class java.lang.incompatibleclasschangeerror class java.lang.abstractmethoderror class java.lang.illegalaccesserror class java.lang.instantiationerror class java.lang.nosuchfielderror

15-214 Midterm Exam Andrew ID: SOLUTIONS 3 / 13 class java.lang.nosuchmethoderror class java.lang.noclassdeffounderror class java.lang.unsatisfiedlinkerror class java.lang.verifyerror class java.lang.threaddeath class java.lang.virtualmachineerror class java.lang.internalerror class java.lang.outofmemoryerror class java.lang.stackoverflowerror class java.lang.unknownerror class java.lang.exception class java.lang.classnotfoundexception class java.lang.clonenotsupportedexception class java.lang.illegalaccessexception class java.lang.instantiationexception class java.lang.interruptedexception class java.lang.nosuchfieldexception class java.lang.nosuchmethodexception class java.lang.runtimeexception class java.lang.arithmeticexception class java.lang.arraystoreexception class java.lang.classcastexception class java.lang.illegalargumentexception class java.lang.illegalthreadstateexception class java.lang.numberformatexception class java.lang.illegalmonitorstateexception class java.lang.illegalstateexception class java.lang.indexoutofboundsexception class java.lang.arrayindexoutofboundsexception class java.lang.stringindexoutofboundsexception class java.lang.negativearraysizeexception class java.lang.nullpointerexception class java.lang.securityexception class java.lang.unsupportedoperationexception a) What does the following program print? public static void main(){ try{ String s = ; Char b = s.charat(5); catch ( Exception e ){ System.out.println( caught an exception ); catch ( Error e ){ System.out.println( caught an error ); caught an exception b) What does the following program output? public static void main(){ try{ asserttrue(false); catch (Exception e){ System.out.println( caught an exception ); catch (Error e){ System.out.println( caught an error ); caught an error

15-214 Midterm Exam Andrew ID: SOLUTIONS 4 / 13 Unit Testing [10 points] You are to develop a set of unit test cases for the following code block. Note that the code below may contain some faults. The test cases you write should catch these faults and any others that might arise as the code evolves. public class AccumValue { private int value; public AccumValue(int init){ value = init; /** * Computes a new accumulation value from the values in vs up to limit * @returns true if value changed, false otherwise. */ public boolean calcaccum ( int limit, AccumValue[] vs ){ int[] array = new int[limit]; if( array.length < limit ) return false; buildarray(array,vs); int tmp=0; for( int s : array ) tmp += s; int old = value; value = tmp; return old!= value; protected void buildarray( int[] array, AccumValue[] vs ){ for( int i=0 ; i<array.length ; ++i ) array[i] = vs[i].getvalue(); public int getvalue(){ return value;

15-214 Midterm Exam Andrew ID: SOLUTIONS 5 / 13 Q1. [10 points] Fill in the blanks to produce several test cases that check the code shown above. If a test case should throw an exception you should write it as: @Test( expected = NameOfException.class ) where NameOfException is a reasonable exception that the code should throw for that situation. If the test case should not throw any exception then either cross out the blank box or leave it empty. public class AccumValueTester { @Test a public void testconstructor() { assertequals( 214, new AccumValue(214). getvalue() ); @Test ( expected = IllegalArgumentException.class ) a public void testargumentssanitycheck1() { new AccumValue(0).calcAccum( - 1, new AccumValue(0) ); @Test ( expected = IllegalArgumentException.class ) a public void testargumentssanitycheck2() { new AccumValue(0).calcAccum( 2, null ); @Test ( expected = IllegalArgumentException.class ) a public void testargumentssanitycheck3() { new AccumValue(0).calcAccum( 2, new AccumValue[]{ ); @Test a public void testcorrectresult() { AccumValue c = new AccumValue(0); AccumValue[] x = { new AccumValue(2), new AccumValue(3) ; asserttrue( c.caclaccum(1, x) ); assertequals( 2, c.getvalue() ); assertfalse( c.caclaccum(1, x) ); assertequals( 2, c.getvalue() ); asserttrue( c.caclaccum(2,x) ); assertequals( 5, c.getvalue() );

15-214 Midterm Exam Andrew ID: SOLUTIONS 6 / 13 Method Dispatch [16 Points] Consider the following code: package b; abstract class Bird { protected int a = 1; public abstract void identify(); protected void shout(){ System.out.println("Kaw- Kaw"); public void action(){ System.out.println("Fear me "+ this.a +" times"); public void flyaround(){ System.out.println("Wooooosh, I am a "); identify(); shout(); System.out.println("You should "); action(); protected int geta(){ return a; protected void addtoa(){ a++; package b; public class Penguin extends Bird{ private int a; public Penguin(){ a = 2; @Override public void identify() { System.out.println("Penguin #" + a + " reporting for duty!"); public void shout(){ System.out.println("Shouting is uncivilized..."); public void action(int times){ System.out.println("Swim "+ (times + geta()) +" times!"); public void flyaround(){ System.out.println("Sometimes I dream I can fly like this: "); super.flyaround(); package a; public class Program{ public static void act1(){ Bird b = new Bird(); b.flyaround();

15-214 Midterm Exam Andrew ID: SOLUTIONS 7 / 13 public static void act2(){ Bird b = new Penguin(); act3(b); public static void act3(penguin p){ Bird b = new Penguin(); b.shout(); public static void act4(){ Bird b = new Penguin(); b.action(15); public static void act5(){ Bird b = new Penguin(); b.flyaround(); public static void act6(){ Bird b = new Penguin(); b.identify(); public static void act7(){ Bird b = new Penguin(); b.addtoa(); ((Penguin)b).action(4); Q1. [16 points] For each of the following methods that refer to the code above, if there is a compilation error, explain what it is and how to fix it. If there is no compilation error in a particular act method, say what the method prints. a) Program.act1() Doesn t compile, cannot instantiate an abstract class. b) Program.act2() Doesn t compile, act3(penguin p) will not accept act3(bird b). c) Program.act3(new Pengin()) Doesn t compile shout() is protected and being accessed outside of package d) Program.act4() Doesn t compile, the method signature action(int i) is not present in the static

15-214 Midterm Exam Andrew ID: SOLUTIONS 8 / 13 type Bird. e) Program.act5() Some times I dream I can fly like this: Wooooosh, I am Penguin #2 reporting for duty! Shouting is uncivilized... You should Fear me 1 times f) Program.act6() Penguin #2 reporting for duty! g) Program.act7() Doesn t compile addtoa() is protected and being accessed outside of package.

15-214 Midterm Exam Andrew ID: SOLUTIONS 9 / 13 Design Patterns [16 points] public interface Dead { public Beef dead1(); public interface Beef { public void beef1(foo f); public void beef2(); public interface Foo { public void foo1(); public class Deadbeef implements Dead { private static Deadbeef feebdaed = new Deadbeef(); private Deadbeef(){ private static DeadBeef deadbeef1(){ return feebdaed; public Beef dead1(){ return new Beefdead(); public class Beefdead implements Beef { private ArrayList<Foo> beefdead = new ArrayList<Foo>(); public void beef1(foo f){ beefdead.add(f); public void beef2(){ for(foo f: beefdead){ f.foo1(); public class Bar implements Foo { public void foo1(){ System.out.println("15-214 rocks my socks!"); The world- renowned hacker, "NotYour214TA", has some tricks up his sleeve. In order to protect his code from being understood by other he changes around all of the names so that other hackers can't read it. Little does he know at Carnegie Mellon, we laugh at such simple problems!

15-214 Midterm Exam Andrew ID: SOLUTIONS 10 / 13 Q1. [12 points] There are 3 key design patterns that are used in the code above. State these patterns and describe which classes play which roles in those patterns. Hint 1: CHOOSE FROM THESE PATTERNS: singleton, facade, adapter, strategy, proxy, composite, observer, factory method, template, decorator. PATTERNS THAT ARE NOT IN THIS LIST WILL NOT RECIEVE CREDIT Hint 2: A single class may be used in multiple patterns. pattern #1: Abstract Factory role of each relevant class in pattern #1: - Dead is a factory - Deadbeef is a concrete factory - Beef is a product - Beefdead is a concrete product pattern #2: Observer role of each relevant class in pattern #2: - Foo is an observer - Bar is a concrete observer - Beef is the subject - Beefdead is a concrete subject pattern #3: Singleton role of each relevant class in pattern #3: - Deadbeef is a singleton

15-214 Midterm Exam Andrew ID: SOLUTIONS 11 / 13 Q2. [4 points] Name the most appropriate pattern for each purpose: Hint: CHOOSE FROM THESE PATTERNS: singleton, facade, adapter, strategy, proxy, composite, observer, factory method, template method, decorator. a) add functionality to individual objects dynamically and transparently Decorator. b) expose the functionality of an object through another interface Adapter. c) fix the structure of an algorithm but allow portions of that algorithm to vary Template Method. d) load an object from a database on demand Proxy.

15-214 Midterm Exam Andrew ID: SOLUTIONS 12 / 13 Verification [22 points] Q1. [8 points] Compute the weakest precondition. Assume integer operations. Simplify the result as much as possible. Important note: Assume all variables and operations range over integers. a) wp ( ' r *= x; n = n- 1 ', ans = x n * r) Ans: wp ( 'r=r*x', ans=x^(n- 1)*r) ans = x^(n- 1)*(r*x) ans = x^n * r b) wp (' x *= x; n /= 2 ', ans = x n * r) Ans: wp ( 'x=x*x', ans = x^(n/2)*r) ans = (x^2)^(n/2)*r // n even ans = x^n * r ans = (x^2)^(n- 1)/2 * r // n odd ans = x^(n- 1) * r Q2. [6 points] Always (all models), Never (no models), or Sometimes (some models) a) True => False Never b) False => False Always c) False => True Always d) False => x=1 Always e) x=1 => False Sometimes f) x=1 => True Always

15-214 Midterm Exam Andrew ID: SOLUTIONS 13 / 13 Q3. [8 points] The weak and the strong. Indicate your answer by circling an assertion or by notating "None of these." a) Which assertion is weakest? x=1 Odd(x) True None of these b) Which assertion is strongest? x=1 Odd(x) True None of these c) Which assertion is strongest? x=1 Odd(x) False y=1 None of these d) Which assertion is weakest? x=1 Odd(x) False y=1 None of these