Sample Midterm CS INSTRUCTIONS: The real exam will be closed books and closed notes. public void foo() throws Up, Fit {... }

Similar documents
Fundamentals of Java Programming

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

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

Java Interview Questions and Answers

CS506 Web Design and Development Solved Online Quiz No. 01

Java Application Developer Certificate Program Competencies

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Syllabus for CS 134 Java Programming

AP Computer Science Java Subset

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Computing Concepts with Java Essentials

History OOP languages Year Language 1967 Simula Smalltalk

Java (12 Weeks) Introduction to Java Programming Language

Java Programming Language

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

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

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Mouse Event Handling (cont.)

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

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

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

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

Inheritance, overloading and overriding

Java SE 8 Programming

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Programming with Java GUI components

Chapter 13 - Inheritance

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

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

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

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

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

LAYOUT MANAGERS. Layout Managers Page 1. java.lang.object. java.awt.component. java.awt.container. java.awt.window. java.awt.panel

Moving from CS 61A Scheme to CS 61B Java

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

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

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

GUI Components: Part 2

Specialized Programme on Web Application Development using Open Source Tools

Description of Class Mutation Mutation Operators for Java

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Chapter 1 Java Program Design and Development

C++FA 5.1 PRACTICE MID-TERM EXAM

Programmation 2. Introduction à la programmation Java

Specialized Programme on Web Application Development using Open Source Tools

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

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

JAVA INTERVIEW QUESTIONS

ICOM 4015: Advanced Programming

Advanced Data Structures

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

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

Object-Oriented Programming in Java

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

C++ INTERVIEW QUESTIONS

Course Title: Software Development

CS193j, Stanford Handout #10 OOP 3

Java CPD (I) Frans Coenen Department of Computer Science

Semantic Analysis: Types and Type Checking

Programming Methods & Java Examples

Install Java Development Kit (JDK) 1.8

JIDE Action Framework Developer Guide

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

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

CIS 190: C/C++ Programming. Polymorphism

Habanero Extreme Scale Software Research Project

Programming and Software Development (PSD)

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

THE OPEN UNIVERSITY OF TANZANIA

D06 PROGRAMMING with JAVA

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

The C Programming Language course syllabus associate level

JiST Graphical User Interface Event Viewer. Mark Fong

Construction of classes with classes

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Contents. 9-1 Copyright (c) N. Afshartous

Glossary of Object Oriented Terms

An Introduction To UML Class Diagrams Classes

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

Java SE 7 Programming

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Java SE 7 Programming

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

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

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

El Dorado Union High School District Educational Services

Visual Basic. murach's TRAINING & REFERENCE

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

Getting Started with the Internet Communications Engine

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Chapter 5 Names, Bindings, Type Checking, and Scopes

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

Part 3: GridWorld Classes and Interfaces

Java the UML Way: Integrating Object-Oriented Design and Programming

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Transcription:

Sample Midterm CS 3230 Name: INSTRUCTIONS: The real exam will be closed books and closed notes. 1. Complete the method definition by filling in the blank: public void foo() throws Up, Fit... public void callsfoo() try foo(); catch (Up u) catch (Fit f) throws f; ans: throws Fit General: Method foo can potentially throw two exceptions: Up and Fit. Both of these are caught but Fit is rethrown in the second catch-block and so must be announced. 2. A Java program contains the following method: int square(int s) s = s * s; return s; What does the following code print out? int length = 5; int area = square(length); System.out.println(length + " " + area); ans: 5 25 General: Java passes all method parameters by value: each method has a local copy of parameter. 1

3. What happens here (assume all necessary constructors and note that the line numbers are not part of the code)? 1. public class Fraction 2. 3. private int num; 4. private int denom; 5. 6. public Fraction mult(fraction f) 7. 8. return new Fraction(num * f.num, denom * f.denom); 9. 10. ----------------------------------------------- 11. Foo f1 = new fraction(); 12. Foo f2 = new fraction(); 13. f1.bar(f2); a. Compiler error on line 8; one object may not access the private features of another object b. Compiler error on line 13; one object may not access the private features of another object c. Compiles but generates a runtime error on line 8 d. Compiles but generates a runtime error on line 13 e. Compiles and runs without error ans: e General: Access control modifiers (e.g., public, private, and protected) are defined at the class level not at the object level. This implies that private does not prevent one instance of a class from accessing the instance variables of another instance of the same class. 4. Upon which class relationship does object casting rely? a. Association b. Aggregation c. Composition d. Inheritance e. Dependency ans: d General: Objects may only be converted or cast if the original and destination classes are related by inheritance (aka generalization). An up-cast is one of three things necessary for polymorphism; the other two are method overriding and inheritance itself. 2

