Programming Methods & Java Examples



Similar documents
Computing Concepts with Java Essentials

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

The Interface Concept

Creating a Simple, Multithreaded Chat System with Java

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Fundamentals of Java Programming

Building a Multi-Threaded Web Server

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

CS330 Design Patterns - Midterm 1 - Fall 2015

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

Java Interview Questions and Answers

Specialized Programme on Web Application Development using Open Source Tools

Java Application Developer Certificate Program Competencies

Java (12 Weeks) Introduction to Java Programming Language

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

History OOP languages Year Language 1967 Simula Smalltalk

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

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

Lab Experience 17. Programming Language Translation

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

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

COMP61532 Pattern-based Software Development Liping Zhao John Sargeant Comments. Please see the attached.

Java SE 8 Programming

1 Hour, Closed Notes, Browser open to Java API docs is OK

Effective Java Programming. measurement as the basis

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Syllabus for CS 134 Java Programming

Mail User Agent Project

Explain the relationship between a class and an object. Which is general and which is specific?

The Walters Art Museum. Mathematics STAINED GLASS DRAWING

ACTIVITY 6: Falling Objects

CPS122 - OBJECT-ORIENTED SOFTWARE DEVELOPMENT. Team Project

Lecture 7: Class design for security

INPUT AND OUTPUT STREAMS

Netbeans IDE Tutorial for using the Weka API

CPS122 Lecture: State and Activity Diagrams in UML

16 Collection Classes

Using Inheritance and Polymorphism

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

AP Computer Science Java Subset

El Dorado Union High School District Educational Services

C++FA 5.1 PRACTICE MID-TERM EXAM

Specialized Programme on Web Application Development using Open Source Tools

Lesson 8: Simon - Arrays

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Getting Started with the Internet Communications Engine

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

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

Math 4310 Handout - Quotient Vector Spaces

Introduction to Programming System Design. CSCI 455x (4 Units)

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

How To Draw A Cell Phone Into A Cellphone In Unminimal Diagram (Uml)

Java EE Web Development Course Program

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Japan Communication India Skill Development Center

CSE 1020 Introduction to Computer Science I A sample nal exam

Glossary of Object Oriented Terms

Action settings and interactivity

6.080 / Great Ideas in Theoretical Computer Science Spring 2008

Crash Course in Java

DC60 JAVA AND WEB PROGRAMMING JUNE b. Explain the meaning of the following statement public static void main (string args [ ] )

CS 1133, LAB 2: FUNCTIONS AND TESTING

Java SE 7 Programming

Regular Expressions and Automata using Haskell

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

WRITING DATA TO A BINARY FILE

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

C++ Programming Language

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

ECE 122. Engineering Problem Solving with Java

Pushes and Pulls. TCAPS Created June 2010 by J. McCain

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

Japan Communication India Skill Development Center

Colour by Numbers Image Representation

COURSE SYLLABUS EDG 6931: Designing Integrated Media Environments 2 Educational Technology Program University of Florida

Japan Communication India Skill Development Center

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

arrays C Programming Language - Arrays

How To Write A Program For The Web In Java (Java)

Lecture 1 Introduction to Android

Software Development. Chapter 7. Outline The Waterfall Model RISKS. Java By Abstraction Chapter 7

Object Oriented Design

Java from a C perspective. Plan

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Schema Classes. Polyhedra Ltd

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CS 106 Introduction to Computer Science I

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Android Application Development Course Program

Official Android Coding Style Conventions

C++ INTERVIEW QUESTIONS

Introducing Variance into the Java Programming Language DRAFT

Using Dedicated Servers from the game

Part 1 Foundations of object orientation

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

Java CPD (I) Frans Coenen Department of Computer Science

An Overview of Java. overview-1

An Incomplete C++ Primer. University of Wyoming MA 5310

Transcription:

