Java Fundamentals: Concepts and Syntax, Exams of Advanced Education

A wide range of java programming concepts, including data structures, control flow, object-oriented programming, and exception handling. It provides a comprehensive overview of fundamental java syntax and language features, such as classes, interfaces, inheritance, and nested classes. The document also explores advanced topics like abstract classes, comparators, and static/instance initializers. By studying this document, students can gain a deep understanding of the core principles and best practices in java development, which are essential for building robust and efficient applications. The content is structured in a clear and logical manner, making it suitable for both beginners and experienced programmers looking to solidify their java knowledge.

Typology: Exams

2023/2024

Available from 08/27/2024

Qualityexam
Qualityexam šŸ‡°šŸ‡Ŗ

2.5

(4)

6.3K documents

1 / 29

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CMSC 132 Exam Review With 100%
Correct And Verified Answers 2024
Analyzing runtime
Insert element into position 0 of an array of size n (in java) - Correct Answer-Runs in
linear time, (if the array is size n and you double it, time will be doubles as well, this is a
good way to think about linear time).
Analyzing runtime
Retrieving an element from an array of size n (at a particular index, in java). - Correct
Answer-When the CPU has to do the arithmetic to get the element from the specified
index, it's a constant time operation. The arithmetic barley takes any time regardless of
what index it is asking for.
(note: the size of arrays in java are bounded to 2^32)
Analyzing runtime
Program that prints all of the n-digit numbers - Correct Answer-It is an exponential
function multiplied by a linear function.
Think about 2 parabolas where one is shallow and the other is steep.
Can we make the shallow one worse than the steep one by multiplying it by a large
constant? - Correct Answer-- Yes, all parabolas are in the same "ballpark."
- It doesn't matter if one parabola starts better by the other, if you multiply it by a big
enough number, it is the same thing.
Imagine a parabola and a shallow line where the line is clearly faster, what if we start
multiplying it? will the line still be better? - Correct Answer-- Multiplying does slow it
down but even when we multiply by a large number, after the crossover we still see that
the red line is faster.
- As n goes to infinity, there is no way u can multiply the line by a number and make it
worse.
- Conclusion: lines are better/faster than parabolas.
f(n) as O(g(n)) means: - Correct Answer-As n goes toward infinity, f is either better,
(faster/smaller) than g, or "in the same ballpark."
What does "In the same ballpark" mean? - Correct Answer-- Even though g might seem
better (smaller), we can multiply it by a big number and make it worse (bigger) than f(for
big values of n).
- We can find a big enough value m, so that f(n) < mg(n) for sufficiently large n.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Java Fundamentals: Concepts and Syntax and more Exams Advanced Education in PDF only on Docsity!

CMSC 132 Exam Review With 100%

Correct And Verified Answers 2024

Analyzing runtime Insert element into position 0 of an array of size n (in java) - Correct Answer-Runs in linear time, (if the array is size n and you double it, time will be doubles as well, this is a good way to think about linear time). Analyzing runtime Retrieving an element from an array of size n (at a particular index, in java). - Correct Answer-When the CPU has to do the arithmetic to get the element from the specified index, it's a constant time operation. The arithmetic barley takes any time regardless of what index it is asking for. (note: the size of arrays in java are bounded to 2^32) Analyzing runtime Program that prints all of the n-digit numbers - Correct Answer-It is an exponential function multiplied by a linear function. Think about 2 parabolas where one is shallow and the other is steep. Can we make the shallow one worse than the steep one by multiplying it by a large constant? - Correct Answer-- Yes, all parabolas are in the same "ballpark."

  • It doesn't matter if one parabola starts better by the other, if you multiply it by a big enough number, it is the same thing. Imagine a parabola and a shallow line where the line is clearly faster, what if we start multiplying it? will the line still be better? - Correct Answer-- Multiplying does slow it down but even when we multiply by a large number, after the crossover we still see that the red line is faster.
  • As n goes to infinity, there is no way u can multiply the line by a number and make it worse.
  • Conclusion: lines are better/faster than parabolas. f(n) as O(g(n)) means: - Correct Answer-As n goes toward infinity, f is either better, (faster/smaller) than g, or "in the same ballpark." What does "In the same ballpark" mean? - Correct Answer-- Even though g might seem better (smaller), we can multiply it by a big number and make it worse (bigger) than f(for big values of n).
  • We can find a big enough value m, so that f(n) < mg(n) for sufficiently large n.