5. A program contains the following definitions and statements: public class Employee private String name; public Employee(String name) this.name = name; public String tostring() return name; public static void change(employee temp) temp.name = "Wally"; ----------------------------------- Employee e = new Employee("Dilbert"); Employee.change(e); System.out.println(e); What is printed? a. Wally b. Dilbert c. The statement temp.name = "Wally"; will not compile d. The statement System.out.println(e); will not compile ans: a temp points to the same object as does e (it becomes an alias for the object). When the object is modified through temp, it modifies the original object. 3

6. A program contains the following definitions and statements: public class Employee private String name; public Employee(String name) this.name = name; public String tostring() return name; public static void change(employee temp) temp = new Employee("Wally"); ----------------------------------- Employee e = new Employee("Dilbert"); Employee.change(e); System.out.println(e); What is printed? a. Wally b. Dilbert c. The statement temp = new Employee("Wally"); will not compile d. The statement System.out.println(e); will not compile ans: b temp initially points to the same object as e, but the statement temp = new Employee("Wally"); causes temp to point to a new object. e is not changed and continues to point to the original object. 4

7. Examine the following two Java classes, the method definition, and the method call: public class Foo... public class Bar extends Foo... mymethod(foo f)... mymethod(new Bar()); Choose the statement below that is the most accurate and the most complete: a. mymethod(new Bar()); will not compile nor will it run. b. mymethod(new Bar()); will compile but it will not run. c. mymethod(new Bar()); causes an object up-cast. d. mymethod(new Bar()); causes an object down-cast. ans: c General: This is the most common syntax resulting in an object up-cast. 8. What gets printed out by the Java code listed below the classes (i.e., below the line; note that the line numbers are not part of the code)? class Animal public String whoareyou() return an Animal ; class Insect extends Animal public String whoareyou() return an Insect ; class Spider extends Insect public String whoareyou() return a Spider ; -------------------------------------------------- 1. Animal a0 = new Insect(); 2. Insect i = new Spider(); 3. Animal a1 = new Spider(); 4. System.out.println(a0.whoAreYou()); 5. System.out.println(i.whoAreYou()); 6. System.out.println(a1.whoAreYou()); a. an Animal, an Insect, a Spider b. an Insect, a Spider, a Spider c. Compile error on line 4. d. Compile error on line 5. e. Compile error on line 6. f. Runtime error on line 4. g. Runtime error on line 5. h. Runtime error on line 6. 5

ans: b General: Java methods are polymorphic by default. The object (on the right of the assignment operator) and not the reference variable (on the left of the assignment operator) determines which method is ultimately called. 9. Examine the classes and the object instantiation below. ans: a,b public class Alpha public int counter; public class Beta extends Alpha public int total; public class Gamma extends Beta public int max; -------------------------------------------- Beta mybeta = new Gamma(); Which of the following statements are valid? Check all that represent a valid instance variable access (note that all instance variables are public): a. mybeta.counter = 0; b. mybeta.total = 100; c. mybeta.max = 200; General: Although mybeta refers to a Gamma object (which does have a max instance variable), mybeta is of type Beta (which does not have a max instance variable). mybeta may access public or protected instance variables that are defined in the classes that are above it in the inheritance hierarchy but not in those classes below it. 6

10. An abstract class may have final methods. Choose the most accurate, relevant, and complete response to this assertion. a. The statement is correct; an abstract class may have concrete methods, which may be final, and which are inheritable. b. The statement is correct; an abstract class may have concrete methods because the final keyword takes precedence over the abstract keyword. c. The statement is INcorrect; abstract classes may not have final methods because final methods may not be overridden. d. The statement is INcorrect; abstract classes may not have final methods because abstract classes may not be instantiated. e. The statement is INcorrect; abstract classes may not have final methods because its methods must be overridden in a subclass. f. The statement is INcorrect; abstract classes may not have final methods because the abstract and final keywords are incompatible. ans: a General: All methods in a final class are final, but an abstract class may contain concrete methods. So what about a final class with abstract methods? Incorrect: The correct answer is (a). b: There are no precedence rules for keywords. c: Final methods may not be overridden, but an abstract class may also have concrete methods, which do not need to be overridden. d: Abstract classes cannot be instantiated but their concrete subclasses may be. e: Only the abstract methods must be overridden in the subclasses; concrete methods do not need to be overridden. f. Abstract and final may not describe the same feature or class; however, in this problem abstract describes a class and final describes one or concrete methods within the class. 7

