Download presentation
Presentation is loading. Please wait.
Published byElijah Dennis Modified over 9 years ago
1
CIS 068 Welcome to CIS 068 ! Lesson 3: Algorithm Correctness And Efficiency
2
CIS 068 Overview Subjects: Program Defects Exceptions Testing Strategies Formal Methods of Verification Efficiency of Algorithms
3
CIS 068 Errors Three kinds of errors: 1.Syntax errors 2.Runtime errors 3.Logical errors
4
CIS 068 Syntax Errors Mistakes in the use of language‘s grammar (or syntax) Usually not critical Usually discovered by compiler...but sometimes hard to find !
5
CIS 068 Syntax Error Example The next slide will show a JAVA program. It is supposed to show all numbers n divisible by 7 without remainder, 0<n<1000 Please answer the following questions: 1.Will the compiler accept the code ? 2.What is the program‘s result ? 3.Does a compiler always find syntax-errors ?
6
CIS 068 Syntax Error Example public class Class1 { public static void main(String[] args) { /* Detect if number is multiple of 7 */ for (int i=1; i<1000; i++){ if ((i%7) == 0){ System.out.println(i+""); // Exit Program --------------------------------- System.out.println("That's it. Goodbye."); System.exit(0); } The loop is defined by these brackets ! The program will exit INSIDE the loop
7
CIS 068 Syntax Error Example Will the compiler accept the code ? What is the program‘s result ? Does a compiler always find syntax-errors ? YES “That’s it. Goodbye” NO !
8
CIS 068 Runtime Errors Occuring during program execution Critical if appearing in special cases (see Example ‘AT&T breakdown’, last lesson) Not discovered by compiler Forces the computer to exit program (if no recovery code is written)
9
CIS 068 Runtime Error Example The next slide will show a JAVA program, assigning the series 1,1/2, 1/3, 1, 1/2, 1/3,... to a 60-element array. Please answer the following questions: Will the compiler accept the code ? What will happen executing the program ?
10
CIS 068 Runtime Error Example public class Class1 { public static void main(String[] args) { int myArray[] = new int[60]; // Assign 1, ½, 1/3, 1, ½, 1/3... to myArray for (int i =1; i <= 60; i++){ myArray[i] = i/(i%3); } Index out of bounds (60) Expression (i%3) is 1,2,0,1,2,0.. Division by Zero !
11
CIS 068 Runtime Error Example Will the compiler accept the code ? What will happen executing the program ? Yes (Multiple) Runtime Errors will occur, starting with a division by zero.
12
CIS 068 Common Runtime Errors
13
CIS 068 Common Runtime Errors cont‘d Class Cast Exception References to objects of one type can be casted to different types in the class- hierarchy Two types of casting: 1.UPcasting 2.DOWNcasting
14
CIS 068 Up/Down casting Root class1 Derived from UPCAST DOWNCAST Always safeCan cause error
15
CIS 068 Up/Down casting Example: Class2 derived from Class1 Class2 adds field int onlyInClass2
16
CIS 068 Up/Down casting, examples Class1 c1 = new Class1();// c1 = Class1 - Object Class2 c2 = new Class2();// c2 = Class2 - Object // Class2 c3 = (Class2)c1;// DOWNCAST ERROR ! // Class1 c3 = (Class1)c2;// UPCAST ((Class2)c3).onlyInClass2 = 5;// DOWNCAST possible ! // Class1 c3 = c1; ((Class2)c3).onlyInClass2 = 5;// DOWNCAST ERROR !
17
CIS 068 NullPointerError Occurs when trying to attempt a non- existing object For C++ - programmers: don’t be confused, there are really no pointers in JAVA ! Example: Object testObject = null;// init Object to null (necessary for compiler) If (expression) {// testObject = new Object ();// create Object } testObject.testMethod();// will result in error if expression was false
18
CIS 068 Exceptions How to handle errors Without exceptions: program entered undefined state or crashes possible errors can be guarded by if – statements better use exceptions !
19
CIS 068 Exceptions Are The Rule Runtime Error Create instance of class Exception (‘throw’ exception) Program ‘catches’ the exception, i.e. appropriate codeblock is entered
20
CIS 068 Try – Catch mechanism Syntax: try { // Statements that may throw exceptions … } catch(Exception1 e1){ //statements to execute for exceptions type Exception1 } catch(Exception2 e2){ //statements to execute for exceptions type Exception2 } … finally{ // Statements to execute after try-catch }
21
CIS 068 Try – Catch Example try{ int n = 4 / 0; } catch(ArithmeticException ae){ ae.printStackTrace(); } Some Exceptions provided by JAVA:
22
CIS 068 Exceptions Exceptions are Objects Since Exceptions are Objects, you can derive your own Exception. myOwnException
23
CIS 068 Exceptions What to do with exceptions ? every exception has the methods getMessage(), returning a detailed message of the exception printStackTrace(), printing the exception and its backtrace getMessage() and printStackTrace() are inherited from class Throwable
24
CIS 068 Exceptions Example: try{ … } catch(Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); } … Example for Stack-Trace:
25
CIS 068 Exceptions try – catch – finally finally {} is ALWAYS executed independent from execution of try{} and/or catch {} – body Only System.exit() overrides that rule A good place to clean up !
26
CIS 068 Throwing Exceptions Using the throw – command, Exceptions can directly be triggered (rather than waiting for the JVM)
27
CIS 068 Logic Errors Most Critical Errors Occur in the design – phase Can’t be detected by computer, not at compile-time, not at run-time What can be done ?
28
CIS 068 Logic Errors carefully check the algorithm single step tracing explain and simulate execution with other team members (structured walkthrough) use program testing strategies
29
CIS 068 Testing Strategies Develop test-plan early in the design stage
30
CIS 068 Testing Strategies Use defensive programming, i.e. include code for every unexpected or invalid data values ! (Example: string – input)
31
CIS 068 Testing Strategies Testing questions: Who does the testing ? Blackbox or Whitebox – Testing ?
32
CIS 068 Testing Strategies Top – Down Testing Entire logical flow is implemented Usage of stubs instead of completed Methods Easy to write provide defined results easy simulation of unexpected data
33
CIS 068 Testing Strategies Bottom – Up Testing implementation of single methods test of each method separately by driver - programs
34
CIS 068 Debugging Tips Carefully document each method parameter and local variable using comments as you write the code. Also describe the method’s purpose. Name methods and variables meaningful Create an execution-trace by printing out the method’s name when executed Display the values of all arguments upon entry to a method Display the values of all results after returning from a method Verify results by hand – computation !
35
CIS 068 Formal Methods of Program Verification Assertions logical statements about the program which are asserted to be true written as a comment in the code to describe what is supposed to be true at this point task of tester: prove that a program fragment meets its specification
36
CIS 068 Assertions A simple example Proving means: the final assertion, the postcondition, follows from the initial precondition
37
CIS 068 Assertions The assignment rule: testing vice versa allows to transform a postcondition in a precondition Replace each occurrence of x in R with e Truth of x after the assignment is given by truth of e prior to the assignment
38
CIS 068 Assertions Verifying an if – statement Formally:
39
CIS 068 Assertions Verifying an if – statement Example:
40
CIS 068 Assertions Verifying Loops: Loop Invariants Logical statement involving program variables that is true before the loop is entered after each execution of the loop body when the loop termination occurs The loop – invariant ‘simulates’ a constant precondition
41
CIS 068 Loop Invariants - Example
42
CIS 068 Loop Invariants - Example
43
CIS 068 Loop Invariants - Example (example 2)
44
CIS 068 Efficiency Measurement of number of program – steps performed Usually a precise measure can’t be given Approximation dependent on preconditions Big – O (Order of Magnitude) Notation
45
CIS 068 Big – O Notation Definition: Algorithm has order of magnitude f(n) [=O(f(n))] means: There exists a constant C such that the actual running-time T(N) is less than C * f(n) for N towards infinity f(n) can therefore be determined by the fastest growing term of the algorithm.
46
CIS 068 Big – O Notation Example: An algorithm performing n*n + 4 steps (depending on precondition n) has the order of magnitude n*n, O(n*n) Question: Is an O(n) algorithm A1 necessarily always (i.e. for all n) faster than an O(n*n) algorithm A2 ?
47
CIS 068 Big – O Notation (example: insert)
48
CIS 068 Review Subjects: Different Types of Errors Exceptions, try-catch-finally Testing Strategies Formal Methods of Verification assignment rule loop invariants Efficiency of Algorithms Big O
49
CIS 068 Good Bye The Subjects of this lesson are covered in chapter 2 of Software Design & Data Structures in Java By Elliot B. Koffman + Paul A. T. Wolfgang
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.