ASSIGNMENT 1:
Task 1:
Review the following codes, find and fix errors also explain the errors
Debugging Exercise 1: Array Manipulation
Objective: To identify and fix errors in a Java program that manipulates arrays.
public class ArrayManipulation {
( public static void main(String[] args) {
int[] numbers = (1, 2, 3, 4, 5);
for (int i = 0; i<= numbers.length; i++) {
System.out.println(numbers[i]):
Error:
1. Array Initialization
2. For Loop Condition
Corrected code:
public class ArrayManipulation {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Correct way to initialize an array using curly braces
for (int i = 0; i < numbers.length; i++) { // Corrected loop condition
System.out.println(numbers[i]); // Corrected println statement and removed colon
Errors explained:
1. Array Initialization: Arrays in Java are initialized using curly braces {} and not parentheses
(). So, int[] numbers = {1, 2, 3, 4, 5}; initializes an array of integers with 5
elements containing the values 1 through 5.
2. For Loop Condition: The condition in the for loop should be i < numbers.length
instead of i <= numbers.length. This is because array indexing in Java starts from 0,
so numbers.length gives the number of elements in the array, but indexing goes from 0
to numbers.length - 1.
Debugging Exercise 2: Object-Oriented Programming
Objective: To identify and fix errors in a Java program that demonstrates basic object-
oriented programming principles.
class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
public void start() {
System.out.println("Starting the car.");
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry");
car.start();
car.stop();
Errors:
Missing stop() Method in Car Class
Corrected code:
class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
public void start() {
System.out.println("Starting the car.");
// Adding a stop method
public void stop() {
System.out.println("Stopping the car.");
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry");
car.start();
car.stop();
Error explained:
Encapsulation: The Car class now encapsulates both start() and stop() methods, which
are behaviors related to the car object. This adheres to the principle of encapsulation in object-
oriented programming by bundling related behaviors together within the Car class.
Object Initialization: In the main method of the Main class, a Car object named car is
instantiated with the make "Toyota" and model "Camry". This demonstrates the creation of objects
based on a class definition.
Method Invocation: The car.start(); and car.stop(); lines in the main method
demonstrate invoking methods on the car object, showing how objects interact with their behaviors
(methods) to perform actions (starting and stopping).
Debugging Exercise 3: Exception Handling
Objective: To identify and fix errors in a Java program that demonstrates exception handling.
public class ExceptionHandling {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5);
try {
System.out.println(numbers[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
int result = divide(10, 0);
System.out.println("Result: " + result);
public static int divide(int a, int b) {
return a/b;
Errors:
1. Array Index Out of Bounds Exception Handling
2. Arithmetic Exception Handling
Corrected error:
public class ExceptionHandling {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
try {
System.out.println(numbers[10]); // Trying to access index 10 which doesn't exist
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
// Handling ArithmeticException by catching it
try {
int result = divide(10, 0); // Trying to divide by zero
System.out.println("Result: " + result); // This line will not be reached if an exception occurs
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Divisor cannot be zero"); // Throw an exception if b is 0
return a / b;
Errors explained:
Try-Catch Blocks: Both try-catch blocks are used to handle specific types of exceptions:
The first try-catch block handles ArrayIndexOutOfBoundsException when
accessing an invalid index in the numbers array.
The second try-catch block handles ArithmeticException when attempting to
divide by zero in the divide method.
Method Invocation: The main method invokes divide(10, 0);, demonstrating how
exceptions thrown from methods are caught and handled in Java.
Output: With proper exception handling, even if an exception occurs (like dividing by zero), the
program gracefully handles it by printing an appropriate error message .
Exercise 4:
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n-1) + fibonacci(n-2);
public static void main(String[] args) {
int n = 6;
int result = fibonacci(n);
System.out.println("The Fibonacci number at position" + n + " is: " + result);
The code aims to calculate the Fibonacci sequence. However, there is a bug in the code.
When the student runs this code, it will raise an error or produce incorrect output. The
student's task is to identify and correct the bug.
Errors:
1. Memoization Implementation
2. Efficient Computation
Corrected code:
import java.util.HashMap;
import java.util.Map;
public class Fibonacci {
// Memoization map to store computed Fibonacci numbers
private static Map<Integer, Integer> memo = new HashMap<>();
public static int fibonacci(int n) {
if (n <= 1)
return n;
// Check if Fibonacci number for 'n' is already computed
if (memo.containsKey(n)) {
return memo.get(n);
} else {
// Compute Fibonacci number and store in memoization map
int fib = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, fib);
return fib;
public static void main(String[] args) {
int n = 6;
int result = fibonacci(n);
System.out.println("The Fibonacci number at position " + n + " is: " + result);
Errors explained:
Memoization: By storing previously computed results, the Fibonacci sequence is computed
efficiently without recomputing values multiple times.
Recursive Approach: The recursive structure remains intact (fibonacci(n) =
fibonacci(n-1) + fibonacci(n-2)), but with the added benefit of caching results for
quick lookup.
Output: When you run the modified main method, it correctly computes and prints the Fibonacci
number at position n (in this case, n = 6), demonstrating the corrected and optimized Fibonacci
sequence calculation.
Exercise5:
import java.util.*;
public class PrimeNumbers (
public static List<Integer> findPrimes(int n) {
List<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
boolean is Prime = true;
for (int j = 2; j<i; j++) {
if (i % j == 0) {
isPrime = false;
break;
if (isPrime) {
primes.add(i);
return primes;
public static void main(String[] args) {
int n = 20;
List<Integer> primeNumbers = findPrimes(n);
System.out.println("Prime numbers up to +n+":"+ primeNumbers);
}
The code aims to find prime numbers up to a given limit. However, there is a bug in the
code. When the student runs this code, it will raise an error or produce incorrect output. The
student's task is to identify and correct the bug.
Errors:
1. Prime Number Check: In the findPrimes method:
Correction in Loop:
Edge Case Handling:
2. Output Formatting: In the main method
Corrected code:
import java.util.*;
public class PrimeNumbers {
public static List<Integer> findPrimes(int n) {
List<Integer> primes = new ArrayList<>();
// Edge case for smaller values of n
if (n < 2) {
return primes; // Return empty list for n < 2
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
// Check for factors of i from 2 to sqrt(i)
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
return primes;
public static void main(String[] args) {
int n = 20;
List<Integer> primeNumbers = findPrimes(n);
System.out.println("Prime numbers up to " + n + ": " + primeNumbers);
Errors explained:
Prime Number Check: The corrected implementation iterates through numbers from 2 to n and
checks if each number is prime by testing divisibility from 2 up to its square root. This is more
efficient than testing divisibility up to i - 1.
Edge Case Handling: Handling the case where n is less than 2 ensures the function returns an
empty list, as there are no prime numbers less than 2.
Output: The main method now correctly prints the list of prime numbers found up to the
specified limit n, formatted for clarity.