11. Examine the following class definitions: class Insect public void sting(int howhard)... class Spider extends Insect public int sting(int howhard)... Method sting is a. a correctly overridden method b. a correctly overloaded method c. an erroneously overridden method d. an erroneously overloaded method ans: c General: Overloading takes place within a single class where two or more methods have the same name. This is an example of overriding: two classes related by inheritance define methods with the same name. Overloaded methods may have different return types but overridden methods must have the same return type. 12. What is the relationship between class A and class F illustrated by the UML class diagram? a. Inheritance b. Association c. Aggregation d. Composition e. Dependency ans: d General: This is basically a memorization problem, but do notice some of the similarities and differences. Inheritance and aggregation are both hollow symbols. Aggregation and composition are both four-sided diamonds. The similarity in the shape of the aggregation and composition symbols suggests that the relations are similar. The association symbol is the only one that is not decorated at one end (both ends are the same) and is the only relation that is bidirectional. 8

13. Identify the class relationships illustrated by the following code fragment. class Foo class Bar final Foo f; a. Inheritance b. Association c. Aggregation d. Composition e. Dependency ans: c;d General: In C++ it is possible to distinguish between aggregation and composition. Aggregation is implemented with pointers and composition is implemented with embedded objects (created by static instantiation). In Java, all objects are manipulated by references: there are no static objects. In some cases a Java program can mark the distinction by using the final keyword for an composition. In general, however, the distinction between aggregation and composition in a Java program exists only in the intension of the class designer. The other four relationships are not so ambiguous. 14. Class Bar overrides the Object equals method to test two Bar objects for equality. Choose the correct signature for the Bar equals method. a. public boolean equals(bar other) b. public boolean equals(object other) c. public boolean equals(object other1, Object other2) d. public boolean equals(bar other1, Bar other2) ans: b General: To make a correct override, the overriding method defined in the sub-class must have the same signature (method name, return type, and argument list - number of arguments and corresponding data types) as the overridden method in the super class. Furthermore, the access specifier (i.e., public, protected, private, or default/friendly - no specifier) may not be more restrictive than the method in the super class (though it can be same or less restrictive). The signature of the Object equals method is public boolean equals(object other). 9

15. A programmer wishes to use the Collections.sort method to sort the elements of a list. Each element of the list has both a name (implemented as a String) and an ID number (implemented as an int). In some cases the sort will be by name and in other cases by ID. Which library mechanism should the programmer choose? a. Comparable b. Comparator ans: b See the feedback for the following question. 16. A programmer wishes to use the sort(object[] a) method defined in the Arrays class to sort an array of Foo objects. Choose the best definition for class Foo: a. public class Foo implements Comparator<Foo>... b. public class Foo implements Comparable<Foo>... c. public class Foo extends Comparator<Foo>... d. public class Foo extends Comparable<Foo>... e. public class Foo extends Sortable<Foo>... f. public class Foo... ans: b General: Comparator and Comparable are interfaces that must be implemented, not extended. A class that implements the Comparable interface must define the compareto method, which the Arrays sort method uses to order two objects as a part of the sorting operation. The Comparator interface is used when creating a helper class. An instances of the helper is passed as the second parameter to an overloaded version of the sort method. The first technique is less complex but also less flexible: Use Comparable when you need to sort by one instance variable and use Comparator when you need to do multiple sorts based on two or more instance variables. 17. Given that polymorphism allows a programmer to easily call the methods of a subclass that has been upcast, why is it necessary, as a part of overriding the equals method, to down cast the argument? Choose the most correct and the most complete answer: a. Polymorphism applies only to methods and not to data. b. The statement is incorrect: a down-cast is not necessary. c. The down-cast is necessary to insure that both objects are instances of the same class. d. The down-cast is necessary to insure that one object is not null. ans: a 10

(Goes with the question below) The following two classes are defined in a Java program: public class Employee private String name; private float salary; public Employee(String name, float salary) this.name = name; this.salary = salary; public float calcpay() return salary / 24; // Employee public class Sales extends Employee private float commission; private float totalsales; public Sales(String name) ; public Sales (String name, float salary, float commission, float totalsales) ; public float calcpay() return ; // Sales 18. Choose the best sequence of statements to complete the second Sales constructor? a. super(name, salary); commission = commission; this.commission = commission; this.totalsales = totalsales; b. commission = commission; this.commission = commission; this.totalsales = totalsales; super(name, salary); c. super.name = name; super.salary = salary; this.commission = commission; this.totalsales = totalsales; d. this.name = name; this.salary = salary; this.commission = commission; this.totalsales = totalsales; e. The argument names must be changed so that they are not the same as the instance variable names before the program will compile. 11

