Dynamic Design Patterns

Size: px
Start display at page:

Download "Dynamic Design Patterns"

Transcription

1

2 Dynamic Design Patterns Adaptive Design in Uncertain Diverse Environment Stephen Wang This book is for sale at This version was published on This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do Stephen Wang

3 Tweet This Book! Please help Stephen Wang by spreading the word about this book on Twitter! The suggested hashtag for this book is #Software Design. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter:

4 Contents Acknowledgement Introduction Section 1. Optimum Pattern Further reading

5 Acknowledgement Below is a list of who helped editing this book: Seaborn Lee. Thanks. Thank my family, without their support, this book could not be published. This book referred the book Design Patters¹ ¹

6 Introduction Diversity Software have diverse features, that allows different people have different data. Object oriented programming is one of the technique makes it possible to write software to adapt the diversity of software. A system may have many operations share one same interface, may have many data share some fields. The object oriented technique allows define interfaces and classes for process these diversities. However, nowadays, software become more diverse that makes program more complicated. These diversity are uncertain in some circumstances, the rules are predefined, program runs with these predefined rules makes the uncertainty possible. Uncertainty Entertainment Game applications makes fun with uncertainty, not only the random numbers, but also the diversity of conditions. Business Business changes frequently, software need scalability to fit frequently changed requirements, and if possible, auto-adaptive is desired. Customize In the age of Internet, internet users want to customize the online services they are using. Therefore the online service applications need to be customizable. Customization makes user happy, but also bring technical challenge. Object oriented programming requires classes share method signature with its interface, classes inherit from one interface share method signature. But, in uncertain circumstance, processes are very different, then it is very difficult to unify the method signature of many classes. Adaptive programming techniques is needed to fit in these uncertain diverse circumstances.

7 Introduction 3 Predictability In uncertain diverse circumstances, only rules are predefined, the instances, behaviors, data are not predictable. In predictable circumstances, just apply some interfaces, and implementations can handle with the diversity, but in unpredictable circumstances, programmers cannot write an exact instance for next step, they can write a piece of codes that generate the desired instance according to the predefined rules. And because the parameters of rules are changeable, the difficulty of programming is raised. Dynamic Design Patterns Design patterns solve the diversity issues. But the uncertainty of diversity can not be solved by design patterns only. Dynamic design patterns are designed to solve some specific uncertain diverse issues. As implied in its name, dynamic design patterns are still design patterns, they are based on design patterns, and added some diversity to fit with the uncertainty of requirements.

8 Section 1. Optimum Pattern Description Chain of responsibility pattern² allows pass parameter through a chain of classes. Each step in the chain would do with the parameter, and return a result until the end of the chain. But, if the chain is not predictable, the chain can not be predefined. It needs to create handler in the chain dynamically according to the predefined rules, call the created handler continuously until the exit condition is met. This pattern is used to optimize strategies, so it is also called Optimum Pattern. UML The UML of optimum pattern is as follows: Structural Sample ²

9 Section 1. Optimum Pattern 5 This structural sample demonstrates the optimum pattern, which generates dynamic handler until the exit condition is met. Handler The interface of responsibility handler. HandlerFactory The factory creates concrete handler dynamically according to predefined rules. ConcreteHandlerA, ConcreteHanlderB The two concrete handlers to execute the concrete process. NullHandler The Null Object Pattern object that handle request in dummy. Client The client that call other classes. Text The aggregate object that contains the target object. 1 public interface Handler { 2 public Text handle(text text); 3 } 1 public class HandlerFactory { 2 3 public static Handler create(string params) { 4 int aindex = params.lastindexof("a"); 5 int bindex = params.lastindexof("b"); 6 if (aindex >= 0 bindex >= 0) { 7 if (aindex > bindex) { 8 return new ConcreteHandlerA(); 9 } else { 10 return new ConcreteHandlerB(); 11 } 12 } else { 13 return new NullHandler(); 14 } 15 } 16 }