On a test Fawzi may ask: show 3n^2 + 15n + 20 is O(n^2) How would you show that? - Correct Answer-- Determine what number to multiply by n^2 to show that it can be worse than the first function.

  • answer: "I choose the multiplier n = 4, now 3n^2 + 15n + 20 < m(n^2) as long as n >

Show 100n + 150 is O(n) - Correct Answer-- Keep plugging numbers into n until you could prove the answer is true.

  • I choose m = 101
  • Now 100n + 150 < m(n) as long as n > 1000 What is the big O of the binary search algorithm? - Correct Answer-O(log n) If f is linear and g is quadratic, - Correct Answer-then f is O(g) but g is NOT O(f) If f is linear and g is logarithmic, - Correct Answer-then f is NOT O(g) but g IS O(f) if f(n) = 2^n and g(n) = 3^n, - Correct Answer-then f is O(g) but g is not O(f) f is O(g) meaning - Correct Answer-- f is either better (smaller) than g or at least not dramatically worse.
  • this is big O notation f is o(g) meaning - Correct Answer-f is dramatically better (smaller) than g. Suppose we have two functions, f(n) and g(n), and we want to know: Are they "in the same ballpark"? if not, which one is better/worse? evaluate this limit: lim (f(n)/g(n)) n --> infinity What does it mean if this limit comes out as 0? - Correct Answer-If this limit comes out as zero that means whatever is in the denominator is getting bigger dramatically faster than whatever is on top, so f is faster. We can write this in little o notation: f(n) is o(g(n)) Suppose we have two functions, f(n) and g(n), and we want to know: Are they "in the same ballpark"? if not, which one is better/worse? evaluate this limit: lim (f(n)/g(n)) n --> infinity