ans: a General: name and salary are private instance variables of class Employee so they may not be accessed directly (this rules out c. and d.). The this keyword operates within a class and does not access the super class (this also rules out d.). name and salary must be initialized by the Employee constructor, which is called as super(name, salary) in Sales, but this call must be the first statement in the Employee constructor (this rules out b.). By using the this keyword, instance and local variables may have the same name (this rules out e.). 19. (Note: this is a very difficult question; if used on the midterm, it will be simplified.) Examine the two classes and the object instantiation below. abstract public class Stuff abstract public void firstmethod(); public void secondmethod()... public void thirdmethod()... public class MoreStuff extends Stuff public void firstmethod()... Public void secondmethod()... Public void lastmethod()... --------------------------------------------------------------------------- Stuff more = new MoreStuff(); Check all valid method calls: a. more.firstmethod(); b. more.secondmethod(); c. more.thirdmethod(); d. more.lastmethod(); ans: a,b,c General: The compiler locates instance variables and method names in the symbol table based on the type of the reference variable (i.e., Stuff more); it locates method bodies (i.e., instructions) based on the type of the instantiated object (i.e., new MoreStuff). a. class Stuff defines an abstract method named firstmethod and although it does not have a body, its name is in the Stuff symbol table and polymorphism locates the overridden body defined in class MoreStuff. b. class Stuff defines a method named secondmethod and polymorphism locates the overridden body defined in class MoreStuff. c. MoreStuff inherits method thirdmethod from Stuff, which is called here. d. Stuff does not have a method named lastmethod, which is required for polymorphism - this statement will not compile let alone run. 12

20. Given the following method definition: public void foo(void) throws Bar... If class Bar extends class RuntimeException, must a method calling foo either catch or claim (with the throws keyword) exception Bar? a. Yes b. No ans: b General: Exceptions that extend class Exception or a subclasses of Exception are checked (i.e., they must be caught or claimed with the throws keyword. RuntimeException, a subclass of Exception, is (sorry) an exception: RuntimeException and its subclasses are not checked and so it is not necessary to catch or claim them. Class Error is also an exception (in both senses used here) and although it is not a subclass of RuntimeException, it is also not checked. 21. Consider the following fragments of code and choose the most accurate, relevant, and complete description. (Note that the line numbers are not a part of the code.) 1. public class Foo implements ActionListener, MouseListener 2. 3. public class Bar 4. private Foo f = new Foo(); 5. private JButton button = new JButton( Open ); 6. private JPanel panel = new JPanel(); 7. 8. button.addactionlistener(f); 9. panel.addmouselistener(f); 10. a. There will be a compile error on line 9 because panels may not be a mouse event source. b. There will be a compile error on line 9 as the Foo object f is already listening to button. c. The code will compile and run but the Foo object f will only respond to panel because it registered last and overwrote button. d. It will compile and run without error because is it possible for Foo object f to be a listener to both the button and the panel at the same time. ans: d General: In general, a listener object can listen to multiple event sources and a single event source can send its event to multiple listeners (i.e., the connection between event sources and 13

listeners can be a many-to-many relation). 22. layout managers place components in one of five predefined locations. a. BoarderLayout b. FlowLayout c. GridLayout d. GridBagLayout ans: a General: Different layout managers organize the components they contain in different ways. The BorderLayout organizes them into four narrow border areas around the edges of a frame and into one (generally) larger central area. It s important to know how the four basic AWT managers organize components. 23. layout managers never honor any component s preferred size (i.e., all of the components are stretched to fit the layout manager). a. BoarderLayout b. FlowLayout c. GridLayout d. GridBagLayout ans: c General: The tallest component in the layout manager determines the row height and the widest component determines the column width - all components are stretched to this size. The FlowLayout honors all preferred sizes (i.e., it doesn t stretch any component). BorderLayout honors the preferred height (but stretches the width) of components in the north and south; honors the preferred width (but stretches the height) of components in the east and west; it stretches both the height and width of components in the center. GridBagLayout managers can be configured to honor both height and width, height only, width only, or neither. 24. What is the default layout manager for a JFrame? For a JDialog? For a JApplet? a. FlowLayout, FlowLayout, and BorderLayout b. BorderLayout, BorderLayout, and FlowLayout c. BorderLayout, BorderLayout, and BorderLayout d. FlowLayout, FlowLayout, and FlowLayout ans: c General: The default layout managers of four containers are important: JFrame, JDialog, JApplet, and JPanel. All except JPanel have a BorderLayout by default; a JPanel has a FlowLayout manager by default. 14

25. Describe how to draw a blank Mah Jong tile. Focus on the drawing methods (syntax in not important) and on how the coordinates are identified. What object supports gradient painting and how do you get the object? 26. Describe very generally how to center a picture on the Mah Jong picture tile. 15