10 Section 1. Optimum Pattern 6 1 public class ConcreteHandlerA implements Handler { 2 public Text handle(text text) { 3 int index = text.find("a"); 4 return text.reduce(index); 5 } 6 } 1 public class ConcreteHandlerB implements Handler { 2 public Text handle(text text) { 3 int index = text.find("b"); 4 return text.reduce(index); 5 } 6 } 1 public class NullHandler implements Handler { 2 public Text handle(text text) { 3 return text; 4 } 5 } 1 public class Client { 2 public void dynamicchain(text text) { 3 while (text.hasmore()) { 4 Handler next = HandlerFactory.create(text.text); 5 next.handle(text); 6 } 7 } 8 9 public static void main(string[] args) { 10 Client client = new Client(); 11 client.dynamicchain(new Text("aba2fdac23fabc")); 12 } 13 }

11 Section 1. Optimum Pattern 7 1 public class Text { 2 public String text; 3 4 public Text(String t) { 5 this.text = t; 6 } 7 8 public boolean hasmore() { 9 return!text.isempty(); 10 } public int find(string target) { 13 int index = text.lastindexof(target); 14 System.out.println(text.substring(index)); 15 return index; 16 } public Text reduce(int index) { 19 String reduced = ""; 20 if (index > 0) { 21 reduced = text.substring(0, index); 22 } else { 23 reduced = ""; 24 } 25 text = reduced; 26 return this; 27 } 28 } The result of the source above is : 1 bc 2 a 3 ac23f 4 a2fd 5 b 6 a Real World Sample A book store is going to have a promotion to a series of books, the discount strategy is defined as below :

12 Section 1. Optimum Pattern 8 5 different books in set, 75%, 4 different books in set, 80%, 3 different books in set, 90%, 2 different books in set, 95%, 1 book in set, 100%. each book s price is 8 EUR. Then how much would be the cheapest price after pick books as below: book #1-2 copies book #2-2 copies book #3-2 copies book #4-1 copy book #5-1 copy In this case, the best strategy is not predefined, but the rule is predefined. Pick as more as possible, and mind that 4 copies + 4 copies is cheaper than 5 copies + 3 copies. 1 import java.util.list; 2 3 public interface CartStrategy { 4 public Cart handle(cart cart, List<Strategy> strategies); 5 } 1 import java.util.list; 2 3 public class MostCartStrategy implements CartStrategy { 4 public Cart handle(cart cart, List<Strategy> strategies) { 5 Strategy strategy = cart.pickmost(); 6 strategies.add(strategy); 7 return cart; 8 } 9 }

13 Section 1. Optimum Pattern 9 1 import java.util.list; 2 3 public class SmartCartStrategy implements CartStrategy { 4 public Cart handle(cart cart, List<Strategy> strategies) { 5 Strategy before = cart.pick4(); 6 Strategy after = cart.pick4(); 7 strategies.add(before); 8 strategies.add(after); 9 return cart; 10 } 11 } 1 import java.util.list; 2 3 public class NullCartStrategy implements CartStrategy { 4 public Cart handle(cart cart, List<Strategy> strategies) { 5 return cart; 6 } 7 } 1 public class CartStrategyFactory { 2 3 public static CartStrategy create(cart cart) { 4 if (cart.has44()) { 5 return new SmartCartStrategy(); 6 } else if (!cart.isempty()) { 7 return new MostCartStrategy(); 8 } else { 9 return new NullCartStrategy(); 10 } 11 } 12 }