for (int i= n; i> 1 ; i/= 2) { System.out.println("HI"); } - Correct Answer-O(log n) Analyzing code fragments void foo() {...} // Takes time O(š‘›^3) for (int i= 0; i< n; i++) { for (int j = i; j < n; j++) { foo(); } } - Correct Answer-O(n^5)

  • Here we see that foo() takes n^3 time and the nested loops are n^2 so here we will need to multiply them and once we do we see that it is O(n^5) Analyzing code fragments for (int i= 0; i< 500; i++) { for (int j = 0; j < n; j++) { for (int k = 1000000; k > 1; k /= 2) { System.out.println("HI"); } } } - Correct Answer-We have 2 constants multiplied by each other so this example will be O(n). Can you write your own collection class that facilitates generics? - Correct Answer-Yes, you need to use a parameterized type. public class MyCollection { // Internally, use T in almost any imaginable way } What does T represent? - Correct Answer-T is a type that you don't know in advanced, when someone makes use of your code they will specify a type. It is similar to array lists since you can specify different types as you use array lists. Imagine you are writing an ordered pair collection: public class OrderedPair{ } What methods would you include? - Correct Answer-- public OrderedPair(T left, T right) {...}
  • public T getLeft(){....}
  • public T getRight(){....}
  • public void setLeft(T left){....}
  • public void setRight(T left){....}
  • public String toString(){....} (ordered pair example in lecture 43) If we wrote the ordered pair collection: public class OrderedPair{ } How would you use that class to create a new ordered pair of type String in the driver? - Correct Answer-OrderedPair stringPair = new OrderedPair<>("x", "y");
  • As seen above when we create a new ordered pair we specify the type on the left. If you tried to add something of a different type into that ordered pair, it will not compile. Let's say there is a class called UnderGrad that extends Student, and Student extends person. Additionally, Student implements an interface called CanStudy. What is UnderGrad a subtype of? - Correct Answer-Student, Person, Object, and CanStudy How can you control what the user puts into a collection you create? (parameterized types) - Correct Answer-public class MyCollection { ...... }
  • T must be a subtype of Foo
  • Foo could be a class or interface
  • This is kind of confusing because we see extends with classes but here we are using it in a different context that is related to interfaces. You want to write a collection that limits the type T to a list of things that are comparable to each other, how would you start the class? - Correct Answer-public class SortedList<T extends Comparable>{....} public class MyCollection { private T[] a = new T[3]; private T[] b = (T[]) new Object[4]; }
  • What compiles?
  • What is better than trying to use arrays here? - Correct Answer-- Arrays aren't very advanced so the first statement (private T[] a = new T[3];) will not compile when trying to create a new array of type T. private T[] b = (T[]) new Object[4]; compiles.

Here is a list: 12, 7, 9, 8, 4 What is the successor of nine? - Correct Answer- What are some data structures that implement list? - Correct Answer-- Array (sequential allocation)

  • Linked lists (nodes are connected together but they are all separate objects in memory). What would an empty linked list look like? - Correct Answer-head ---> null (head initialized as null represents an empty linked list) 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). (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. What is encapsulation? - Correct Answer-Hiding something in a private shell, in order to access private members they use public methods. What are the 2 types of encapsulation? What do they each mean? - Correct Answer- data encapsulation - make the data private

procedural encapsulation - switching out an algorithm behind the scenes and no user will know (rule of thumb: encapsulate what may change later). Why do the wrapper classes exist? - Correct Answer-In order to make collections of these values. Collections can only collect objects, not primitives. (T/F) all the wrapper classes are immutable. - Correct Answer-TRUE. You cannot change the state of the object. Which declaration is correct? a) Integer x = new Integer(7); b) Integer x = Integer.valueOf(7); - Correct Answer-b is correct, a is deprecated. b is a better option because the Integer object is immutable so there is no need to create a new copy of seven every time, since aliasing is not a concern. explain auto-boxing - Correct Answer-java is expecting an integer object but you give it a primitive, it changes it to the wrapper class Integer automatically instead, this is called auto boxing. explain auto-unboxing - Correct Answer-if you give it an integer object when java is expecting primitive int, java will accept it and unboxes the 7, and turns it into a primitive. collections framework - Correct Answer-Many classes/interfaces that allow easy use of data structures and types. (EXAMPLE: array lists) How would you create a new array list called x of type Cat? what is wrong with the deprecated version? - Correct Answer-ArrayList 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; } How would you access objects from an enumeration named 'Day'? - Correct Answer-If you wanted to access Monday you type:

After creating a list of Strings, what would you type before being able to call methods from the iterator interface? - Correct Answer-Iterator iterator = nameOfList.iterator(); //examples of the methods being used: while(iterator.hasNext()){ String word = iterator.next() System.out.println(word); } What exception gets thrown when using a for each loop to remove elements from a collection? - Correct Answer-java.util.ConcurrentModificationException (T/F) When you pass a primitive variable to a method, the method CAN modify it - Correct Answer-FALSE (T/F) A method call that passes an object as a parameter can potentially modify the state of a reference to that object. - Correct Answer-TRUE What does it mean for a class/object to be immutable? - Correct Answer-The state (instance variables) are set during construction but cannot be modified after that. What does it mean for a class/object to be mutable? - Correct Answer-The state is set during construction and it might be modified later. What are privacy leaks? - Correct Answer-Suppose a mutable member has been intentionally encapsulated (made private), modification of its 'state' within the class is expected ("mutation"). Direct mutation by external code should not be possible, if it does then there is a privacy leak. A constructer is returning a direct reference to a private instance variable called symbols, therefore if you change a variable pointing to that reference, it will change the private variable as well. How can we avoid this? - Correct Answer-use the copyOf method so it creates a copy rather than pointing it to the direct reference. What we did here to fix the problem is called a 'defensive copy' (note: copyOf works on arrays not array lists) "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 (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 # 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.

