School of Informatics, University of Edinburgh

Size: px
Start display at page:

Download "School of Informatics, University of Edinburgh"

Transcription

1 CS1Bh Solution Sheet 3 Debugging and Logic This is a solution set for CS1Bh Question Sheet 3. You should only consult these solutions after attempting the exercises. Notice that the solutions are samples alternative answers may be possible. 1. Consider the following Java class, StringConcat. The intention of this class is to concatenate the command line arguments and to print them out. However, the implementation of the main method in the class contains a bug. Use the Java debugger to single-step through the program and find the bug. 1 class StringConcat { 2 public static void main (String[] args) { 3 String s = ""; 4 for (int i = 0 ; i < args.length ; i++) { 5 s.concat(args[i]); 6 7 System.out.println(s); 8 9 NOTE: The original version of this question sheet contained a bug, which, in turn induced an easily found bug in the StringConcat.java. This bug is corrected in the program shown above. The solution below refers to the corrected version and the remaining, less easily found, bug. Here is a trace of the Java debugger at work on this example, [scar]stg: jdb StringConcat test1 test2 test3 Initializing jdb... > stop at StringConcat:5 Deferring breakpoint StringConcat:5. It will be set after the class is loaded. > stop at StringConcat:7 Deferring breakpoint StringConcat:7. It will be set after the class is loaded. > run run StringConcat test1 test2 test3 > 1

2 VM Started: Set deferred breakpoint StringConcat:7 Set deferred breakpoint StringConcat:5 Breakpoint hit: thread="main", StringConcat.main(), line=5, bci=8 5 s.concat(args[i]); main[1] locals Method arguments: args = instance of java.lang.string[3] (id=194) Local variables: s = "" i = 0 main[1] cont > Breakpoint hit: thread="main", StringConcat.main(), line=5, bci=8 5 s.concat(args[i]); main[1] locals Method arguments: args = instance of java.lang.string[3] (id=194) Local variables: s = "" i = 1 main[1] cont > Breakpoint hit: thread="main", StringConcat.main(), line=5, bci=8 5 s.concat(args[i]); main[1] locals Method arguments: args = instance of java.lang.string[3] (id=194) Local variables: s = "" i = 2 main[1] cont > Breakpoint hit: thread="main", StringConcat.main(), line=7, bci=25 7 System.out.println(s); main[1] locals Method arguments: args = instance of java.lang.string[3] (id=194) Local variables: s = "" i = 3 main[1] cont > The application exited The bug is that the programmer has misunderstood that the concat() method returns a string 2

3 as its result, rather than updating it in-place. The fix is to replace line 5 by s = s.concat(args[0]); 2. In this example we are attempting to produce a simple program to count the number of characters in a text file. For this we need to use classes from the java.io package, the FileInputStream class and the DataInputStream class. As we know, any file input or output operations can raise Java exceptions. Because of this we enclose the readchar() method call inside a try block and we handle the problems of not finding the file, reaching the end of the file and other input errors in the expected way (see lines 13 to 19 of the following program). 3

4 1 import java.io.*; 2 class CountingCharacters { 3 public static void main (String[] args) { 4 int count = 0; 5 try { 6 FileInputStream f = new FileInputStream(args[0]); 7 DataInputStream d = new DataInputStream(f); 8 char c; 9 while (true) { 10 c = d.readchar(); 11 count++; catch (FileNotFoundException e) { 14 System.out.println("Could not find file "+args[0]); 15 catch (EOFException e) { 16 System.out.println("Character count: " + count); 17 catch (IOException e) { 18 e.printstacktrace(); The program which we have seems very simple, and it is hard to imagine that it could contain any errors. The name of the file to be read is passed into the program as the first entry in the array of command line arguments (args[0]). We open this as a FileInputStream and construct a DataInputStream on top (where previously in CS1Ah Lecture Note 29 we had seen an ObjectInputStream). We read characters from the file as seen on line 10. We count each character which we read on line 11. We repeat this until there are no characters left and then the EOFException is caught and the count of the number of characters is printed out on line 16. However, when we first use this program on a sample input file such as this: abcdefghijklmnopqrstuvwxyz the program prints the following message: Character count: 13 This is certainly not what we had expected. The input file contains 26 characters, not 13, so how has the program gone wrong? Use the Java debugger to find the bug. As usual, we single-step through the code inspecting the values of local variables. [scar]stg: jdb CountingCharacters inputfile Initializing jdb... > stop at CountingCharacters:10 Deferring breakpoint CountingCharacters:10. It will be set after the class is loaded. 4

5 > run run CountingCharacters inputfile > VM Started: Set deferred breakpoint CountingCharacters:10 Breakpoint hit: thread="main", CountingCharacters.main(), line=10, bci=25 10 c = d.readchar(); main[1] step main[1] Step completed: thread="main", CountingCharacters.main(), line=11, bci=31 11 count++; main[1] print c c =? At every stage we find that the character variable c prints as?. This seems to point the way to the diagnosis of the source of the error. For further clarification we would need to revise Java s idea of a character. Java reserves sixteen bits for a character (called a UNICODE character) whereas most programming languages only use eight (called an ASCII character). Thus each pair of eight-bit ASCII characters in the file is being interpreted (in this case incorrectly) as a single sixteen-bit UNICODE character. To repair this problem we need to read the characters as bytes and cast them to a character. We replace line 10 above with the following line to repair the problem. c = (char) d.readbyte(); With this correction in place the program counts characters correctly. 5

6 3. a) Use semantic trees to check whether each of the following formulas is a tautology. If it is not a tautology, describe a counter example. i. ((P Q) P ) P This and other solutions produced by choosing topmost signed formula to discharge in the event of a choice, unless otherwise stated. f: ((P Q) P ) P t: (P Q) P Q t: P t: P f: Q A tautology. ii. P Q P Q t: P Q Q P Q Q Q t: P t: Q t: P Q f: Q t: P t: Q t: P t: Q f: Q 6

7 Counter-examples from remaining open paths are {P f, Q t and {P t, Q f. iii. P (Q R) (P Q) (P R) (Q R) (P Q) (P R) t: P (Q R) f: (P Q) (P R) t: P t: Q R Q t: Q f: Q R t: R f: Q f: R A tautology. b) Use semantic trees to check whether each of the following formulas is satisfiable or a contradiction. If it is satisfiable, give a satisfying assignment. i. P P t: P P t: P t: P 7

8 A contradiction. ii. (P Q) P Q Q t: P f: Q t: (P Q) P Q t: P Q t: P t: Q Is satisfiable. Satisfying assignments include {P t, and {Q t. iii. (P Q) (Q R) (P R) Here we vary the order of discharging nodes to keep the tree size down. We also split the top-level conjunction in a single step. t: (P Q) (Q R) (P R) t: P Q t: Q R t: (P R) R t: P f: R t: Q f: Q t: R A contradiction. 4. Here are some exercises in reasoning by using chains of logical equivalences. See Lecture Note 18 for background and a list of equivalence rules you can use. In your solutions, give a few words by each step to explain why that step is justified. 8

9 a) P Q R P Q R P Q R P ( Q R) characterisation ( P Q) R associativity (P Q) R de Morgans law P Q R characterisation b) P (Q P ) t P (Q P ) P ( Q P ) characterisation (P P ) Q assoc. and comm. t Q Excluded middle t Excluded Middle is the name given to the rule (P P ) t. It was included in CS1Ah Lecture Note 18, though its name was omitted. c) P ( P Q) P Q (Use only rules 1-18). P ( P Q) (P P ) (P Q) dist. over f (P Q) P Q d) (P Q) ( P R) (P Q) ( P R) (P Q) ( P R) ( P Q) (P R) characterisati ( P P ) ( P R) (Q P ) (Q R) dist. over (P Q) ( P R) ( P P ) (Q R) comm. (P Q) ( P R) (Q R) (P Q) ( P R) ((P P ) Q R) identity for (P Q) ( P R) (P Q R) ( P Q R) dist over (P Q) ( P R) e) (i j j k) i > j i j j k (State and use an extra rule relating < and ) Using extra rule that a > b (a b), we have (i j j k) i > j (i j j k) (i j) extra rule (i j (i j)) (j k (i j)) dist. over t (j k (i j)) excluded middle law j k (i j) t identity for i j j k comm. + characterisation 9

10 5. a) Put the following formulas in disjunctive normal form using chains of equivalence steps. A general procedure for applying equivalence rules to put propositions in DNF is: i. Eliminate occurrences of and using their characterisations in terms of, and. ii. Push all occurrences of inwards and cancel double occurrences. All s should now only surround variables. iii. Repeatedly distribute s over s (push s under the s). i. (P Q) (Q R) (P Q) (Q R) ( P Q) ( Q R) (( P Q) Q) (( P Q) R) ( P Q) (Q Q) ( P R) (Q R) ( P Q) ( P R) (Q R) Here the expression was already in DNF at the penultimate step, but then we applied some simplification. ii. (P 1 Q 1 ) (P 2 Q 2 ) (P 3 Q 3 ) One DNF form for this expression is (P 1 P 2 P 3 ) (P 1 P 2 Q 3 ) (P 1 Q 2 P 3 ) (P 1 Q 2 Q 3 ) (Q 1 P 2 P 3 ) (Q 1 P 2 Q 3 ) (Q 1 Q 2 P 3 ) (Q 1 Q 2 Q 3 ) If we had n conjuncts instead of 3, we would have 2 n conjuncts in the DNF form. If we care about keeping the size of expressions down, putting them in DNF (or CNF) is not always a good idea! b) Put the following formulas in conjunctive normal form: The general procedure is the same as for DNF, except in step 3, one instead repeatedly distributes s over s. i. (P Q) (Q R) (P Q) (Q R) ( P Q) ( Q R) 10

11 ii. P Q P Q (P Q P Q) ((P Q (P Q)) ( (P Q) (P Q)) (P Q) (P Q) (( P Q) ( P Q)) (P Q) ( P Q) Here we have additionally used instances of the idempotence rules A A A and A A A to simplify expressions, though we still would have got a DNF expression without these rules. 6. Consider the following truthtable for a 3 argument propositional operator C. P Q R C(P, Q, R) f f f f t f f f f t f f t t f t f f t f t f t t f t t t t t t t Write down a formula for C in a. DNF, b. CNF. Hint: for DNF, write one disjunct for each variable truth assignment making the operator true. For CNF, write one conjunct for each variable truth assignment making the operator false. A DNF form is A CNF form is (P Q R) (P Q R) ( P Q R) (P Q R) (P Q R) ( P Q R) (P Q R) (P Q R) 7. Consider writing down propositions in n propositional variables. What s the largest set S of such propositions such that for no two different propositions P, Q in S, we have that P Q is a tautology? Hint: this is related to, but much bigger than, the number of valuations you have to check to see if P is a tautology. P Q is a tautology just when P and Q have the same truth tables, so the number of distinct propositions is the same as the number of distinct truth tables. A truth table for a proposition in n variables has 2 n rows, one row for each valuation of the variables. For each row, there are 2 possibilities for the truth value of the proposition, so there are overall 2 2n possible truth tables. Hence the largest set S has size 2 2n. 11

12 8. Lecture Note 19 considered a class A with an integer array field x and a method findmin() for finding the minimum value stored in x: class A { private int[] x; public int findmin() { int min = x[0]; for (int i = 1; i!= x.length ; i++) { if (x[i] < min) min = x[i]; return min; One property not checked by the assertions and loop invariant discussed in the note is that the min value returned actually occurs in the array x. a) Using ESC/Java-like syntax, annotate the the class definition with an ensures postcondition, assert statements and a loop invariant appropriate for checking this property. Hint: you will need to use a \exists quantifier. A solution, very similar to that from the lecture note, is: class A { private int[] x; //* requires x!= null && x.length!= 0; //* ensures //* (\exists int n; 0 <= n & n < x.length & \result == x[n]); public int findmin() { int min = x[0]; //* assert min == x[0]; //* loop_invariant //* (\exists int n; 0 <= n & n < i & min == x[n]); for (int i = 1; i!= x.length ; i++) { if (x[i] < min) min = x[i]; //* assert //* (\exists int n; 0 <= n & n < x.length & min == x[n]); return min; 12

13 b) Using the Java 1.4 assertion facility, code an appropriate post-condition check for this property. Use an auxiliary method as shown in the note. A solution is: class A { private int[] x; public int findmin() { assert x!= null && x.length!= 0 : "A.findMin: precondition" ; int min = x[0]; for (int i = 1; i!= x.length ; i++) { if (x[i] < min) min = x[i]; assert checkpostcondition(min) : "A.findMin: postcondition" ; return min; private boolean checkpostcondition(int min) { boolean val = false; for (int i = 0; i!= x.length; i++) { val = val (x[i] == min); return val; 9. Using ESC/Java-like syntax, complete the the requires (precondition), ensures (postcondition) and loop invariant assertions for the following Java method which evaluates the integer value of a boolean array arr: //@ requires... //@ ensures \result =... static boolean intval(int i; int[] arr) { int val = 0; //@ loop_invariant val =... for (int j = 0; j!= arr.length; j++) { if (arr[j]) val = val + intpow(2,j); return val; Assume that a method static int intpow(int a, int b) {... 13

14 for computing a b is defined elsewhere in the same class. Use the syntax (\sum int k; i<=k & k<j; e) to express the mathematical sum j 1 e. k=i You might also want to make use of conditional expressions in Java which have form b? e 1 : e 2. If b evaluates to true, this expression evaluates to e 1. Otherwise it evaluates to e 2. A solution is: //@ requires arr!= null; //@ ensures \result = //@ (\sum int k; 0<=k & k<arr.length; arr[k]? intpow(2,k) : 0); static boolean intval(int i; int[] arr) { int val = 0; //@ loop_invariant //@ val = (\sum int k; 0<=k & k<j; arr[k]? intpow(2,k) : 0); for (int j = 0; j!= arr.length; j++) { if (arr[j]) val = val + intpow(2,j); return val; 10. In the spirit of the overview in Lecture Note 19 of the assertion languages of JML and ESC/Java, write requires (precondition) and ensures (postcondition) pragmas for the method public void add(int index, Object element); found in the LinkedList Java collection class ( see 4.1/docs/api/java/util/LinkedList). Your precondition should check that the collection reference (refer to it using this) is non null and that the index is in range. Checks in postcondition should assert how existing elements of the collection are unchanged and the new element has been inserted as position index. In the postcondition, refer to the collection at the start using \old(this). requires this!= null & 0 <= index & index < size() ; ensures (\forall int i ; 0 <= i & i < index ==> get(i) == \old(this).get(i)) & (\forall int i ; index <= i & i < \old(this).size() ==> get(i+1) == \old(this).get(i)) 14

15 & get(index) == element; public void add(int index, Object element); To understand this, note that the add method puts the new element before the existing element at position index. If the list is originally e 0, e 1, e 2, e 3, e 4 and we make a call add(2, a), the new list will be e 0, e 1, a, e 2, e 3, e 4. It is not necessary to have element!= null as part of the precondition. It may be a pathological case, but nothing will go wrong if we add a null reference in place of (a reference to) an element object at some position in a list. Stephen Gilmore, Paul Jackson, Michael Fourman, April 16th,

Computer Science 1 Bh

Computer Science 1 Bh UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Bh Resit Examination Specimen Solutions Date: Friday 6th September 2002 Time: 09:30 11:00

More information

CS2: Debugging in Java

CS2: Debugging in Java CS2: Debugging in Java 1. General Advice Jon Cook (LFCS) April 2003 Debugging is not always easy. Some bugs can take a long time to find. Debugging concurrent code can be particularly difficult and time

More information

Computer Science 1 Bh

Computer Science 1 Bh UNIVERSITY OF EDINBURGH course CS0077 FACULTY OF SCIENCE AND ENGINEERING DIVISION OF INFORMATICS SCHOOL OF COMPUTER SCIENCE Computer Science 1 Bh Degree Examination Date: Saturday 25th May 2002 Time: 12:00

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

Testing, Debugging, and Verification

Testing, Debugging, and Verification Testing, Debugging, and Verification Formal Specification, Part II Srinivas Pinisetty 23 November 2017 Introduction Today: Introduction to Dafny: An imperative language with integrated support for formal

More information

Full file at

Full 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 information

Computer Science 1 Ah

Computer Science 1 Ah UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Formal Methods for Java

Formal Methods for Java Formal Methods for Java Lecture 1: Introduction Jochen Hoenicke Software Engineering Albert-Ludwigs-University Freiburg October 26, 2011 Jochen Hoenicke (Software Engineering) Formal Methods for Java October

More information

Fondamenti della Programmazione: Metodi Evoluti. Lezione 5: Invariants and Logic

Fondamenti della Programmazione: Metodi Evoluti. Lezione 5: Invariants and Logic Fondamenti della Programmazione: Metodi Evoluti Prof. Enrico Nardelli Lezione 5: Invariants and Logic versione originale: http://touch.ethz.ch Reminder: contracts Associated with an individual feature:

More information

Software Engineering

Software Engineering Software Engineering Lecture 13: Testing and Debugging Testing Peter Thiemann University of Freiburg, Germany SS 2014 Recap Recap Testing detect the presence of bugs by observing failures Recap Testing

More information

Propositional Calculus: Boolean Algebra and Simplification. CS 270: Mathematical Foundations of Computer Science Jeremy Johnson

Propositional Calculus: Boolean Algebra and Simplification. CS 270: Mathematical Foundations of Computer Science Jeremy Johnson Propositional Calculus: Boolean Algebra and Simplification CS 270: Mathematical Foundations of Computer Science Jeremy Johnson Propositional Calculus Topics Motivation: Simplifying Conditional Expressions

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

Programming Languages Third Edition

Programming Languages Third Edition Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand

More information

Lecture Notes on Contracts

Lecture Notes on Contracts Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,

More information

Fundamentals of Software Engineering

Fundamentals of Software Engineering Fundamentals of Software Engineering Reasoning about Programs - Selected Features Ina Schaefer Institute for Software Systems Engineering TU Braunschweig, Germany Slides by Wolfgang Ahrendt, Richard Bubel,

More information

Software Engineering Testing and Debugging Testing

Software Engineering Testing and Debugging Testing Software Engineering Testing and Debugging Testing Prof. Dr. Peter Thiemann Universitt Freiburg 08.06.2011 Recap Testing detect the presence of bugs by observing failures Debugging find the bug causing

More information

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP 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 information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Pace University. Fundamental Concepts of CS121 1

Pace 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 information

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion Prelim 1 CS 2110, October 1, 2015, 5:30 PM 0 1 2 3 4 5 Total Question Name True Short Testing Strings Recursion False Answer Max 1 20 36 16 15 12 100 Score Grader The exam is closed book and closed notes.

More information

Checking Program Properties with ESC/Java

Checking Program Properties with ESC/Java Checking Program Properties with ESC/Java 17-654/17-765 Analysis of Software Artifacts Jonathan Aldrich 1 ESC/Java A checker for Java programs Finds null pointers, array dereferences Checks Hoare logic

More information

Notes of the course - Advanced Programming. Barbara Russo

Notes of the course - Advanced Programming. Barbara Russo Notes of the course - Advanced Programming Barbara Russo a.y. 2014-2015 Contents 1 Lecture 2 Lecture 2 - Compilation, Interpreting, and debugging........ 2 1.1 Compiling and interpreting...................

More information

Program Verification (6EC version only)

Program Verification (6EC version only) Program Verification (6EC version only) Erik Poll Digital Security Radboud University Nijmegen Overview Program Verification using Verification Condition Generators JML a formal specification language

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

Programming with Contracts. Juan Pablo Galeotti, Alessandra Gorla Saarland University, Germany

Programming with Contracts. Juan Pablo Galeotti, Alessandra Gorla Saarland University, Germany Programming with Contracts Juan Pablo Galeotti, Alessandra Gorla Saarland University, Germany Contract A (formal) agreement between Method M (callee) Callers of M Rights Responsabilities Rights Responsabilities

More information

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm CIS 110 Introduction To Computer Programming February 29, 2012 Midterm Name: Recitation # (e.g. 201): Pennkey (e.g. bjbrown): My signature below certifies that I have complied with the University of Pennsylvania

More information

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore Lecture 04 Software Test Automation: JUnit as an example

More information

(a) (4 pts) Prove that if a and b are rational, then ab is rational. Since a and b are rational they can be written as the ratio of integers a 1

(a) (4 pts) Prove that if a and b are rational, then ab is rational. Since a and b are rational they can be written as the ratio of integers a 1 CS 70 Discrete Mathematics for CS Fall 2000 Wagner MT1 Sol Solutions to Midterm 1 1. (16 pts.) Theorems and proofs (a) (4 pts) Prove that if a and b are rational, then ab is rational. Since a and b are

More information

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Final Exam Solution Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Final Exam Solution

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

To prove something about all Boolean expressions, we will need the following induction principle: Axiom 7.1 (Induction over Boolean expressions):

To prove something about all Boolean expressions, we will need the following induction principle: Axiom 7.1 (Induction over Boolean expressions): CS 70 Discrete Mathematics for CS Fall 2003 Wagner Lecture 7 This lecture returns to the topic of propositional logic. Whereas in Lecture 1 we studied this topic as a way of understanding proper reasoning

More information

Stream Manipulation. Lecture 11

Stream Manipulation. Lecture 11 Stream Manipulation Lecture 11 Streams and I/O basic classes for file IO FileInputStream, for reading from a file FileOutputStream, for writing to a file Example: Open a file "myfile.txt" for reading FileInputStream

More information

6.11: An annotated flowchart is shown in Figure 6.2.

6.11: An annotated flowchart is shown in Figure 6.2. 6.11: An annotated flowchart is shown in Figure 6.2. Figure 6.2. Annotated flowchart of code fragment of Problem 6.13. The input specification is A: n 1, 2, 3,. It clearly holds at all points on the flowchart,

More information

Mathematical Logic Prof. Arindama Singh Department of Mathematics Indian Institute of Technology, Madras. Lecture - 9 Normal Forms

Mathematical Logic Prof. Arindama Singh Department of Mathematics Indian Institute of Technology, Madras. Lecture - 9 Normal Forms Mathematical Logic Prof. Arindama Singh Department of Mathematics Indian Institute of Technology, Madras Lecture - 9 Normal Forms In the last class we have seen some consequences and some equivalences,

More information

Atropos User s manual

Atropos User s manual Atropos User s manual Jan Lönnberg 22nd November 2010 1 Introduction Atropos is a visualisation tool intended to display information relevant to understanding the behaviour of concurrent Java programs,

More information

ITI Introduction to Computing II

ITI 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 information

ITI Introduction to Computing II

ITI 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 information

Assertions, pre/postconditions

Assertions, pre/postconditions Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What

More information

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

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014 CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014 Name: This exam consists of 8 problems on the following 8 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam.

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

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

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

More information

Definition: A context-free grammar (CFG) is a 4- tuple. variables = nonterminals, terminals, rules = productions,,

Definition: A context-free grammar (CFG) is a 4- tuple. variables = nonterminals, terminals, rules = productions,, CMPSCI 601: Recall From Last Time Lecture 5 Definition: A context-free grammar (CFG) is a 4- tuple, variables = nonterminals, terminals, rules = productions,,, are all finite. 1 ( ) $ Pumping Lemma for

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CS 251 Intermediate Programming Java Basics

CS 251 Intermediate Programming Java Basics CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions

More information

Lecture 7. File Processing

Lecture 7. File Processing Lecture 7 File Processing 1 Data (i.e., numbers and strings) stored in variables, arrays, and objects are temporary. They are lost when the program terminates. To permanently store the data created in

More information

[Ch 6] Set Theory. 1. Basic Concepts and Definitions. 400 lecture note #4. 1) Basics

[Ch 6] Set Theory. 1. Basic Concepts and Definitions. 400 lecture note #4. 1) Basics 400 lecture note #4 [Ch 6] Set Theory 1. Basic Concepts and Definitions 1) Basics Element: ; A is a set consisting of elements x which is in a/another set S such that P(x) is true. Empty set: notated {

More information

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

The Java Modeling Language JML

The Java Modeling Language JML The Java Modeling Language JML Néstor Cataño ncatano@puj.edu.co Faculty of Engineering Pontificia Universidad Javeriana The Java Modelling Language JML p.1/47 Lecture Plan 1. An Introduction to JML 2.

More information

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

CSE 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 information

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Task 1 In this question, we are in a nominal subtyping setting. Some languages have a special

More information

JML. Outline. Métodos Formais em Engenharia de Software. MI, Braga these slides were prepared by adopting/adapting teaching material

JML. Outline. Métodos Formais em Engenharia de Software. MI, Braga these slides were prepared by adopting/adapting teaching material Métodos Formais em Engenharia de Software JML José Carlos Bacelar Almeida Departamento de Informática Universidade do Minho MI, Braga 2008 Outline Design by Contract and JML Design by Contract Java Modeling

More information

Runtime Checking for Program Verification Systems

Runtime Checking for Program Verification Systems Runtime Checking for Program Verification Systems Karen Zee, Viktor Kuncak, and Martin Rinard MIT CSAIL Tuesday, March 13, 2007 Workshop on Runtime Verification 1 Background Jahob program verification

More information

Arguing for program correctness and writing correct programs

Arguing for program correctness and writing correct programs Arguing for program correctness and writing correct programs Saying things about states, programs Program state s1: x=4, y=-1.5, A={ me, you, he Assertions about program states x=3 False in s1 (y=x) x>=0

More information

Formal Specification and Verification

Formal Specification and Verification Formal Specification and Verification Proof Obligations Bernhard Beckert Based on a lecture by Wolfgang Ahrendt and Reiner Hähnle at Chalmers University, Göteborg Formal Specification and Verification:

More information

You must include this cover sheet. Either type up the assignment using theory4.tex, or print out this PDF.

You must include this cover sheet. Either type up the assignment using theory4.tex, or print out this PDF. 15-122 Assignment 4 Page 1 of 12 15-122 : Principles of Imperative Computation Fall 2012 Assignment 4 (Theory Part) Due: Thursday, October 18, 2012 at the beginning of lecture Name: Andrew ID: Recitation:

More information

Overview The Java Modeling Language (Part 1) Related Work

Overview The Java Modeling Language (Part 1) Related Work Overview The Java Modeling Language (Part 1) Wolfgang Schreiner Wolfgang.Schreiner@risc.jku.at Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria http://www.risc.jku.at

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

Streams and File I/O

Streams 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 information

COE318 Lecture Notes Week 4 (Sept 26, 2011)

COE318 Lecture Notes Week 4 (Sept 26, 2011) COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details

More information

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Pages 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 information

ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen

ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial p.1/??

More information

CS February 17

CS February 17 Discrete Mathematics CS 26 February 7 Equal Boolean Functions Two Boolean functions F and G of degree n are equal iff for all (x n,..x n ) B, F (x,..x n ) = G (x,..x n ) Example: F(x,y,z) = x(y+z), G(x,y,z)

More information

EXAMINATIONS 2009 MID-TERM TEST. COMP 202 / SWEN 202 Formal Methods of Computer Science / Formal Foundations of Software Engineering WITH ANSWERS

EXAMINATIONS 2009 MID-TERM TEST. COMP 202 / SWEN 202 Formal Methods of Computer Science / Formal Foundations of Software Engineering WITH ANSWERS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Time Allowed: 90 minutes EXAMINATIONS 2009 MID-TERM TEST COMP 202 / SWEN 202 Formal Methods

More information

Formale Entwicklung objektorientierter Software

Formale Entwicklung objektorientierter Software Formale Entwicklung objektorientierter Software Praktikum im Wintersemester 2008/2009 Prof. P. H. Schmitt Christian Engel, Benjamin Weiß Institut für Theoretische Informatik Universität Karlsruhe 5. November

More information

HST 952. Computing for Biomedical Scientists Lecture 8

HST 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 information

LOGIC AND DISCRETE MATHEMATICS

LOGIC AND DISCRETE MATHEMATICS LOGIC AND DISCRETE MATHEMATICS A Computer Science Perspective WINFRIED KARL GRASSMANN Department of Computer Science University of Saskatchewan JEAN-PAUL TREMBLAY Department of Computer Science University

More information

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure. Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading. Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Assn 3 posted. Announcements Final on June 14 or 15?

More information

Propositional Calculus. CS 270: Mathematical Foundations of Computer Science Jeremy Johnson

Propositional Calculus. CS 270: Mathematical Foundations of Computer Science Jeremy Johnson Propositional Calculus CS 270: Mathematical Foundations of Computer Science Jeremy Johnson Propositional Calculus Objective: To provide students with the concepts and techniques from propositional calculus

More information

THE CONCEPT OF OBJECT

THE CONCEPT OF OBJECT THE CONCEPT OF OBJECT An object may be defined as a service center equipped with a visible part (interface) and an hidden part Operation A Operation B Operation C Service center Hidden part Visible part

More information

To prove something about all Boolean expressions, we will need the following induction principle: Axiom 7.1 (Induction over Boolean expressions):

To prove something about all Boolean expressions, we will need the following induction principle: Axiom 7.1 (Induction over Boolean expressions): CS 70 Discrete Mathematics for CS Spring 2005 Clancy/Wagner Notes 7 This lecture returns to the topic of propositional logic. Whereas in Lecture Notes 1 we studied this topic as a way of understanding

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

JAVA BASICS II. Example: FIFO

JAVA BASICS II. Example: FIFO JAVA BASICS II Example: FIFO To show how simple data structures are built without pointers, we ll build a doubly-linked list ListItem class has some user data first refers to that ListItem object at the

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

221 Compilers Exercise 1: writing a very tiny interpreter

221 Compilers Exercise 1: writing a very tiny interpreter 221 Compilers Exercise 1: writing a very tiny interpreter The objective of this exercise is to write an interpreter in Java for a very simple programming language in fact a language for controlling the

More information

Computer Science 1 Ah

Computer Science 1 Ah UNIVERSITY OF EDINBURGH course CS0077 FACULTY OF SCIENCE AND ENGINEERING DIVISION OF INFORMATICS SCHOOL OF COMPUTER SCIENCE Computer Science 1 Ah Degree Examination Date: Saturday 25th May 2002 Time: 09:30

More information

Static program checking and verification

Static program checking and verification Chair of Software Engineering Software Engineering Prof. Dr. Bertrand Meyer March 2007 June 2007 Slides: Based on KSE06 With kind permission of Peter Müller Static program checking and verification Correctness

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

More information

Week 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 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 information

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

1993: renamed Java; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as

More information

CSEN 202: Introduction to Computer Programming

CSEN 202: Introduction to Computer Programming June 23, 2012 : Final exam Model Solutions Instructions. Please read carefully before proceeding. (a) The duration of this exam is 180 minutes. (b) Non-programmable calculators are allowed. (c) No books

More information

CS170 Introduction to Computer Science Midterm 2

CS170 Introduction to Computer Science Midterm 2 CS170 Introduction to Computer Science Midterm 2 03/25/2009 Name: Solution You are to honor the Emory Honor Code. This is a closed book and closednotes exam, and you are not to use any other resource than

More information

Chapter 17. Iteration The while Statement

Chapter 17. Iteration The while Statement 203 Chapter 17 Iteration Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Interation and conditional execution form the basis for algorithm

More information

Chapter 6 Primitive types

Chapter 6 Primitive types Chapter 6 Primitive types Lesson page 6-1. Primitive types Question 1. There are an infinite number of integers, so it would be too ineffient to have a type integer that would contain all of them. Question

More information

Informatics 1 - Computation & Logic: Tutorial 3

Informatics 1 - Computation & Logic: Tutorial 3 Informatics - Computation & Logic: Tutorial Counting Week 5: 6- October 7 Please attempt the entire worksheet in advance of the tutorial, and bring all work with you. Tutorials cannot function properly

More information

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as

More information

TRIAL EXAM C Software Engineering using Formal Methods TDA293 / DIT270

TRIAL EXAM C Software Engineering using Formal Methods TDA293 / DIT270 TRIAL EXAM C Software Engineering using Formal Methods TDA293 / DIT270 also serving as additional training material for the course Formal Methods for Software Development, TDA294/DIT271 1 Exam/Tenta SEFM

More information

CS 512, Spring 2017: Take-Home End-of-Term Examination

CS 512, Spring 2017: Take-Home End-of-Term Examination CS 512, Spring 2017: Take-Home End-of-Term Examination Out: Tuesday, 9 May 2017, 12:00 noon Due: Wednesday, 10 May 2017, by 11:59 am Turn in your solutions electronically, as a single PDF file, by placing

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

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

CSSE 220. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysListPractice from SVN CSSE 220 Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop Check out ArraysListPractice from SVN Help with Peers Having a peer help you with some strange bug or specific problem Great

More information

ECSE 321 Assignment 2

ECSE 321 Assignment 2 ECSE 321 Assignment 2 Instructions: This assignment is worth a total of 40 marks. The assignment is due by noon (12pm) on Friday, April 5th 2013. The preferred method of submission is to submit a written

More information

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key CIS 110 Introduction to Computer Programming 12 February 2013 Midterm Answer Key 0. (1 point) Miscellaneous (a) Write your name, recitation number, and PennKey (username) on the front of the exam. (b)

More information

Fall 2005 CS 11 Final exam Answers

Fall 2005 CS 11 Final exam Answers Fall 2005 CS 11 Final exam Answers 1. Question: (5 points) In the following snippet of code, identify all places where type casting would occur automatically or would need to occur through a forced cast.

More information