14 Section 1. Optimum Pattern 10 1 public class Book { 2 public String name; 3 public float price; 4 5 public Book(String n, float p) { 6 this.name = n; 7 this.price = p; 8 } 9 } 1 import java.util.*; 2 3 public class Cart { 4 5 Map<Book, Integer> books = new HashMap<Book, Integer>(); 6 7 public void add(book book, Integer count) { 8 if (books.containskey(book)) { 9 books.put(book, books.get(book) + count); 10 } else { 11 books.put(book, count); 12 } 13 } public boolean isempty() { 16 if (books.isempty()) { 17 return true; 18 } 19 Iterator iterator = books.keyset().iterator(); 20 while (iterator.hasnext()) { 21 Book book = (Book) iterator.next(); 22 if (books.get(book)!= 0) { 23 return false; 24 } 25 } 26 return true; 27 } public boolean has44() { 30 //44 = 535 different books, at least 3 of them is more than 2 copies 31 //44 = 44 (4 different books, all are more than 2 copies) 32 List<Book> onecopy = new ArrayList<Book>();

15 Section 1. Optimum Pattern List<Book> morecopies = new ArrayList<Book>(); Iterator iterator = books.keyset().iterator(); 36 while (iterator.hasnext()) { 37 Book book = (Book)iterator.next(); 38 Integer count = books.get(book); 39 if (count > 1) { 40 morecopies.add(book); 41 } else { 42 onecopy.add(book); 43 } 44 } if (onecopy.size() + morecopies.size() == 5 && morecopies.size() >= 3 47 morecopies.size() >= 4) { 48 return true; 49 } return false; 52 } public Strategy pick4() { 55 Strategy strategy = new Strategy(); if (countbooktype() == 4) { 58 return pickmost(); 59 } else { 60 Book least = findleastbook(); 61 for (Book book : BookFlyweight.books) { 62 if (hasbook(book) &&!book.equals(least)) { 63 pickbook(strategy, book); 64 } 65 } 66 } return strategy; 69 } private int countbooktype() { 72 int count = 0; 73 for (Book book : BookFlyweight.books) { 74 if (hasbook(book)) {

16 Section 1. Optimum Pattern count ++; 76 } 77 } 78 System.out.println("count = " + count); 79 return count; 80 } private Book findleastbook() { 83 int min = -1; 84 Book least = null; 85 Iterator keys = books.keyset().iterator(); 86 while (keys.hasnext()) { 87 Book book = (Book)keys.next(); 88 int count = books.get(book); 89 if (min == -1) { 90 min = count; 91 least = book; 92 } 93 if (min > count) { 94 least = book; 95 min = count; 96 } 97 } 98 return least; 99 } public Strategy pickmost() { 102 Strategy strategy = new Strategy(); if (hasbook(bookflyweight.book_1)) { 105 pickbook(strategy, BookFlyweight.BOOK_1); 106 } 107 if (hasbook(bookflyweight.book_2)) { 108 pickbook(strategy, BookFlyweight.BOOK_2); 109 } 110 if (hasbook(bookflyweight.book_3)) { 111 pickbook(strategy, BookFlyweight.BOOK_3); 112 } 113 if (hasbook(bookflyweight.book_4)) { 114 pickbook(strategy, BookFlyweight.BOOK_4); 115 } 116 if (hasbook(bookflyweight.book_5)) {

17 Section 1. Optimum Pattern pickbook(strategy, BookFlyweight.BOOK_5); 118 } return strategy; 121 } private boolean hasbook(book book) { 124 if (books.containskey(book)) { 125 if (books.get(book) == 0) { 126 return false; 127 } 128 return true; 129 } 130 return false; 131 } private void pickbook(strategy strategy, Book book) { 134 strategy.add(book); 135 books.put(book, books.get(book) - 1); 136 } 137 } 1 import java.util.hashmap; 2 import java.util.iterator; 3 import java.util.map; 4 5 public class Strategy { 6 Map<Book, Integer> books = new HashMap<Book, Integer>(); 7 8 public void add(book book) { 9 books.put(book, 1); 10 } public String tostring() { 13 String text = ""; 14 Iterator iterator = books.keyset().iterator(); 15 while (iterator.hasnext()) { 16 Book book = (Book)iterator.next(); 17 text += book.name + "@" + books.get(book) + ","; 18 } 19 return text; 20 }

18 Section 1. Optimum Pattern public float price() { 23 float price = 0.0f; 24 Iterator iterator = books.keyset().iterator(); 25 while (iterator.hasnext()) { 26 Book book = (Book)iterator.next(); 27 price += book.price; 28 } 29 return price * discountrate(); 30 } public float discountrate() { 33 switch (books.keyset().size()) { 34 case 5: 35 return 0.75f; 36 case 4: 37 return 0.8f; 38 case 3: 39 return 0.9f; 40 case 2: 41 return 0.95f; 42 default: 43 return 1f; 44 } 45 } 46 } 1 import java.util.arraylist; 2 import java.util.list; 3 4 public class Client { 5 6 public static void main(string[] args) { 7 Cart cart = new Cart(); 8 cart.add(bookflyweight.book_1, 2); 9 cart.add(bookflyweight.book_2, 2); 10 cart.add(bookflyweight.book_3, 2); 11 cart.add(bookflyweight.book_4, 1); 12 cart.add(bookflyweight.book_5, 1); List<Strategy> strategies = new ArrayList<Strategy>(); 15

19 Section 1. Optimum Pattern while (!cart.isempty()) { 17 CartStrategy strategy = CartStrategyFactory.create(cart); 18 cart = strategy.handle(cart, strategies); 19 } 20 float price = 0.0f; 21 for (Strategy strategy : strategies) { 22 System.out.println(strategy.toString()); 23 price += strategy.price(); 24 } 25 System.out.println("The amount is : " + price); 26 } 27 } 1 public class BookFlyweight { 2 public static final Book BOOK_1 = new Book("#1", 8); 3 public static final Book BOOK_2 = new Book("#2", 8); 4 public static final Book BOOK_3 = new Book("#3", 8); 5 public static final Book BOOK_4 = new Book("#4", 8); 6 public static final Book BOOK_5 = new Book("#5", 8); 7 } The result of the source above is : 51.2

