Find error Flashcards
public class FindTheError {
public static void main(String[] args) {
myMethod(0);
}
public static void myMethod(int num) { System.out.print(num + " "); myMethod(num + 1); // ❌ no termination } }
Error: myMethod never stops calling itself—there’s no base case—so you get a StackOverflowError.
Fix: Add a base‑case check before the recursive call,
int[] numbers = { 8, 0, 9, 4, 3, 7, 2 };
int location = IntBinarySearcher.search(numbers, 7);
: Binary search requires the array to be sorted, but numbers isn’t sorted.
Fix: Sort first (e.g. Arrays.sort(numbers)), or use a linear search if the data must stay unsorted.
ArrayList myList = new ArrayList<String>();</String>
Left side omits the generic parameter.
ArrayList<String> myList = new ArrayList<>();</String>
public <T implements Comparable<T>> T greatest(T arg1, T arg2)</T>
Error: Use extends (not implements) in a generic bound.
Fix: public <T extends Comparable<T>> T greatest(T arg1, T arg2)</T>
public class MyClass<T> {
public static void displayValue(T value) { … }
}</T>
Error: A static method cannot use the class’s type parameter T.
Fix: Either remove static or give the method its own type parameter:
public static <T> void displayValue(T value) { … }</T>
public class Point<T> { … }</T>
Error: You can’t combine extends and super in a type‑parameter declaration.
Fix: Decide on a single bound,
public class Point<T> { … }</T>
Node ref = myList;
ref++; // ❌ invalid
System.out.print(ref.value);
Error: You can’t ++ a reference.
Fix:
Advance via the link: ref = ref.next;
Node ref = myList;
while (ref.next != null) {
System.out.print(ref.value + “ “);
ref = ref.next;
}
Error: The last node’s value never prints (loop stops when ref.next is null).
Fix:
After the loop, print ref.value, or use while (ref != null).
int pop() {
if (top == 0) throw new EmptyStackException();
else {
return s[top - 1];
top–; // ❌ unreachable
}
}
Error: top– is after return.
Fix:
top–;
return s[top];
void enqueue(int x) {
if (empty()) {
rear = new Node(x);
front = rear;
} else {
rear = new Node(x);
rear = rear.next; // ❌ loses the new node
}
}
Error: Overwrites rear instead of linking the new node.
Fix:
rear.next = new Node(x);
rear = rear.next;
int pop() {
if (empty()) throw new EmptyStackException();
return top.value; // ❌ top never moves
}
Error: Does not update top to remove the node.
Fix:
int val = top.value;
top = top.next;
return val;
int dequeue() {
if (empty()) throw new EmptyQueueException();
int value = front.value;
front++; // ❌ invalid pointer arithmetic
return value;
}
Error: front++ isn’t how you advance a node pointer.
Fix:
int value = front.value;
front = front.next;
return value;
int dequeue() {
if (empty()) throw new EmptyQueueException();
int val = q[rear]; // ❌ should use front
rear++;
return val;
}
Error: Uses rear instead of front to remove.
Fix:
int val = q[front];
front++;
return val;