CS56—Midterm Exam 2 KEY
E02, S13, Phill Conrad, UC Santa Barbara
05/21/2013
Name: ___________________________________________________
Umail Address: ______________________________@ umail.ucsb.edu
Circle one: 10am 11am
Please write your name only on this page.
That allows me to grade your exams without knowing whose exam I am grading.
This exam is closed book, closed notes, closed mouth, cell phone off,
except for:
- You are permitted one sheet of paper (max size 8.5x11") on which to write notes
- These sheets will be collected with the exam, and might not be returned
- Please write your name on your notes sheet
There are 100 points worth of questions on the exam, and you have 75 minutes to complete the exam.
A hint for allocating your time—on your first pass through the exam:
- if a question is worth 10 points, spend no more than 5 minutes on it
- if a question is worth 20 points, spend no more than 10 minutes on it
- if a question is worth 40 points, spend no more than 20 minutes on it
- etc.
If you do that, after you complete your first pass through the
exam in 50 minutes, you'll still have 25 minutes to:
- revisit any questions where you need more time
- check your work.
THROUGHOUT THIS EXAM: Keep your answers short and to the point, but detailed enough that if you offered them at a Job Interview, the interviewer would know, beyond a reasonable doubt, that you know what you are talking about.
The amount of space given is a hint to the length of answer I'm looking for. Short, and precise. Use Java-specific terms when you can.
When you can't remember the precise term, do your best to describe the concept in general terms, and hope for partial credit.
- (5 pts) Java has "automatic garbage collection". What does this mean?
All objects in Java are allocated on the heap. The JVM keeps track of which objects are reachable from live variables. When an object is no longer reachable, directly, or indirectly, through any live variable, it becomes eligible for "garbage collection", which means the memory it uses is eligible to be reused for other objects. (The JVM may or may not recycle the memory immediately—it might wait for a low memory condition to do so.)
Discussion: 49/50 had answers receiving full credit. One person wrote the following, which received 2/5: (parts in [square brackets] are my comments): "At the end of a method, Java automatically removes memory that is on the stack [TRUE, BUT NOT GC] or was put on the heap by that method [FALSE!]. It deletes data that will no longer be used by the program [TRUE].".
- git allows for "branching" and "merging"
- (4 pts) What does it mean to "create a branch" in a git repository?
A branch is a separate series of commits within the same repository with a name such as PhillsBranch or AddMenu or TrySockets. It is typically given a name that indicates what the branch is for. The default branch is called master.
- (3 pts) Briefly describe a "real world programming" situation where creating a branch would be appropriate.
Answers may vary. Any situation where you need independent work happening within the same repo is a good situation for branch—examples include "fixing a bug" while still working on new development, adding a feature that isn't fully tested yet, two folks doing work in the same file that may want to defer merging their code to a later point in time.
- (3 pts) Write the git command to create a new branch called "FredsBranch".
git checkout -b FredsBranch
OR
git branch FredsBranch
OR
git branch FredsBranch master
Discussion: the checkout version also switches to the new branch. The branch version only creates the new branch. There were 37/50 perfect answers (23, 13 and 1 of the options shown above, respectively.) Of the remaining answers, 9 were small syntax errors in answers close to the correct ones (-1), while 4 were completely wrong (-3), e.g. confusing branching with forking or cloning, or just writing:
git ____ FredsBranch
- (5 pts) In C++, a pointer can point to (and when dereferenced, refer to) an object on the stack, or an object on the heap.
Is the same with references in Java? Explain your answer.
No. All references in java refer to objects,
and all java objects are allocated on the heap.
Discussion: 42/50 perfect answers.
-
Answer each of these questions in the context of Java Swing Programming.
- (10 pts) Suppose that you see that a particular GUI is built with a class FooComponent that extends JComponent and a class FooFrame that extends JFrame. With only that knowledge, explain what the relationship between FooComponent and FooFrame is likely to be, and what the role of each one is (i.e. what kind of code you'd expect to see inside each one.)
Since the FooFrame is a JFrame, it represents a top level window in a GUI. A FooComponent is likely to be an element that is going to be added to the FooFrame, and might be an area of the GUI on which graphics or widgets appear.
Discussion: 43/50 perfect papers. Partial Credit: 1x (-2), 2x (-5) and 4x (-10).
- (10 pts) Give two specific examples of Layout Managers, and describe briefly how each one works. You don't have to have the "exact" name—a close approximation (plus a reasonably accurate description of how it operates) is good enough. (Five points for each answer.)
For three sample answers, consult page 403 in the text, which describes BorderLayout, FlowLayout and BoxLayout.
If you want more examples, this link has some: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
- Name one layout manager here, then briefly describe: ___________________________
- Name one layout manager here, then briefly describe: ___________________________
Discussion: 39/50 perfect papers. Of the rest, 6 got half credit, and 5 got zero credit.
- Continuing with questions about Java Swing. Keep answers short and precise.
- (5 pts) Explain briefly what kind of code you need to write so that when you click on a JButton, something happens—let's keep it simple, and suppose that what is supposed to happen is that "Hello" is printed on standard output. DON'T WRITE THE FULL CODE—just describe at a high level, using Java Swing specific terminology, how all the pieces fit together. You may use "snippets" of code if that helps, but I'm looking for a DESCRIPTION, not an implementation.
(1) Create an object that implements ActionListener (either "this" or an inner class)
(2) Register the actionListener object with the JButton.
(3) Put System.out.println("Hello") in the actionPerformed method.
(See p. 360 in text.)
Discussion: 48/50 perfect papers. The other two got the gist of it, but either used the wrong name or an illegible name in place of ActionListener, so had a 1 point deduction.
- (5 pts) Continuing from the previous problem—sometimes code that handles button presses and other GUI events involves the use of "inner classes". Explain how inner classes are used in this context, and why inner classes are helpful here.
One or more inner class objects can be used to implement one of more ActionListeners that have full access to the outer classes instance variables. This way each ActionListener can be a separate object but you avoid having to expose inner details outside the class (through getters and setters.)
Discussion: 42/50 perfect papers.
- The Java standard library provides classes called Socket and Thread. For each of the items below, Briefly describe a "useful Java programming project" or a "real world Java program" that would need to use either Sockets, or Threads, and why Sockets or Threads are needed.
(Note an "assignment to learn about sockets/threads" is not an acceptable answer here. It needs to be a "real" kind of program.)
- (5 pts) Briefly describe a "useful Java program" that would need Sockets.
Answers will vary. A good answer is an application that needs to communicate over a network or between processes on the same machine.
- (5 pts) Why would that need Sockets?
Answers will vary. A good answer explains what kind of information is being communicated over a network or between processes on the same machine.
- (5 pts) Briefly describe a "useful Java program" that would need Threads
Answers will vary. A good answer is an application that needs to do more than one thing at a time.
- (5 pts) Why would it need Threads?
Answers will vary. A good answer explains why the application needs to do more than one thing at a time.
Discussion: 44/50 perfect papers. Of the ones that were not perfect: 2 didn't know what sockets were, 3 confused thread.sleep()
with threads in general, and 1 used the bank account example from the textbook for threads (which was really more of a metaphor to illustrate syncronization—this student's answer didn't explain why a banking application was a good application of threads.)
- (10 pts) Write a line of Java code that declares a variable
kennel
, and set it equal to an ArrayList
that can only hold Dog
objects.
ArrayList<Dog> kennel = new ArrayList<Dog>(); // perfect answers: 29/50
Some actual wrong answers.
(possible distractors if this becomes a multiple choice question)
- (-1)
ArrayList kennel = new ArrayList<Dog>();
- (-2)
ArrayList<Dog> kennel = new ArrayList<Dog>;
(x4)
- (-2)
ArrayList kennel = new ArrayList<Dog>()
- (-2)
List<Dog> kennel = new ArrayList<Dog>;
- (-2)
ArrayList<Dog> kennel = new ArrayList();
- (-3)
ArrayList<dog> kennel = new ArrayList<dog>;
- (-3)
ArrayList<Dog> kennel = new ArrayList<Dog>
(x2)
- (-3)
ArrayList kennel = new ArrayList<Dog>;
(x2)
- (-4)
ArrayList<Dog> kennel = new <Dog>ArrayList();
- (-4)
ArrayList<Dog> kennel = new ArrayList<>;
- (-5)
ArrayList kennel = new <Dog>ArrayList();
- (-5)
ArrayList<Dog> kennel = new ArrayList
- (-6)
kennel = new ArrayList<Dog>;
- (-6)
Kennel kennel = (Kennel) new ArrayList<Dog>();
- (-8)
Dog kennel = new ArrayList(Dog);
- (-10)
ArrayList [Dog] kennel;
(10 pts) Suppose a line of code inside method public void foo(); can throw an exception called FooException under some circumstances, and further more you know that FooException extends java.lang.Exception (rather than java.lang.RuntimeException).
In this situation, as the author of the code for the method, you must do one of two things, and it is up to you which one to do.
What are those two things?
Option 1:
Put the line of code that can throw FooException in a try/catch block.
Option 2:
Add throws FooException
to the header of method foo()
Discussion: 30/50 perfect papers. Deductions:
- (-1) (x8) for answers that correctly identified both alternatives, but were vague about how to accomplish the second one (referring to "ducking", but not explaining that meant writing "throws FooException" in the header of the method.
- (-5) (x6) for answers where one option was try/catch, and the other option was "modify the code so that it can't throw the exception". That isn't always an option, but the two answers listed above always are.
- (-3) for answers where one option was "try/catch or declare to be thrown", and the other option was "modify the code so that it can't throw the exception". (See answer above. Here I didn't take off as many points, because both correct alternatives were included.)
- (-5) for answers where one option was try/catch, and the other option was "just don't worry about it, and hope the exception doesn't happen." The code won't compile unless you do one of the two things listed in the "correct" answer above.
- (-5) for answers where one option was try/catch, and the other option was "use a finally block". A finally block goes along with a try/catch in some cases—it isn't an alternative to a try/catch block.
- (-5) (x2) for answers where one option was try/catch with FooException, and the other option was try/catch with Exception. Those are really just two variations of the same approach, and leaves out the other important alternative.
- (-10) One paper left this question unanswered.
(10 pts) How would the situation described in the previous question be different if FooException extended java.lang.RuntimeException instead of java.lang.Exception, and even more important, why does Java have this whole other kind of exception?
How the situation would be different if FooException extended java.lang.RuntimeException?
(Hint: the "situation" is the SAME SITUATION as for the previous question, i.e. that you are the author of public void foo() EXCEPT that now FooException extends java.lang.RuntimeException. I am asking: what difference does that make in what you, as the author of the method public void foo must do?)
You don't need to do anything, since it is an unchecked exception. In particular, the
compiler will not force you to use a try/catch or to declare that the method throws an exception.
Why Java allows for this other kind of exception:
RuntimeExceptions (or unchecked exceptions) are used for situations that
should never occur in properly written code such as dereferencing a null pointer, accessing a non-existent element of an array, asking for the color of a pixel outside the bounds of an image, etc. If these errors happen,
they indicate faulty logic in your code, and you should find and fix these problems during testing. It would cause too
much clutter if every time you dereferenced a pointer you had to try/catch for a NullPointerException, and
every time you had to index into an array you had to check for an ArrayIndexOutOfBoundsException.
Discussion: 22/50 perfect papers. An (incomplete) sampling of wrong answers:
- Runtime Exceptions are not checked exception, so
you would not be able to try/catch or thrwo them. FALSE: you can
still try/catch them or declare them to be thrown. You just don't
have to get your program to compile.
- A Runtime Exception is a problem while the code was
running. TRUE BUT IRRELEVANT: All exceptions are problems that occur
when the code is running.
- Java lets you get away with RuntimeExceptions because it knows maybe you can't handle it. FALSE. RuntimeExceptions typically represent logic errors, which you SHOULD be able to prevent!
- Runtime Exceptions are helpful for halting execution of a program when debugging
or trying to prevent corrupt data in a real environment.
TRUE BUT IRRELEVANT: The statement is true of all exceptions.
- Runtime Exceptions are typically issues that you cannot forsee when writing the code. FALSE. They are typically issues that you can and should prevent.
- The program will not be forced to stop if a RuntimeException is thrown. FALSE. It most certainly will, unless the error is caught— and typically we do NOT want to catch RuntimeExceptions. We want to let the program stop, so we can determine the cause and correct the faulty logic.
- Java allows the RuntimeException because sometimes the logic is not the problem, but it calls something that is not there (like a missing file). UNCLEAR. RuntimeExceptions are typically for the case where logic IS the problem, and its the OTHER kind of exception that is for the case where the logic is not the problem, but rather something outside the user's control.
- In this case, as the author, I wouldn't know that the exception is being thrown until the program is run. TRUE BUT IRRELEVANT. You almost never know at compile time whether an exception is going to be thrown. That is not what distinguishes RuntimeExceptions from regular exceptions. (The name is really sort of misleading—they should probably have been called "unchecked exceptions" instead.)
- These type of exceptions don't stop the file from compiling. TRUE BUT IRRELEVANT. I didn't ask about that. I asked a "why" question.
- This type of exception deals with the logic of the program rather than handling special cases. CLOSE BUT TOO VAGUE/INCOMPLETE FOR FULL CREDIT. Compare with the more complete answer shown above.
- RuntimeExceptions are executed when the program is running. TRUE, BUT IRRELEVANT. So are all Exceptions.
- Java allows RuntimeExceptions because code sometimes needs to run through even with mistakes in it. FALSE, OR VAGUE/INCOMPLETE. Typically, the code won't run through—it will halt with an uncaught exception—unless you mean that you can (though you are not required to) catch the RuntimeException. But your explanation didn't go there, so I can't give full credit.
- For exceptions that are prevalent. NOT EXACTLY. It is not the exceptions that are prevalent, but the code that can, under some circumstances, through an exception. For example, every invocation of a non-static method involves de-referencing a reference (pointer) which could be null. That kind of code is prevalent. However, in well-written code, we would hope that the RuntimeException itself (e.g. the NullPointerException) is NOT prevalent, but rare.
- Some code messes up during runtime and can not be checked if faulty before runtime. TRUE BUT IRRELEVANT. In general, predicting the path that code will take (e.g. whether it goes into an infinite loop) is an undecidable problem. But that has nothing to do with the reason why Java provides for unchecked exeptions.
- A RuntimeException is thrown when code is actually running rather than when it is compiles.TRUE BUT IRRELEVANT, because that is true of all Exceptions.
- RuntimeExceptions are useful when you're not exactly sure when the error is going to happen. For instance, if your internet is out when using a chat program, a RuntimeError would be used to handle it. FALSE; INDEED, EXACTLY THE OPPOSITE. For that situation, you should have a checked exception, because that is something the program author should anticipate as a possibility, and be prepared to handle with a graceful exit (e.g. a nice error message) rather than the output that results from an unchecked exception
- RuntimeExceptions are the result of (usually) syntax typos. FALSE. Syntax errors mean the program doesn't compile.
- You don't have to deal with RuntimeExceptions if you don't want to; they can just be ignored. NOT EXACTLY. The exceptions cannot be ignored. What can be ignored, if you are reasonably confident your code is correct, is the possibility of runtime exceptions resulting from indexing into arrays, dereferencing pointers (references), etc. That is not the same thing as ignoring the exception. You DO have to deal with the exception, usually by fixing the logic error that caused it in the first place.
End of Exam
Total points: ?