20 Further reading Pool Pattern The pattern to access subjects in a limited size pool. Policy Pattern The pattern to work through a policy not a process. Panel Pattern The pattern to ON/OFF switches on a panel. Dispatcher Pattern The pattern to dispatch request to an instance according predefined rules. Coordinator Pattern The pattern to coordinate subjects running under a global circumstance. Dynamic Adapter Pattern The pattern to make adapter by conditions. Dynamic Command Pattern The pattern to execute commands in context.

Kotlin for Android Developers

Kotlin for Android Developers Kotlin for Android Developers Learn Kotlin the easy way while developing an Android App Antonio Leiva This book is for sale at http://leanpub.com/kotlin-for-android-developers This version was published

More information

Kotlin for Android Developers

Kotlin for Android Developers Kotlin for Android Developers Learn Kotlin the easy way while developing an Android App Antonio Leiva This book is for sale at http://leanpub.com/kotlin-for-android-developers This version was published

More information

The Little Mongo DB Schema Design Book

The Little Mongo DB Schema Design Book The Little Mongo DB Schema Design Book Christian Kvalheim This book is for sale at http://leanpub.com/mongodbschemadesign This version was published on 2015-10-09 ISBN 978-1-943846-77-1 This is a Leanpub

More information

CS 1331 Fall 2016 Exam 3 Part 1 ANSWER KEY

CS 1331 Fall 2016 Exam 3 Part 1 ANSWER KEY CS 1331 Fall 2016 Exam 3 Part 1 Fall 2016 ANSWER KEY Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score. Signing signifies you are

More information

A Primer on Design Patterns

A Primer on Design Patterns A Primer on Design Patterns First Edition Rahul Batra This book is for sale at http://leanpub.com/aprimerondesignpatterns This version was published on 2016-03-23 This is a Leanpub book. Leanpub empowers

More information

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

(a) Write the signature (visibility, name, parameters, types) of the method(s) required 1. (6 pts) Is the final comprehensive? 1 2. (6 pts) Java has interfaces Comparable and Comparator. As discussed in class, what is the main advantage of Comparator? 3. (6 pts) We can use a comparator in

More information

1. ArrayList and Iterator in Java

1. ArrayList and Iterator in Java 1. ArrayList and Iterator in Java Inserting elements between existing elements of an ArrayList or Vector is an inefficient operation- all element after the new one must be moved out of the way which could

More information

INTRODUCTION TO SOFTWARE SYSTEMS (COMP1110/COMP1140/COMP1510/COMP6710)