(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.) 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. 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. How is an instance of a subclass constructed? - Correct Answer-Makes a call to the superclass constructor. Why? -members are private -superclass likely has "policies" that need to be enforced. (T/F) If you are in a class that extends another class, the subclass cannot make an assignment to a private variable from its super class. - Correct Answer-TRUE. But how can we fix this? To fix this we need to have a public constructor in the superclass to take care of those variables, and then in the subclass there will be another constructor to take care of the rest of the variable assignments found in itself. flip this card for an example where we use super to invoke the constructor from the super class - Correct Answer-public class Student extends Person{ private double GPA; private int admitYear; public Student(String name, int ID, double GPA, int admitYear){ super(name, ID); this.GPA = GPA; this.admitYear = admitYear; } general summary of "super" - Correct Answer-"super" is used in constructors to invoke super class version of constructor, and you'll see it in many methods such as overridden methods. if you need to call a method from the super class inside the over ridden method of the subclass, you need to put super.nameOfMethod to prevent using the new overridden version. (T/F) your class only extends another class if you specify that. - Correct Answer-FALSE. -every class you write does extend something -if your class doesn't explicitly extend something, it will extend an object -object is always at the root of the inheritance tree What class is said to be 'the mother of all classes'? - Correct Answer-the object class What is found in the object class? - Correct Answer-clone(), toString(), equals(Object obj), finalize(), getClass(), hashCode(), notify()

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 Does c++ have early binding or late binding? - Correct Answer-c++ does early binding (Fawzi used to program in c++ a lot) Whoever is reading this, make sure you understand..... - Correct Answer-the late binding example Fawzi showed at the end of lecture 18. He said it will be quiz/exam material and I cannot type the whole thing here! When casting, what are we trying to do when writing this statement? (Foo)x - Correct Answer-x is not type foo, and we are trying to treat the object x refers to as if it were type foo. It will not change it to foo but it will treat it that way. (note: x is a reference and foo is a type) When will (Foo)x compile? - Correct Answer-If you look at the inheritance diagram and the type of either x or foo is above the type of x or foo then it will compile. (Foo)x What is an upcast? - Correct Answer-If the type of foo is above x's type in the inheritance diagram, it would be called an upcast. (Foo)x What is a downcast? - Correct Answer-If the type of foo is below x's type in the inheritance diagram, it would be called a downcast. upcasting example - Correct Answer-Student s = ....; Person p = (Person)s; can also be done implicitly: Person p = s; this works very well because a student is a person. downcasting example - Correct Answer-Person p = ....;

Student s = (Student)p; Sometimes this works sometimes it does not. -if p refers to an object of type student it's fine -if p refers to an object that is not type student, ClassCastException is thrown. (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 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: Person p = ......;

access levels of: 'protected' - Correct Answer-public features can be accessed: -class -package -subclass (Fawzi says to avoid using protected) access levels of: 'package' (default) - Correct Answer-public features can be accessed: -class -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 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); } - 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{ public int compare (Planet a, Planet b){ return int(a.getMass() - b.getMass()); } } If you wrote: Collections.sort(list) How would the list be sorted? how can we sort it differently with this method? - Correct Answer-It will go by the natural order. If you wanted to order them differently, you would first create a class that implements Comparator and then inside that class, implement the compare method how you want. Then you could call: Collections.sort(nameOfList, new nameOfClass) (T/F) You can write comparators for classes that you did not write. - Correct Answer- TRUE. There are 2 sides to exception handling.. - Correct Answer-There is a programmer who is throwing the exception and a programmer who is catching them.