VelocerApp öffnen

Velocer › Lernkarten › University of Wisconsin–Madison › CS 300: Programming II · UW-Madison

CS 300: Programming II · UW-Madison

Studying for CS 300 (programming II), sharing in case anyone else needs them. · von nullpointer_7 · 198 Karten

University of Wisconsin–Madison

Dieses Deck lernen Einbetten

  1. What does aliasing refer to in the context of memory models?When two or more references point to the same object in memory.
  2. What is garbage collection in Java?Automatic reclamation of heap memory occupied by objects that are no longer referenced.
  3. What is encapsulation?Bundling data and methods within a class and restricting direct access to internal state.
  4. What is polymorphism in object-oriented programming?The ability of objects of different types to respond to the same method call in type-specific ways.
  5. What is the difference between an abstract class and an interface in Java?An abstract class can have state and concrete methods and is extended by one superclass; an interface declares a contract and can be implemented by multiple types.
  6. What are generics used for in Java?Writing classes and methods that operate on typed parameters, providing compile-time type safety.
  7. What is the difference between the stack and the heap?The stack stores method call frames and local variables with automatic lifetime; the heap stores dynamically allocated objects managed by garbage collection.
  8. What does Big-O notation describe?An asymptotic upper bound on an algorithm's growth rate.
  9. What does Big-Theta notation describe?A tight asymptotic bound on an algorithm's growth rate (both upper and lower).
  10. What is recursion?A technique where a method calls itself to solve smaller subproblems, requiring a base case to terminate.
  11. What is the capacity of a Java array determined by?The capacity is fixed at allocation time using new Type[cap] and cannot change afterward.
  12. What are the valid indices for a Java array of length n?Zero-based indices from 0 to arr.length - 1.
  13. How do you access an array's capacity in Java?Use the final field arr.length (no parentheses), unlike String.length().
  14. What values do unassigned array slots hold in Java?Type defaults: 0 for integers, 0.0 for floating point, false for booleans, and null for object references.
  15. Why doesn't arr.length tell you how many meaningful elements an array contains?arr.length only reports total reserved slots; the array cannot track how many live items have been placed inside it.
  16. What is a perfect-size array?An array where every slot holds live data, so size == arr.length and no separate counter variable is needed.
  17. When is a perfect-size array appropriate?When the collection size is fixed and known in advance.
  18. What is an oversize array?An array allocated with extra capacity for future growth, paired with a separate integer variable size tracking live elements.
  19. In an oversize array, what does arr.length represent versus size?arr.length is the total capacity, while size is the number of live elements currently stored.
  20. State the compactness invariant for a compact oversize array.All size live elements occupy contiguous indices [0, size - 1], unused capacity sits in [size, arr.length - 1], and 0 <= size <= arr.length always holds.
  21. In a compact oversize array, where are the live elements located?In contiguous indices from 0 to size - 1.
  22. In a compact oversize array, where is the unused capacity located?In indices from size to arr.length - 1.
  23. What range must the size variable satisfy in an oversize array?0 <= size <= arr.length must always hold.
  24. What is the key difference between perfect-size and oversize arrays regarding tracking?Perfect-size arrays need no separate counter since size == arr.length; oversize arrays require a separate size variable to track live elements.
  25. What does a primitive variable store, and what happens when you assign one primitive variable to another?A primitive variable stores its actual value directly in its memory box. Assigning int y = x; copies the value, so mutating y never affects x.
  26. What does a reference variable store, and what is aliasing?A reference variable stores a memory address (pointer) to an object on the heap. Assigning int[] b = a; copies only the reference, so both variables point to the same underlying array—this is aliasing.
  27. What is the difference between int[] a = {10, 20, 30}; and int[] b = new int[]{10, 20, 30};?The literal form {10, 20, 30} is only valid at declaration. The anonymous allocation new int[]{...} can be used anywhere, including reassignment or as a method argument.
  28. What does int[] c = new int[5]; create?It allocates an array of 5 slots, all zero-initialized. It is commonly paired with a separate int size = 0; variable for an oversize array.
  29. Why must methods that modify an oversize array's element count return the updated size?Because Java passes primitives by value, so a method cannot change the caller's size variable directly. Returning the new size lets the caller update it.
  30. How should print(String[] arr, int size) loop over an oversize array?Loop i from 0 to size - 1, never up to arr.length, so only the valid elements are printed.
  31. How does add(String[] arr, int size, String val) work on an oversize array?If size < arr.length, it places val at arr[size] and returns size + 1. Otherwise the array is full and the value cannot be added.
  32. How does indexOf(String[] arr, int size, String val) search an oversize array?It linearly scans indices [0, size - 1] using .equals(val) and returns the matching index i, or -1 if not found.
  33. Describe the steps of remove(String[] arr, int size, String val) on an oversize array.Find the index idx, shift elements in [idx + 1, size - 1] left by one slot, null out arr[size - 1], and return size - 1.
  34. What is a 2D array in Java, and what do grid.length and grid[r].length mean?A 2D array is an array of row references (int[]). grid.length is the number of rows, and grid[r].length is the number of columns in row r.
  35. How do you access the element at row r and column c of a 2D array?Use grid[r][c], which accesses row r and then column c within that row.
  36. What are parallel arrays, and what is their main drawback?Parallel arrays store related attributes across multiple 1D arrays at matching indices (e.g., menu[i] and prices[i]). They are error-prone because every insertion or removal must be synchronized across all arrays, which motivates using custom classes.
  37. Which types are primitive and which are reference types in Java?Primitives include int, double, boolean, and char. Reference types include arrays like int[], String, and class types like Book.
  38. Why is int[] a = {10, 20, 30}; invalid outside a declaration?The array literal form is only valid at declaration. For reassignment or method arguments, use the anonymous form new int[]{10, 20, 30}.
  39. What is the difference between a class and an object?A class is a blueprint (recipe); an object is a concrete instance created with new ClassName(...).
  40. In Book dune = new Book("Dune");, what happens and in what order?Evaluation is right-to-left: new allocates heap space, the constructor initializes instance fields, then the heap address is stored in dune.
  41. What do instance fields and methods belong to?Each individual object; they are accessed through a specific object reference like dune.getTitle().
  42. What do static fields and methods belong to?The class as a whole—only one shared copy exists in static memory, e.g., Math.pow(2, 3) or Book.MAX_LOAN_DAYS.
  43. What does Book[] shelf = new Book[3]; actually create?One array object filled with null references—not 3 Book objects.
  44. What happens when you dereference a null reference, and how do you prevent it?It throws a NullPointerException; guard with if (shelf[i] != null) before dereferencing.
  45. Why can't primitive types be used as generic type arguments or hold null?Primitives are not objects; each primitive has an immutable wrapper class (e.g., int ↔ Integer, char ↔ Character) that can be used instead.
  46. What are the wrapper classes for int, double, char, and boolean?Integer, Double, Character, and Boolean.
  47. What are autoboxing and unboxing?Java's automatic conversion between primitives and their wrapper classes, e.g., Integer a = 5; (autoboxing) and int x = a; (unboxing).
  48. How does Integer == int comparison behave?The Integer is unboxed and the primitive values are compared, so it compares values.
  49. How does Integer == Integer comparison behave?It compares memory addresses, not values—so use .equals() instead.
  50. Why does Integer a = 100, b = 100; a == b evaluate to true but Integer c = 128, d = 128; c == d evaluate to false?Java caches Integer instances in the range [-128, 127], so values in that range share the same object; 128 is outside the cache.
  51. What is the rule for comparing objects like String and Integer?Always use .equals(), never ==.
  52. Are String and wrapper objects mutable?No—they are immutable; they cannot be mutated after construction.
  53. What does calling s.toUpperCase() do to the original String?It returns a brand-new String; the original variable is unchanged unless reassigned with s = s.toUpperCase().
  54. What are the four memory regions in a Java program?Code, static memory, the stack, and the heap.
  55. What is stored in the code region of memory?Compiled bytecode instructions.
  56. What is stored in static memory, and how long does it last?Static variables; one copy per class for the lifetime of the program.
  57. What is the stack, and what does each frame contain?A LIFO stack of activation frames; each frame is pushed per method call and holds parameters and local variables.
  58. When is a stack frame popped and destroyed?When the method returns.
  59. What is stored in the heap?Dynamically allocated objects created with new.
  60. When does a heap object created inside a method survive after the method returns?If its reference was returned or stored elsewhere (e.g., in a field or static variable).
  61. When does an object become garbage?The moment it is no longer reachable by following any chain of references from active stack frames or static variables.
  62. Who reclaims the memory of garbage objects?The JVM Garbage Collector automatically reclaims their heap memory.
  63. What is a reference copy (aliasing) of an array?Assigning one array variable to another (e.g., Book[] b = a;) without creating a new array; both variables point to the same array.
  64. What does Arrays.copyOf(a, a.length) do for an array of objects?It creates a shallow copy: a new outer array whose slots contain the same object references as the original array.
  65. In a shallow copy of a Book[] array, does mutating b[0]'s fields affect a[0]?Yes, because a[0] and b[0] refer to the same Book object.
  66. What distinguishes a deep copy from a shallow copy of an object array?A deep copy allocates a new array and constructs a new copy of each non-null element, so a[0] != b[0] but a[0].equals(b[0]).
  67. What is ArrayList<E> and what are its key methods?A generic, dynamically resizing list class with methods such as add(x), get(i), size(), and remove(i).
  68. What type must the type argument <E> in ArrayList<E> be?A reference type (e.g., ArrayList<Integer>), never a primitive type like int.
  69. What three pieces of diagnostic state does a Java exception object carry?Its type (what went wrong), its message string, and its stack trace (a snapshot of all open stack frames when thrown).
  70. How is a Java exception object created when an error occurs?It is constructed with new, just like any other object.
  71. What are the two main subclasses of Throwable?Error and Exception.
  72. What kind of failures are Error objects, and should you catch them?Unrecoverable JVM failures like StackOverflowError and OutOfMemoryError; you should never catch them.
  73. What distinguishes checked exceptions from unchecked exceptions?Checked exceptions must be caught or declared with throws or the code won't compile; unchecked exceptions are RuntimeException or its subclasses and the compiler does not force handling.
  74. Which class and its subclasses are considered unchecked exceptions?RuntimeException and all its subclasses.
  75. What must code do to compile when it may throw a checked exception?It must either catch the exception or declare throws in the method signature.
  76. Is NullPointerException checked or unchecked, and why?Unchecked, because it is a subclass of RuntimeException.
  77. Is IOException checked or unchecked?Checked, because it is an Exception subclass but not a RuntimeException.
  78. If no exception occurs in a try block, what happens to the catch blocks?They are skipped; execution proceeds to finally (if present) and then continues after the block.
  79. When an exception is thrown at line k of a try block, what happens to the remaining lines of the try block?The rest of the try block is immediately abandoned; control transfers to exception handling.
  80. How does Java choose which catch block handles a thrown exception?It checks catch blocks top-down and uses the first whose parameter type is the same type or a superclass of the thrown exception.
  81. When does a finally block execute?Always—whether the try succeeded, a catch ran, or an uncaught exception propagated out.
  82. Why does placing catch (RuntimeException e) above catch (ArrayIndexOutOfBoundsException e) cause a compiler error?RuntimeException is a superclass of ArrayIndexOutOfBoundsException, so the more specific catch block becomes unreachable (Unreachable catch block error).
  83. In what order should catch blocks be arranged, and why?From most specific (child) to most general (parent), so that specific handlers are reachable and general ones don't shadow them.
  84. What is the multi-catch syntax for handling two unrelated exceptions with the same recovery logic?catch (NumberFormatException | IndexOutOfBoundsException e) — separate exception types with a pipe (|) in one catch parameter.
  85. When should you use multi-catch instead of separate catch blocks?When two unrelated exceptions share identical recovery logic, so the handling code can be written once.
  86. Does finally run if a catch block executes?Yes; finally always executes regardless of whether a catch handled the exception.
  87. Does finally run if an exception is not caught and propagates out of the method?Yes; finally still executes before the exception propagates out.
  88. What determines whether a catch block matches a thrown exception?The thrown exception's type must be the same as, or a subclass of, the catch parameter type.
  89. What is the difference between throw and throws in Java?throw appears inside a method body and actively raises an exception object now; throws appears in the method signature and declares that the method may let an exception propagate to callers.
  90. What is stack unwinding in Java exception handling?An uncaught exception pops the current method's stack frame and checks the caller's frame, repeating up the call chain until a matching catch is found or main pops and the program terminates with a stack trace.
  91. What happens when an exception propagates all the way out of main?The program terminates and prints the stack trace.
  92. How do you create a checked user-defined exception?Define a class that extends Exception, forwarding the message to super(msg).
  93. How do you create an unchecked user-defined exception?Extend RuntimeException (or IllegalArgumentException), forwarding the message string to super(msg).
  94. What does extending Exception versus RuntimeException mean for a custom exception?Extending Exception makes it checked (must be declared or caught); extending RuntimeException makes it unchecked.
  95. What is the benefit of try-with-resources?Declaring an AutoCloseable resource in the try (...) header guarantees its close() method is called automatically when the block exits, eliminating manual finally cleanup.
  96. Which types can be used in a try-with-resources declaration?Types that implement AutoCloseable (such as Scanner).
  97. How do you test that a method throws an expected exception?Wrap the invalid call in a try block; if the call does not throw, immediately return false;. Catch the exact expected exception type and return true.
  98. What does throw new IllegalArgumentException("Bad age"); do?It creates and raises an IllegalArgumentException with the message "Bad age" at that point in the method body, halting normal execution.
  99. What must the name of a constructor match, and what return type does it have?A constructor has the exact same name as its class and no return type at all—not even void.
  100. When does Java provide a default no-arg constructor?Java supplies a default no-arg constructor only if you write zero constructors. As soon as you write any constructor, the automatic no-arg constructor disappears.
  101. Why does title = title; inside a constructor leave the field null?The parameter shadows the instance field, so the statement assigns the parameter to itself. Use this.title = title; to assign the field.
  102. What does the this keyword reference, and which methods lack it?this holds a reference to the current object instance. Static methods have no this reference.
  103. What is constructor chaining with this(...) and what rule applies?One overloaded constructor can delegate to another constructor in the same class via this(arg1, arg2);. It must be the very first statement in the constructor body.
  104. What distinguishes overloaded methods or constructors from each other?Overloaded methods/constructors share a name but differ in their parameter type lists—count, types, or order. Parameter names and return types do not disambiguate them.
  105. How do you prevent a privacy leak when returning a private ArrayList field?Return a defensive copy, e.g. return new ArrayList<>(this.tags);, rather than the direct reference. Otherwise callers can mutate the private list via methods like clear().
  106. What is the difference between an is-a and a has-a relationship?is-a means inheritance (Textbook extends Book); the subclass inherits superclass fields and methods. has-a means composition, where a class holds another type as a field (e.g., Library has an ArrayList<Book>).
  107. Are constructors inherited by subclasses, and how must a subclass constructor start?Constructors are never inherited. Every subclass constructor must call super(...) as its first statement to build the superclass portion.
  108. What happens if a subclass constructor omits super(...) and the superclass has no no-arg constructor?Java implicitly inserts super() with no arguments, which fails to compile because the superclass has no matching no-arg constructor.
  109. What access does private vs. protected vs. public grant?private is visible only inside the declaring class (subclasses cannot touch it directly). protected grants access to subclasses and the same package. public grants access everywhere.
  110. What signature must an override of equals use, and why?The parameter type must be Object (e.g., equals(Object o)). Writing equals(Book b) overloads rather than overrides the inherited method.
  111. What are the steps to correctly override equals(Object o)?Check if (o instanceof Book), downcast with Book other = (Book) o;, then compare logical fields using .equals().
  112. State the Golden Rule of Polymorphism.Compile-time: the reference variable's declared type determines which methods you may call. Runtime: the actual heap object's class determines which overridden version runs.
  113. Why does b.getCourse() fail to compile when b is declared as Book but holds a Textbook?The declared reference type Book determines the methods you are allowed to call, and getCourse() is not defined on Book. Runtime dispatch only affects which overridden version runs, not which methods compile.
  114. How do you safely call a subclass-only method on a superclass reference?Guard with if (b instanceof Textbook), then downcast: ((Textbook) b).getCourse(). Downcasting an incompatible object throws a ClassCastException.
  115. What does marking a class abstract prevent, and what does an abstract method require?An abstract class cannot be instantiated directly (new Book() is illegal). An abstract method has no body (ends with ;) and forces every concrete subclass to override and implement it.
  116. How can concrete methods in an abstract class use abstract methods?Concrete methods (like renew()) can call abstract methods (like getLoanLength()) polymorphically, so each subclass's implementation runs.
  117. What is the default toString() and equals(Object) behavior inherited from Object?Default toString() returns ClassName@hexHash. Default equals(Object) behaves like == (reference comparison).
  118. How do you invoke the superclass version of an overridden method?Use super.methodName() inside the overriding method, e.g. return super.toString() + " [" + course + "]";.
  119. What is an interface in Java?A pure behavioral contract with no instance fields, no constructors, and abstract method signatures.
  120. How many superclasses can a class extend, and how many interfaces can it implement?A class can extend only one superclass but can implement many interfaces.
  121. When implementing an interface method, what access modifier must the method have?The method must be declared public.
  122. What does the compareTo method return if 'this' comes before 'other'?A negative integer (< 0).
  123. What does the compareTo method return if 'this' and 'other' are equal in sort order?Zero (0).
  124. What does the compareTo method return if 'this' comes after 'other'?A positive integer (> 0).
  125. Are generics covariant or invariant in Java?Generics are invariant: ArrayList<Song> is not a subtype of ArrayList<Object> or ArrayList<Track>.
  126. Where is the type parameter <T> placed in a generic method declaration?Before the return type, e.g., public static <T> ArrayList<T> firstNItems(...).
  127. What methods are available on an unbounded type parameter <T>?Only Object methods such as toString() and equals().
  128. What does the bound <T extends Track> guarantee?That T is a subtype of Track, allowing use of Track methods like getSeconds().
  129. When bounding a type parameter to an interface, which keyword is used?The keyword extends is always used for bounds, even when the bound is an interface.
  130. Why can't a generic class execute new T() or new T[cap]?Because Java implements generics via type erasure, so T is erased at runtime.
  131. How does a generic class typically store elements internally?In a Track[] (if bounded) or Object[] (if unbounded), casting elements to (T) on retrieval.
  132. What does x.getClass() == Song.class check?Whether x is an instance of that exact class only, not a subclass.
  133. Why does algorithm analysis count steps instead of measuring wall-clock time?Wall-clock time varies across hardware and background load. Counting fundamental operations as a function of problem size N focuses on the asymptotic growth rate.
  134. What happens to the step count of an O(log N) algorithm when N doubles?It increases by 1 additional step. For example, binary search halves the search range each pass.
  135. What happens to the step count of an O(N^2) algorithm when N doubles?It quadruples (×4). This is typical of nested loops over the same N, such as triangular pair comparisons N(N-1)/2.
  136. What is the growth rate of a loop like for (int i = 1; i < n; i *= 2)?O(log N). The loop variable doubles each iteration, so the number of iterations grows logarithmically with N.
  137. How do you combine the costs of sequential statements in algorithm analysis?Add their costs, then drop lower-order terms and constant multipliers when variables are the same. For example, O(N + N^2) = O(N^2).
  138. How do you combine the costs of nested statements in algorithm analysis?Multiply their costs. A loop inside another loop multiplies their complexities, and hidden loops inside method calls must also be counted.
  139. What is the complexity of calling library.contains(song) (O(N)) inside a loop over M songs?O(M × N). The O(N) cost of each contains call is multiplied by the M iterations of the outer loop.
  140. What is the complexity of calling list.remove(0) (O(N) shift) inside an N-step loop?O(N^2). Each remove(0) shifts O(N) elements, and this happens N times.
  141. When a method depends on two independent sizes M and N, how should complexity be expressed?Keep both variables: O(M × N) for nested work or O(M + N) for sequential work. Only collapse to O(N) if M is bounded by a fixed constant.
  142. For a single search, why is Linear Search O(N) better than sorting first?Sorting first costs O(N log N) + O(log N) = O(N log N), which is worse than a single O(N) linear search. Sorting only pays off for many searches.
  143. What is the complexity of finding duplicates by copying, sorting, and scanning adjacent elements?O(N log N). Copying is O(N), sorting is O(N log N), and the adjacent scan is O(N), so the total is O(N log N), beating the O(N^2) all-pairs check.
  144. What does Big-O (O) represent in algorithm analysis?An upper bound on growth rate, typically the worst-case input requiring the maximum steps.
  145. What does Big-Omega (Ω) represent in algorithm analysis?A lower bound on growth rate, typically the best-case input requiring the minimum steps, such as an early return on the first check.
  146. When does Big-Theta (Θ) exist for an algorithm?If and only if the best-case Ω and worst-case O growth rates match.
  147. What is the growth rate of an O(1) algorithm, and what are examples?Constant: the step count stays unchanged as N grows. Examples include a closed-form formula like n(n+1)/2 or an array index lookup arr[0].
  148. What happens to the step count of an O(N) algorithm when N doubles?It doubles (×2). This is typical of a single pass over N items.
  149. What happens to the step count of an O(N^3) algorithm when N doubles?It multiplies by ×8. This is typical of three nested loops over the same N.
  150. What is the approximate value of log2 N for N = 1,000,000?About 20. For N = 1,000, log2 N is about 10, so each doubling of N adds roughly 1 to log2 N.
  151. What are the two essential parts of a recursive method?1. Base case: solves the smallest instance directly without recursion. 2. Recursive case: breaks the problem into a smaller version and calls itself.
  152. What is a base case in recursion?A condition that solves the smallest problem instance directly, without making a recursive call, stopping the recursion.
  153. What is a recursive case?The part of a recursive method that decomposes the problem into a strictly smaller version of the same problem and calls itself.
  154. What happens on the call stack during a recursive call?Each invocation pushes a new activation frame with its own local parameters, pausing the caller until the inner call returns.
  155. What causes a StackOverflowError in recursion?A missing base case or failure to make progress toward the base case, causing frames to accumulate infinitely until the JVM throws StackOverflowError.
  156. What is the general formula for analyzing recursive time complexity?Total Time = (Number of Recursive Calls) × (Work Done per Call).
  157. Why does removing index 0 from an ArrayList take O(N) time?Because ArrayList shifts all remaining elements left to fill the gap, requiring O(N) steps.
  158. What is the best-case time complexity of a simple sum loop like totalSeconds(songs)?Ω(N) — it always visits every element with no early return.
  159. What is the worst-case time complexity of findMax(songs)?O(N) — it must inspect all N elements to determine the largest.
  160. Why does findMax have matching best and worst bounds?You must inspect every element to know which is largest, so there is no shortcut even in the best case.
  161. What is the best-case complexity of linear search (indexOf)?Ω(1) — the target is found at index 0 in a single step.
  162. What is the worst-case complexity of linear search (indexOf)?O(N) — the target is last or missing, requiring N steps.
  163. Does linear search have a tight Θ bound? Why or why not?No — best case is Ω(1) and worst case is O(N), so the bounds differ and no single tight bound exists.
  164. What is the best-case complexity of binarySearch on a sorted array?Ω(1) — the target is at the exact midpoint, found in one step.
  165. What is the worst-case complexity of binarySearch?O(log N) — the target is missing, requiring about log₂ N steps.
  166. What is the best-case complexity of hasDuplicateTitles (nested pairs)?Ω(1) — if indices 0 and 1 match, the duplicate is found immediately.
  167. What is the worst-case complexity of hasDuplicateTitles (nested pairs)?O(N²) — when all titles are unique, it performs about N(N−1)/2 comparisons.
  168. Why is longest(songs) with removal at index 0 or 1 Θ(N²)?It makes N calls, each requiring O(N) element shifts to remove from the front.
  169. What is the complexity of longest(songs) when removing from the end?Θ(N) — N calls each with O(1) removal at size−1 or size−2.
  170. Why does removing from the front of a list cost O(N) per operation?Removing at index 0 or 1 requires shifting all remaining elements, costing O(N) per removal.
  171. What is the core relationship expressed by an abstract class?An abstract class expresses an is-a hierarchical identity relationship, and subclasses extend it with extends.
  172. What is the core relationship expressed by an interface?An interface expresses a can-do behavioral capability, and classes implement it with implements.
  173. Can an abstract class have instance fields?Yes. An abstract class can hold instance state, including private and protected fields.
  174. Can an interface have instance fields?No. An interface can only declare public static final constants, not instance state.
  175. Can an abstract class have constructors?Yes. Abstract classes can have constructors, which subclasses call via super(...).
  176. Can an interface have constructors?No. Interfaces have no constructors because there is no state to initialize.
  177. Can an abstract class contain concrete methods?Yes. An abstract class can mix concrete methods with abstract methods.
  178. How many classes can a single class extend?At most one. Java supports single inheritance for classes.
  179. How many interfaces can a single class implement?Many. A class can implement multiple interfaces, enabling multiple implementation.
  180. Can you directly instantiate an abstract class with new Track()?No. Direct instantiation of an abstract class is a compile error.
  181. Can you directly instantiate an interface with new Playable()?No. Direct instantiation of an interface is a compile error.
  182. Which type supports holding private or protected state: abstract class or interface?The abstract class. Interfaces cannot hold instance state, only public static final constants.
  183. Which type allows a class to inherit from multiple sources: abstract class or interface?The interface. A class can implement many interfaces but extend only one class.
  184. What keyword does a subclass use to inherit from an abstract class, and what keyword is used to adopt an interface?A subclass uses extends for an abstract class and implements for an interface.
  185. What does public Book(String title) { title = title; } do wrong?It assigns the parameter to itself, leaving the instance field this.title as null. It should be this.title = title;.
  186. What happens if a class defines only public Book(String title) and code calls new Book()?It causes a compile error, because defining any constructor removes the implicit default no-arg constructor.
  187. A subclass constructor doesn't explicitly call super(title) when the superclass has no no-arg constructor. What happens?It's a compile error; the subclass must explicitly invoke an existing superclass constructor.
  188. Does public boolean equals(Book other) override Object.equals?No. It overloads rather than overrides, so ArrayList.contains() still calls Object.equals (reference equality). Use @Override public boolean equals(Object o).
  189. Given Book b = new Textbook(...), why is b.getCourse() a compile error when getCourse is defined only in Textbook?The compile-time type of b is Book, and Book has no getCourse method. Only methods declared on the compile-time type can be called.
  190. Given Book b = new Textbook(...), which version of an overridden toString() runs at runtime?Textbook's version runs, because overridden instance methods are dispatched based on the runtime type of the object.
  191. Why does new T() fail to compile inside a generic class Box<T>?Type erasure removes the type parameter at runtime, so the compiler cannot know which constructor to call. Use a Class<T> token or factory instead.
  192. Why can't you write new T[10] inside a generic class?Because of type erasure, the runtime type of T is unknown, so generic array creation is not allowed.
  193. Why is obj instanceof T illegal inside a generic class?Type erasure means T has no runtime representation, so the instanceof check cannot be performed.
  194. Can an ArrayList<Song> be passed to a parameter of type ArrayList<Track> or ArrayList<Object>?No. Generics are invariant, so ArrayList<Song> is not a subtype of ArrayList<Track> or ArrayList<Object>.
  195. How do you write a method that accepts lists of any subtype of Track?Use a bounded generic: <T extends Track> void foo(ArrayList<T> list).
  196. What is the safe way to compare two Integer or String objects for equality?Use .equals() (or Objects.equals), never ==, since == compares object references.
  197. What is the difference between a compile-time type and a runtime type?The compile-time type is the declared type of the variable and determines which methods can be called; the runtime type is the actual object's class and determines which overridden method executes.
  198. Why does ArrayList.contains() fail to find an object when equals is written with a Book parameter instead of Object?Because that method doesn't override Object.equals, so contains() uses reference equality (==) and won't match an equal-but-different object.

Velocer ist kostenlos: Spaced Repetition und deine eigenen Karten aus jedem Dokument.

PDF to flashcards · Lecture to flashcards · Practice exam · Syllabus study plan · Anki import

Weitere Decks von University of Wisconsin–Madison