INTRODUCTION TO SOFTWARE SYSTEMS (COMP1110/COMP1140/COMP1510/COMP6710) Important notice: This document is a sample exam. The final exam will differ from this exam in numerous ways. The purpose of this sample exam is to provide students with access to an exam written in a

More information

SAMPLE EXAM Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010

SAMPLE EXAM Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010 SAMPLE EXAM Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010 NAME (Printed) NAME (Signed) E-mail Exam Rules Show all your work. Your

More information

Engineering Innovation Center LabVIEW Basics

Engineering Innovation Center LabVIEW Basics Engineering Innovation Center LabVIEW Basics LabVIEW LabVIEW (Laboratory Virtual Instrument Engineering Workbench) is a graphical programming language that uses icons instead of lines of text to create

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information

Git Workbook. Self-Study Guide to Git. Lorna Mitchell. This book is for sale at

Git Workbook. Self-Study Guide to Git. Lorna Mitchell. This book is for sale at Git Workbook Self-Study Guide to Git Lorna Mitchell This book is for sale at http://leanpub.com/gitworkbook This version was published on 2018-01-15 This is a Leanpub book. Leanpub empowers authors and

More information

Teach Yourself Enterprise Architect in Ten Days

Teach Yourself Enterprise Architect in Ten Days Teach Yourself Enterprise Architect in Ten Days An Introduction to the Famous and Affordable Modelling Tool Enterprise Architect Peter Doomen This book is for sale at http://leanpub.com/ea-in-10-days This

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Functional Programming in Ruby

Functional Programming in Ruby Functional Programming in Ruby Coding with Style koen handekyn This book is for sale at http://leanpub.com/functionalprogramminginruby This version was published on 2014-04-17 This is a Leanpub book. Leanpub

More information

This exam is open book. Each question is worth 3 points.

This exam is open book. Each question is worth 3 points. This exam is open book. Each question is worth 3 points. Page 1 / 15 Page 2 / 15 Page 3 / 12 Page 4 / 18 Page 5 / 15 Page 6 / 9 Page 7 / 12 Page 8 / 6 Total / 100 (maximum is 102) 1. Are you in CS101 or

More information

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Name: ID: Problem 1) (8 points) For the following code segment, what are the values of i, j, k, and d, after the segment

More information

COMP110 MT2 Study Guide

COMP110 MT2 Study Guide COMP110 MT2 Study Guide 1. T/F Determine whether the following statements are true or false. If false, correct the statement. F a. Given a list of unsorted integers from 0 to 100, inclusive, we can perform

More information

Highlights of Previous Lecture

Highlights of Previous Lecture Highlights of Previous Lecture Inheritance vs. Composition IS-A-KIND-OF vs. HAS-A relationships Java vs. C++: differences in ability to access base class behavior Interfaces as contracts, as types, supporting

More information

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Introduction to Programming Written Examination

Introduction to Programming Written Examination Introduction to Programming Written Examination 23.9.2016 FIRST NAME STUDENT NUMBER LAST NAME SIGNATURE Instructions for students: Write First Name, Last Name, Student Number and Signature where indicated.

More information

public static boolean isoutside(int min, int max, int value)

public static boolean isoutside(int min, int max, int value) See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static

More information

Lab Exercise 1. Objectives: Part 1. Introduction

Lab Exercise 1. Objectives: Part 1. Introduction Objectives: king Saud University College of Computer &Information Science CSC111 Lab Object II All Sections - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

More information

Lecture 17. For Array Class Shenanigans

