Download CMSC 132 Exam review Questions with 100% Correct Answers | Verified | Latest Update 2024 and more Exams Advanced Education in PDF only on Docsity! CMSC 132 Exam review Questions with 100% Correct Answers | Verified | Latest Update 2024 What do you find in a java interface? - Correct Answer-method prototypes, final static variables, static methods (note: instance methods are ok if you use the term 'default'). The classes that implement an interface must implement ___________ - Correct Answer- Instance methods from interface (note: default instance method does not need to be implemented, it has already been inherited). When should you use the key word 'Override'? - Correct Answer-When you are implementing a method from an interface. If there is default implementation of a method you can use override to implement it differently. (reminder: if it is already implemented in the interface, you do not need to implement it in a different class because it has already inherited it). pg. 1 professoraxe l (T/F) - You can add other code to the classes that inherit the superclass features aside from the interface method implementations. - Correct Answer-TRUE (T/F) you cannot create polymorphic collections - Correct Answer-FALSE What does API stand for and what is it? - Correct Answer-Application Programming Interface, the API is part of a model that are exposed to the user (public features). For example, when you write projects you use the String class, it has an API which are the features from that class available to users. Overall in an API you find public variables, public methods, and the contracts of the methods. What did Fawzi mention is important to remember in regards to the API? - Correct Answer-When changing code, make sure to leave the API the same so the outside user doesn't have anything to worry about. pg. 2 professoraxe l deprecated version? - Correct Answer- ArrayList<Cat> x = new ArrayList<>(); (note: the deprecated version does not specify what type of object goes into the list, if you were to add a Dog to Cat list, it would still compile but an exception will be thrown if you try to remove the Dog object). What are some methods in the collections class? - Correct Answer- Collections.shuffle(list) - shuffles an array list int max = Collections.max(list) - returns max + few more spoken about in lecture What is found in an enumeration? - Correct Answer-An enum is like a class, there are a small number of pre-defined instances, identified with "symbolic constants". example: public enum Day { Sun, Mon, Tues, Wed, Thurs, Fri, Sat; } pg. 5 professoraxe l How would you access objects from an enumeration named 'Day' ? - Correct Answer-If you wanted to access Monday you type: Day.Mon Day is the name of the enum, Mon is the object (T/F) with enumerations you should not use .equals method, use double == - Correct Answer-TRUE How can we generate an array representing the pre defined constants in an enumeration? - Correct Answer-.values() method can be called on an enum, it returns an array of the enums instances. How would the compareTo() method work when used on enumerations? - Correct Answer-its return value is based on the order you typed the Days in. So Monday will be greater than Wednesday since it was typed first. What method can be used to return the index of an instance in an enumeration? - Correct Answer-.ordinal() example: Day.TUE.ordinal() returns the index of Tuesday (note: Day.values()[3] will return the day at the specified index) pg. 6 professoraxe l What can an enumeration consist of? - Correct Answer-- enumerations are almost the same as classes they can have instance members (variables and methods) -they can have static members (variables and methods) -you can give them states/behaviors (T/F) constructors for enumerations are always public - Correct Answer-FALSE (T/F) enumerations have a fixed number of objects defined inside. - Correct Answer-TRUE What is an iterator? - Correct Answer-Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Methods from Iterator interface include: hasNext(), next(), remove() Explain how to use next() method from the Iterator interface - Correct Answer-The iterator goes through each element of collection one by one, when you call next() method it moves the marker forward to the next element and returns an element. pg. 7 professoraxe l "Exposing private mutable data is typically a ____________" - Fawzi - Correct Answer-privacy leak How does the compareTo(T other) method work? - Correct Answer-- if current object and parameter are equal, this method returns 0 - if current object is bigger than parameter, this method returns positive value - if current object is smaller than parameter, this method returns negative value The ________________ interface defines the "natural order" for instances of the class. It is used in hundreds of places in java libraries including Collections.sort, Collections.max, Collections.min, Collections.binarySearch, Arrays.sort, Arrays.binarySearch. - Correct Answer-Comparable A class called Dog extends a class called Animal, this means a Dog Is-A ____________. - Correct Answer-Animal A class called Dog extends a class called Animal, this would make Dog the _____ class and Animal the __________ class. - Correct Answer-sub, super pg. 10 professoraxe l (T/F) inheritance can allow you to take advantage of polymorphism. - Correct Answer-TRUE Imagine there is a class called Bird and 2 classes that directly extend it are Eagle and Turkey. Additionally there is a class called Bald Eagle that extends Eagle. What kinds of objects can b represent? public void takeBath(Bird b) {....} - Correct Answer-b can represent a Bird, Eagle, Bald Eagle, or a Turkey If a class called Bird extends a class called animal, and a class called Turkey extends Bird, What does Turkey inherit from Bird? - Correct Answer- Turkey will inherit any methods Bird inherited from its superclass as well as any additional methods in the Bird class. (note: Turkey which is a subclass of Bird inherits the overridden methods within Bird rather than the methods from Birds superclass.) //if you are confused watch lecture #11 pg. 11 professoraxe l What is allowed in a java class? What is not? - Correct Answer-Instance variables, static variables, instance method implementations, static method implementations, instance method prototypes with no code that are declared "abstract", constructors, unlimited number of instances. Cannot have instance method prototypes with no code that aren't declared "abstract." What is allowed in a java interface? What is not? - Correct Answer-Final static variables, instance method implementations declared as default, static method implementations, instance method prototypes with no code. Cannot have constructors or any number of instances. What is allowed in a java enumeration? What is not? - Correct Answer-Instance variables, static variables, instance method implementations, static method implementations, private constructors only, fixed number of instances. Cannot have instance method prototypes without code, does not have unlimited instances, constructors cant be public. pg. 12 professoraxe l A class can only extend ________ other class. But a class can implement multiple ___________(s). - Correct Answer-one, interface class X extends Y implements A, B, C {...} (T/F) An instance of X is only "class X" - Correct Answer- TRUE When is x == y true? - Correct Answer-when x and y are the same object (aliases) When is x.equals(y) true? - Correct Answer-when x and y are objects that look the same (same state). When is c.contains(a) true? (c is a collection) - Correct Answer-It is true if there is an object in the collection that "looks" the same as the argument a. (T/F) The "default" implementation of equals (inherited from object class) is the same as == - Correct Answer-TRUE (Note: because the default implementation of the equals method works the same as ==, it is important to override it and implement it differently if needed.) pg. 15 professoraxe l Study the proper equals method found in lecture..... - Correct Answer-13... Sorry the example for the proper equals method is too big to put on Quizlet. Let's say there is a class called Student that extends Person. Which of these are ok? a) Person x = new Student(); b) Student y = new Person(); - Correct Answer-Option a works because x is polymorphic. Option b does not work because a person is not a student. Let's say there is a class called Student that extends Person and we write: Student s = new Student(); Person p = s; //Person has instances such as name and ID //Student has year and GPA what objects will we be able to access if we use s? - Correct Answer-The whole thing. This includes name, ID, year, and GPA which belong to the Person class and Student class. pg. 16 professoraxe l Let's say there is a class called Student that extends Person and we write: Student s = new Student(); Person p = s; //Person has instances such as name and ID //Student has instances such as year and GPA which of these objects will we be able to access if we use p? - Correct Answer-p can only access the features belonging to the Person class (name and ID number). In an instance method (or constructor) of student class, what is "this"? - Correct Answer-"this" sees the object as the class it was declared in In an instance method (or constructor) of student class, what is "super"? - Correct Answer-"super" sees the object as the superclass of the current class How do "this" and "super" behave in memory? - Correct Answer-'this' is referring to a whole object including features inherited from a potential superclass, 'super' is only referring to features from super class when called inside a subclass. pg. 17 professoraxe l What is found in the object class? - Correct Answer-clone(), toString(), equals(Object obj), finalize(), getClass(), hashCode(), notify() (T/F) every single object you write inherits the code from the object class. - Correct Answer-TRUE Class vs Type - Correct Answer--every object has exactly one class -the class of an object cannot change -objects may be of many types Lets say there is a class called GradStudent that extends Student, and Student extends Person. a) Is this statement allowed? Person p = new GradStudent(); b) what is the class of the instantiated object? - Correct Answer-a) Yes, it is allowed because a grad student is a person. b) grad student is the class. pg. 20 professoraxe l Define overloading - Correct Answer-Two or more methods in a class have the same name but different parameters. Define overriding - Correct Answer-Subclass "replaces" inherited method from superclass with the exact same prototype, but different implementation. Suppose there is a class called Student that extends class Person and they both contain a method walk(); Person p = new Student(); p.walk(); //explain early binding/static binding in this context. - Correct Answer-the compiler decides everything, it checks to see what type of variable p is and based on that they will bind that piece of code to the walk() method in the Person class. So this decision of what method is called is decided early during compilation, before the code has even run. Suppose there is a class called Student that extends class Person and they both contain a method walk(); pg. 21 professoraxe l Person p = new Student(); p.walk(); //explain late/dynamic binding in this context. - Correct Answer-The decision of what method will get called is made during run time, while the program is running and java gets to that line, it checks where the object p is at this moment and sees what class it is and then call the method from that class. We see that p is a new student so it will use the walk method from the student class. Advantages of early binding - Correct Answer--decision is made in the beginning so run time is a little bit faster -it is easier to understand What's better about late binding? - Correct Answer-The same line can be used to call different walk methods, it just depends on the class of the current object. We can take advantage of polymorphism. Does java have early binding or late binding? - Correct Answer-java has late/dynamic binding pg. 22 professoraxe l (T/F) Down casting can be done implicitly - Correct Answer- FALSE. Down casting is never done implicitly by compiler. Person p = new Person(); Student s = new Student(); Person tricky = new Student(); Wont compile, throws exception, or works fine? a) Person y = s; b) Student y = p; c) Student y = (Student)p; d) Student y = tricky; e) Student y = (Student)tricky; f) (Faculty)s g) (Faculty)tricky - Correct Answer-a) implicit upcast - works fine b) attempted downcast - wont compile c) compiles, but throws exception d) downcast - does not compile e) works fine f) does not compile g) compiles, but throws exception pg. 25 professoraxe l Lets say there is a class called Student that extends a class called Person and we write: Student s = .....; Person p = (Person)s; Is this up casting or down casting? will it work? - Correct Answer-This is upcasting and it will work without any issues. Lets say there is a class called Student that extends a class called Person and we write: Person p = ......; Student s = (Student)p; Is this up casting or down casting? will it work? - Correct Answer-This is down casting. It compiles but will throw an exception during run time if the object p on the heap is not type student, if it is type student than this will work without any issue. Lets say there is a class called Student that extends a class called Person and we write: pg. 26 professoraxe l Person p = ......; Student s = (Student)p; How can we make sure this down cast will not throw any exceptions? - Correct Answer-if (p instanceof Student) { Student s = (Student)p; } (instanceof helps guarantee it will not throw a class caste exception) Does java allow multiple inheritance? - Correct Answer-NO. Inheritance vs Composition - Correct Answer-Inheritance - a Student "is-a" Person student has direct access to all the features of the Person class. Allows polymorphism + rigid design decision. Composition - a Student "has-a" Person student has indirect access to the features of the Person class. Does not allow polymorphism, flexible design. pg. 27 professoraxe l -package access levels of: 'private' - Correct Answer-public features can be accessed: -class Can you override a variable that is inherited? - Correct Answer-Yes it is called shadowing. Not a good idea to do that... Features of abstract classes - Correct Answer-- Cannot be instantiated directly, (cannot write Foo f = new Foo()) - May include abstract methods (similar to an interface) ex: public abstract void doSomething(); (any class containing an abstract method must be declared abstract) Abstract classes vs Interfaces - Correct Answer-Abstract classes: - instance variables (state) - constructors pg. 30 professoraxe l Interfaces: - a class can implement more than one (favor interfaces) More details about abstract classes with example - Correct Answer-Let's say we have an abstract class called Shape. Shape has an abstract method declared inside called drawMe(), it passes down the abstract method drawMe to be over ridden in the subclasses. Every shape must have an available draw me method. Features of abstract class example - Correct Answer-There is an abstract class Shape, it has private instance variables, constructor, getters, and lastly we see an abstract method prototype that will be implemented later in the classes that extend Shape. Describe what the key word 'super' does, you may use this example for context: public Square(int x, int y, Color color, int size) { super(x, y, color, size, 1.0); pg. 31 professoraxe l } - Correct Answer-Rectangle is the superclass of Square. When we call super here it will call the constructor from the Rectangle class and we can pass the correct parameters. If a class implements the comparable interface it has to have...? - Correct Answer-A compareTo method that defines the natural order of the class. If you have a class that implements the Comparable interface and defines the natural order inside of the class (with the compareTo method), how would you be able to write an additional compare method if you wanted to order your objects differently from the natural order? - Correct Answer-You could create a separate class (implementing Comparator) which can be provided to define additional orderings. The Comparator interface has one method called compare that expects 2 parameters. ex: public class PlanetMassComparator implements Comparator<Planet>{ public int compare (Planet a, Planet b){ pg. 32 professoraxe l trace in the console that tells you what went wrong. (We do not want this). Example (how would you handle this?): You see a method that passes an array list of Integer objects. The method will find the smallest one and return it. But what if the list that gets passed as a parameter is empty? - Correct Answer-This would be a situation where you would want to use a try/catch block: try{ list.remove(findSmallest(list)); } catch (IllegalArgumentException e) { } (leaving the inside of the catch block empty is called 'no op' aka no operation) What does the finally block do? - Correct Answer-As we leave the try catch, if there is a finally block it will ALWAYS run. This block can be used to close buffers, and make sure nothing is broken if we terminate in the middle of a process. pg. 35 professoraxe l (note: even if the try block doesn't catch any exceptions, the finally will always run). What are the unchecked exceptions we saw in lecture? - Correct Answer-- OutOfMemoryError, StackOverflowError (these are both errors) - IllegalStateException, NullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundsException (these are runtime exceptions) What are the checked exceptions we saw in lecture? - Correct Answer-SQLException, IOException, FileNotFoundException Ex: situations where exceptions will occur (1/2 unchecked exceptions). - Correct Answer-- A Null pointer exception can occur when you forget to instantiate (keyword new). - An index out of bound exception can happen when you are trying to put something in at an index number that it outside the bounds of the array. Ex: situations where exceptions will occur (2/2 checked exceptions). - Correct Answer-- A file not found exception can happen when your program is supposed to operate on a file and the file is not there. pg. 36 professoraxe l - An IO exception (very general) is related to input/output. For example, if you are trying to read data from a different computer and some issue occurred on their end. This is not in the control of the programmer. - A SQL exception - java can be used to interact with the sequel data base, this can be thrown if the sequel data base throws an error. What are the two unchecked exceptions that are used when there is a possibility of running out of resources on a local machine? - Correct Answer-OutOfMemoryError and StackOverflowError (T/F) You are less likely to write catch blocks for checked exceptions. - Correct Answer-FALSE. You are less likely to write catch blocks for unchecked exceptions. Important things to note about unchecked exceptions. - Correct Answer-a) Should not ever happen - usually caused by programming errors b) They are not typically caught - (they shouldn't normally be thrown with a correct implementation) pg. 37 professoraxe l } Things to know about static nested classes public class A { private static class B { ...... } } - Correct Answer-- Rarely used - It is like having 2 ordinary classes - They are typically private because it is most likely used for class A. - Privacy is not respected between class A and class B How would you instantiate a static nested class? - Correct Answer-OuterClass.NestedClass name = new OuterClass.NestedClass(); (note: this answer is supposed to be on one line^) Features of inner classes public class A { pg. 40 professoraxe l public class B { ...... } } - Correct Answer-- Privacy is not respected between class A and class B (like static classes) - Each B object must be 'associated with' a particular A object - When B is constructed (new), connection with A object is established - The B object has immediate access to the A object's members - The A object has no special access to the B object What outer class object is innerGuy connected to? public class A { public class B { ........ } public void foo(){ B innerGuy = new B(); } pg. 41 professoraxe l } - Correct Answer-When we call the foo method (which is in class A), there is always a current object invoking the foo method, and inside foo when we make the new B object, it gets hooked onto the current A object. public class A { public class B { ........ } } //A outerGuy = new A(); What is the syntax for making a class B object that's connected to this particular A object seen above as a comment? - Correct Answer-A.B servicer = outerGuy.new B(); Where are some places you would use an inner class? public class A { public class B { ...... } pg. 42 professoraxe l What can you put inside an anonymous inner class? - Correct Answer-The definition of the class including instance variables, instance methods, static things etc. Except there will not be any constructors inside the class. (T/F) It makes sense to create a shallow copy of an immutable member. - Correct Answer-TRUE. __________ objects require deep copies in order to avoid aliasing. - Correct Answer-Mutable (T/F) String objects are immutable and do not require deep copies. - Correct Answer-TRUE. What are the two ways to copy an object? - Correct Answer-- copy constructor (if there is one) - clone method (returns copy of the object) What kind of copy is made if you call the super class version of clone on an object? - Correct Answer-Shallow copy In order for a user to call the clone method on your objects... - Correct Answer-your class has to implement the cloneable interface. pg. 45 professoraxe l What happens if your class does not implement the cloneable interface but the user tries to call the clone method? - Correct Answer-JVM will throw CloneNotSupportedException (T/F) Your class does not always extend another class. - Correct Answer-FALSE. Your class ALWAYS extends something. (T/F) If the super class of your class is not cloneable, then you cannot make your class cloneable. - Correct Answer- TRUE. (it has to be a chain) To make your class "Cloneable" you must: - Correct Answer-- Ensure that the superclass of your class is the Object class or implements cloneable. - Include "implements Cloneable" at the top of your class. - Carefully override the clone method. Can you use the clone method to create a deep copy? - Correct Answer-Yes, you must override the method and implement it in a way that will create a deep copy. (If needed check lecture 31 to see code for overriding the clone method). pg. 46 professoraxe l What are the 2 kinds of initialization blocks? - Correct Answer-- static initializer - instance initializer Things to know about static initializers public class Foo(){ static { ...... } } - Correct Answer-- Any code written inside the static initializer will run exactly one time. When does it run? when we run the foo class. - they are used to initialize static data - used often Things to know about instance initializers public class Foo(){ { } pg. 47 professoraxe l (T/F) A java program is a process that usually involves 6 or 8 threads all running at the same time. - Correct Answer- TRUE. Procedural Programming Flow (steps) - Correct Answer-- Main thread begins executing statements (in main method) - Main thread executes statements sequentially until main method is popped off the call stack - Main thread dies then program terminates What are common container classes? - Correct Answer- JFrame - a window JPanel - rectangular region with no border JScrollPane - region with scroll bars JDialog - quick and easy dialog box When creating a GUI, what is something you can use to help reposition things inside a window when the windows size changes? - Correct Answer-You can use layout managers What are some different layout managers in java? - Correct Answer-Border layout - top, bottom, left, right, and center sections Box layout - one row or one column pg. 50 professoraxe l Flow layout (default) - lays things out in a row. When space runs out it creates a second row etc. Grid bag layout - grid where you can do fancy tweaks (useful) names not testable ^ What is a timer? - Correct Answer-Timers can be used to create a pause in your code. They are very useful when programming games because you need pauses at certain moments. explain the syntax of this timer: Timer timer = new Timer(1000, new MyListener()); timer.start(); - Correct Answer-The 1000 represents one second, and when the code reaches this point it will wait one second and then run the code inside the listener MyListener. When does java call the paint method? - Correct Answer- Anytime the GUI needs to be re drawn. (Paint method can be overridden and it allows custom drawing into panel). pg. 51 professoraxe l (T/F) When thinking about complexity, log curves have slower runtimes than parabolas. - Correct Answer-FALSE. Log curves are faster because as the data size increases, time (y axis) is staying low. (T/F) Exponential function graphs are not necessarily desirable. - Correct Answer-TRUE. They are not desirable because time is increasing very fast as the data increases. (sometimes there is no better algorithm and they are fine). What does the function/graph look like based on the given example? (example found in lecture 37) Double all values in an array of size n. - Correct Answer- Linear function (if it runs in linear time and you double the size of the data then the time will double as well). What does the function/graph look like based on the given example? (example found in lecture 37) Color in every pixel on an nxn photo. - Correct Answer-- O(n^2) pg. 52 professoraxe l