Programming Methods & Java Examples Dr Robert Harle, 2009 The following questions may be useful to work through for supervisions and/or revision. They are separated broadly by handout, but borders are necessarily blurred. Since there is no Java lecture course, I have included some Java questions that pick up on points in the ticks. There are no past exam questions for the Programming Methods & Java question on CST Paper 1 so the course website will also feature some sample tripos-esque questions for you to download and try. Some of these questions are more involved than others - roughly speaking they start quick and easy and finish tougher in each section. An asterix by any question or part of a question indicates that the answer may need more than you ve been explicitly taught. Consult your supervisor for a sensible subset to attempt. Handout 1: Bouncing Ball 1. Imagine you have been given software that predicts the weather next year by simulating all the physical processes that the software authors felt relevant. The software predicts that it will rain next week. What could you do to decide whether or not to trust the simulation? 2. A student wishes to have an equivalent class to Vector2D for a 3D vector. She argues that because a 3D vector is a 2D vector with a bit extra (z), it should derive from Vector2D. Comment on this. 3. In Vector2D.java, the member variables are all private. This means that any derived classes cannot reference them directly. Is this a problem? 4. Explain what a marker interface is and find an example in Java that is not the interface Cloneable. 5. A student forgets to use super.clone() in their clone() method: public class SomeClass extends SomeOtherClass implements Cloneable { private int[] mdata;... public Object clone() { SomeClass sc = new SomeClass(); sc.mdata = mdata.clone(); What could go wrong? 1

6. Vector2D provides methods to add two vectors. Contrast the following approaches to providing an add method assuming Vector2D is (i) mutable, and (ii) immutable. (a) public void add(vector2d v) (b) public Vector2D add(vector2d v) (c) public Vector2D add(vector2d v1, Vector2D v2) (d) public static Vector2D add(vector2d v1, Vector2D v2) 7. A student proposes to modify the bouncing ball simulation to use a time step that can vary in length dynamically. They argue that this will allow the simulation to continue rather than die abruptly when the bounces become too small for the current time step. Comment on this approach. 8. An alternative strategy to clone()-ing an object is to provide a copy constructor. This is a constructor that takes the enclosing class as an argument and copies everything manually: public class MyClass { private String mname; private int[] mdata; // Copy constructor public MyClass(MyClass tocopy) { this.mname = tocopy.mname; // TODO... (a) Complete the copy constructor. (b) Make MyClass clone()-able (you should do a deep copy). (c) * Why might the Java designers have disliked copy constructors? [Hint: What happens if you want to copy an object that is being referenced using its parent type?]. (d) * Under what circumstances is a copy constructor a good solution? 9. Consider the class below. What difficulty is there in providing a deep clone() method for it? public class CloneTest { private final int[] mdata = new int[100]; 10. (*) Rewrite the basic bouncing ball simulator (where the floor is static) to work with a-priori event detection. 11. Modify the bouncing ball simulation so that the ball is given some horizontal velocity intially. With each bounce the horizontal speed should be reduced in a similar fashion to the vertical speed. Handout 2: Design Patterns 12. Explain the difference between the two types of polymorphism in programming.

13. Imagine you have two abstract classes: Employee (which implements everything associated with being an employee) and Ninja (which implements everything needed to be a ninja). If you have employees who are also ninjas, you would presumably want to write: public class NinjaEmployee extends Ninja, Employee {... This is called multiple inheritance. Suggest why it isn t supported in Java (Hint: multiple inheritance of interfaces is supported so what s the difference?) 14. Suppose you have an abstract class TeachingStaff with two concrete subclasses: Lecturer and Professor. Problems arise when a lecturer gets promoted because we cannot convert a Lecturer object to a Professor object. Using the State pattern, show how you would redesign the classes to permit promotion. 15. Describe how Java I/O makes use of the Decorator pattern (e.g. Look at java.io.reader and java.io.inputstreamreader). 16. A drawing program has an abstract Shape class. Each Shape object supports a draw() method that draws the relevant shape on the screen. There are a series of concrete subclasses of Shape, including Circle and Rectangle. The drawing program keeps a list of all shapes in a List<Shape> object. (a) Should draw() be an abstract method? (b) Write Java code for the function in the main application that draws all the shapes on each screen refresh. (c) Show how to use the Composite pattern to allow sets of shapes to be grouped together and treated a a single entity. (d) Which design pattern would you use if you wanted to extend the program to draw frames around some of the shapes? 17. In the Java GUI Libraries, each component has a LayoutManager that determines how any child components it has will be laid out on screen. For example, GridLayout is a concrete LayoutManager that sets things out in a uniformly-sized grid, whilst BorderLayout is also a concrete LayoutManager that lays out one main component and four others along its sides. Identify the design pattern in use here. 18. Explain using diagrams how to the Abstract Factory pattern would help in writing an application that must support different languages (english, french, german, etc). 19. One technique to break a Singleton object is to extend it and implement Cloneable. This allows Singleton objects can be cloned, breaking the fundamental goal of a Singleton! Write a Java Singleton class that is not final but still prevents subclasses from being cloned.

20. Assume there is a machine somewhere on the internet that can supply the latest stock price for a given stock. The software it runs is written in Java and implements the interface: public interface StockReporter { public double getstockprice(string stockid); You are given a Java class MyStockReporter that implements this interface for you. When you use a MyStockReporter object, your request is passed onto the real machine. (a) Identify the design pattern (b) Why is this design inefficient? (c) Draw a UML class diagram and a sequence diagram to explain how the Observer pattern could improve efficiency. Give the changes to the interface that would be required. Handout 3: Photo Organiser 21. Why are interfaces useful in decoupling classes? 22. Explain why it is rarely possible to fully decouple the View from the Controller in the MVC pattern. 23. Describe how Java swing makes use of the MVC, Composite and Observer patterns. 24. The Photo class in the lectures does not behave sensibly if we provide a bad filename for the photo. Alter the program so that when a bad filename is given, a message will alert the user to the mistake rather than continuing regardless. 25. * Write a view component for the Photo Organiser that lists all of the photos in the organiser by filename, sorted alphabetically. Handout 4: Web Server 26. The sendheader() method in HTTPConnection.java uses a boolean return value to indicate success or failure. Discuss the advantages and disadvantages of using exceptions instead. 27. Explain the notion of a thread. Why do threads make programming harder?

28. HTTPConnection needs to read in a requested file from the disk and send it out to the browser. The code supplied does so byte-by-byte: DataOutputStream output = new DataOutputStream(mSocket.getOutputStream()); while (true) { int b = requestedfile.read(); if (b == -1) { break; //end of file output.write(b); It is also possible to read chunks of data in one go using the read(byte[] b) method of InputStream. Investigate the use of this method. Test your code to determine whether reading and sending chunks is more efficient than doing so byte-by-byte. 29. * Look again at the code in the previous question (a) Why does a Java InputStream not throw an exception for the end of file, instead of relying on a return value of -1? (b) Why does read() return an int when it only holds a byte (0 255)? 30. Write a simple program that creates two threads. Each thread should loop forever, printing out Thread X where X is either 1 or 2, depending on the thread which wrote it. What do you notice about the order of printing when you run it? 31. * Write a client that connects to the WebServer in lectures and acts like a browser requesting an HTML file. 32. * Write a server/client pair to handle a multi-user chat. Clients should connect to the server, and anything typed locally should be relayed to the server, which should use the observer pattern to relay it to all other connected clients. Handout 5: Simple Computer Vision 33. Why are the member variables in Pixel.java declared final? 34. Explain what caused the StackOverflowException seen in the lectures. Write a toy program that results in a StackOverflowException.

35. The user of the class Car below wishes to maintain a collection of Car objects such that they can be iterated over in some specific order. public class Car { private String manufacturer; private int age; (a) Show how to keep the collection sorted alphabetically by the manufacturer without writing a Comparator. (b) Show how to keep the collection sorted by {manufacturer, age. i.e. sort first by manufacturer, and sub-sort by age.