Lecture 17. For Array Class Shenanigans Lecture 17 For Array Class Shenanigans For or While? class WhileDemo { public static void main(string[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; Note:

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC 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 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

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12 Objects and State COMP1400 Week 9 Mutator methods The internal state of an object can change. We do this by changing the values contained in its fields. Methods that change an object's state are called

More information

AngularJS Cookbook. 70 Recipes for AngularJS 1.2. Sascha Brink. This book is for sale at

AngularJS Cookbook. 70 Recipes for AngularJS 1.2. Sascha Brink. This book is for sale at AngularJS Cookbook 70 Recipes for AngularJS 1.2 Sascha Brink This book is for sale at http://leanpub.com/angularjs-cookbook This version was published on 2014-03-12 This is a Leanpub book. Leanpub empowers

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Structs and Interfaces

Structs and Interfaces Structs and Interfaces Structs and Interfaces Objectives Create structs as lightweight value-type objects. Create interfaces as contracts for classes to fulfill. Instantiate interfaces. Pass interfaces

More information

1.Which four options describe the correct default values for array elements of the types indicated?

1.Which four options describe the correct default values for array elements of the types indicated? 1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

Variable initialization and assignment

Variable initialization and assignment Variable initialization and assignment int variable_name; float variable_name; double variable_name; String variable_name; boolean variable_name; Initialize integer variable Initialize floating point variable

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

System Modelling. Lecture

System Modelling. Lecture System Modelling Lecture 25.10.2011 Lecture Objectives GUI design with Story-Driven Modelling Class Diagram to Code (revistited) Automatic Code Generation Intro to project Mancala game: 35pts Wireframes

More information

PASS4TEST IT 인증시험덤프전문사이트

PASS4TEST IT 인증시험덤프전문사이트 PASS4TEST IT 인증시험덤프전문사이트 http://www.pass4test.net 일년동안무료업데이트 Exam : 1z0-809 Title : Java SE 8 Programmer II Vendor : Oracle Version : DEMO Get Latest & Valid 1z0-809 Exam's Question and Answers 1 from

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

More information

Object Oriented Programming 2015/16. Final Exam June 28, 2016

Object Oriented Programming 2015/16. Final Exam June 28, 2016 Object Oriented Programming 2015/16 Final Exam June 28, 2016 Directions (read carefully): CLEARLY print your name and ID on every page. The exam contains 8 pages divided into 4 parts. Make sure you have

More information

Interfaces & Generics

Interfaces & Generics Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue General Loops in Java Look at other loop constructions Very common while loop: do a loop a fixed number of times (MAX in the example) int

More information

1. CPU utilization: it is the percentage of time the CPU is used for a specific time period ones want to keep the CPU as busy as possible (Max.

1. CPU utilization: it is the percentage of time the CPU is used for a specific time period ones want to keep the CPU as busy as possible (Max. Cairo University Faculty of Computers & Information Computer Science Department Lab 5: CPU Scheduling Theoretical part: Definition: The process scheduling is the activity of the process manager that handles

More information

IT 313 Advanced Application Development Midterm Exam

IT 313 Advanced Application Development Midterm Exam Page 1 of 9 February 12, 2019 IT 313 Advanced Application Development Midterm Exam Name Part A. Multiple Choice Questions. Circle the letter of the correct answer for each question. Optional: supply a

More information

System Modelling. Lecture

System Modelling. Lecture System Modelling Lecture 02.10.2012 Lecture Objectives Storyboards as a base Objects to Classes GUI design with Story-Driven Modelling Intro to the project: 25pts Story-Driven Modeling 1. Concrete behavior

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

CSE 143 Lecture 20. Circle

CSE 143 Lecture 20. Circle CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

CS 101 Spring 2007 Midterm 2 Name: ID:

CS 101 Spring 2007 Midterm 2 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

1 Shyam sir JAVA Notes

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

Aggregation and Composition. [notes Chapter 4]

Aggregation and Composition. [notes Chapter 4] Aggregation and Composition [notes Chapter 4] 1 Aggregation and Composition the terms aggregation and composition are used to describe a relationship between objects both terms describe the has-a relationship

More information

Oracle 1Z0-851 Java Standard Edition 6 Programmer Certified Professional Exam

Oracle 1Z0-851 Java Standard Edition 6 Programmer Certified Professional Exam Oracle 1Z0-851 Java Standard Edition 6 Programmer Certified Professional Exam 1 QUESTION: 1 Given a pre-generics implementation of a method: 11. public static int sum(list list) { 12. int sum = 0; 13.

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Self-Expressive Code. A handbook of write readable code. Stephen Wang. This book is for sale at

Self-Expressive Code. A handbook of write readable code. Stephen Wang. This book is for sale at Self-Expressive Code A handbook of write readable code. Stephen Wang This book is for sale at http://leanpub.com/self_expressive_code This version was published on 2014-04-06 This is a Leanpub book. Leanpub

More information

EJB - ACCESS DATABASE

EJB - ACCESS DATABASE EJB - ACCESS DATABASE http://www.tutorialspoint.com/ejb/ejb_access_database.htm Copyright tutorialspoint.com EJB 3.0, persistence mechanism is used to access the database in which container manages the

More information

More sophisticated behaviour Lecture 09

More sophisticated behaviour Lecture 09 More sophisticated behaviour Lecture 09 Waterford Institute of Technology February 22, 2016 John Fitzgerald Waterford Institute of Technology, More sophisticated behaviour Lecture 09 1/42 Presentation

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

CMSC 132, Object-Oriented Programming II Summer Lecture 6: CMSC 132, Object-Oriented Programming II Summer 2017 Lecturer: Anwar Mamat Lecture 6: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 6.1 Singly

More information

Java Standard Edition 6 Programmer Certified Professional Exam

Java Standard Edition 6 Programmer Certified Professional Exam Oracle 1z0-851 Java Standard Edition 6 Programmer Certified Professional Exam Version: 4.3 Topic 1, Volume A QUESTION NO: 1 Given a pre-generics implementation of a method: 11. public static int sum(list

More information

public int calculatedamage() { // Generate and return the damage inflicted on ship }

public int calculatedamage() { // Generate and return the damage inflicted on ship } CPSC 233 Final exam review Short answer 1: For this question you are to refer to the following Star Trek TM game. The base type of vessel is a starship which has a number of basic attributes and abilities,

More information

COMP 401 Spring 2014 Midterm 1

COMP 401 Spring 2014 Midterm 1 COMP 401 Spring 2014 Midterm 1 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Getting started with Java

Getting started with Java Getting started with Java by Vlad Costel Ungureanu for Learn Stuff Programming Languages A programming language is a formal constructed language designed to communicate instructions to a machine, particularly

More information

Software Construction

Software Construction Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering

More information

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes Department of Civil and Environmental Engineering, Spring Semester, 2016 ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes Name : Question Points Score 1 30 2 40 3 30 Total 100 1 Question

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

// initialize array to true. for (i = 0; i < s; i++) f[i] = true; // get rid of known non-primes f[0] = f[1] = false;

// initialize array to true. for (i = 0; i < s; i++) f[i] = true; // get rid of known non-primes f[0] = f[1] = false; Listing 1: GeneratePrimes.java This class Generates prime numbers up to a user specified maximum. The algorithm used is the Sieve of Eratosthenes. Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya

More information

d. If a is false and b is false then the output is "ELSE" Answer?

d. If a is false and b is false then the output is ELSE Answer? Intermediate Level 1) Predict the output for the below code: public void foo( boolean a, boolean b) if( a ) System.out.println("A"); if(a && b) System.out.println( "A && B"); if (!b ) System.out.println(

More information

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 Binary Search Trees Lecture 23 October 29, 2018 Prof. Zadia Codabux 1 Agenda Ternary Operator Binary Search Tree Node based implementation Complexity 2 Administrative

More information

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct

More information

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Constructor Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT Object Oriented Programming Examiner s Report March 2017 A1. a) Explain what is meant by the following terms:

More information

CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016

CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016 General instructions: CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016 Please wait to open this exam booklet until you are told to do so. This examination booklet has 13 pages.

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

CS 101 Fall 2005 Midterm 2 Name: ID:

CS 101 Fall 2005 Midterm 2 Name:  ID: This exam is open text book but closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts (in particular, the final two questions are worth substantially more than any

More information

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit. Name CS 110 Practice Final Exam originally from Winter, 2003 Instructions: closed books, closed notes, open minds, 3 hour time limit. There are 4 sections for a total of 49 points. Part I: Basic Concepts,

More information

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003 1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 7, 2003 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do not need to

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Debapriyo Majumdar Programming and Data Structure Lab M Tech CS I Semester I Indian Statistical Institute Kolkata August 7 and 14, 2014 Objects Real world objects, or even people!

More information

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison Media Computation Lecture 16.1, December 8, 2008 Steve Harrison Today -- Details of Creating Classes From requirements to classes Creating a class that will simulate a number game Practice going from requirements

More information

Programming II (CS300)

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

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes Department of Civil and Environmental Engineering, Spring Semester, 2017 ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes Name : Question Points Score 1 50 2 30 3 20 Total 100 1 Question 1: 50

More information

CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

More information

Tuesday, November 15. Testing

Tuesday, November 15. Testing Tuesday, November 15 1 Testing Testing Waterfall model show testing as an activity or box In practice, testing is performed constantly There has never been a project where there was too much testing. Products

More information

Learn Gulp. Jonathan Birkholz. This book is for sale at This version was published on

Learn Gulp. Jonathan Birkholz. This book is for sale at   This version was published on Learn Gulp Jonathan Birkholz This book is for sale at http://leanpub.com/learngulp This version was published on 2015-09-02 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean

More information

Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010

Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010 Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010 NAME (Printed) NAME (Signed) E-mail Exam Rules Show all your work. Your grade will

More information

Oct Decision Structures cont d

Oct Decision Structures cont d Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

More information

Composite Pattern - Shapes Example - Java Sourcecode

Composite Pattern - Shapes Example - Java Sourcecode Composite Pattern - Shapes Example - Java Sourcecode In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four

More information

0.8.0 SimpleConsumer Example

0.8.0 SimpleConsumer Example 0.8.0 SimpleConsumer Example Using SimpleConsumer Why use SimpleConsumer? The main reason to use a SimpleConsumer implementation is you want greater control over partition consumption than Consumer Groups

More information

public static void negate2(list<integer> t)

public static void negate2(list<integer> t) See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static

More information

6O03 project report. Main points for the solution. Build a combination possibility tableau. Problem: Page 5, the prime number problem

6O03 project report. Main points for the solution. Build a combination possibility tableau. Problem: Page 5, the prime number problem 1 6O03 project report Problem: Page 5, the prime number problem Main points for the solution The problem is asking a minimum value of k with given a number of the possibility of its prime combination multinomial.

More information

Introduction to Computer Science II (CSI 1101)

Introduction to Computer Science II (CSI 1101) Introduction to Computer Science II (CSI 1101) Professor: M. Turcotte February 2002, duration: 75 minutes Identification Student name: last name: Section: Student number: initials: Signature: Instructions

More information

MODULE 6q - Exceptions

MODULE 6q - Exceptions MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException

More information

Oracle. Exam Questions 1Z Java Standard Edition 6 Programmer Certified Professional Exam. Version:Demo

Oracle. Exam Questions 1Z Java Standard Edition 6 Programmer Certified Professional Exam. Version:Demo Oracle Exam Questions 1Z0-851 Java Standard Edition 6 Programmer Certified Professional Exam Version:Demo 1. Given a pre-generics implementation of a method: 11. public static int sum(list list) { 12.

More information

CIS 110 Introduction to Computer Programming Summer 2017 Final. Recitation # (e.g., 201):

CIS 110 Introduction to Computer Programming Summer 2017 Final. Recitation # (e.g., 201): CIS 110 Introduction to Computer Programming Summer 2017 Final Name: Recitation # (e.g., 201): Pennkey (e.g., paulmcb): My signature below certifies that I have complied with the University of Pennsylvania

More information

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014 Lists CSC212 Lecture 8 D. Thiebaut, Fall 2014 Review List = Organization of Data in a Linear Fashion, where Order is Important Set of actions that can be carried out efficiently on the data. Typical Actions

More information

Last Name: Circle One: OCW Non-OCW

Last Name: Circle One: OCW Non-OCW First Name: AITI 2004: Exam 1 June 30, 2004 Last Name: Circle One: OCW Non-OCW Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot

More information