assignment 1 task 1 java
assignment 1 task 1 java
Task 1:
Review the following codes, find and fix errors also explain the errors
System.out.println(numbers[i]):
Error:
1. Array Initialization
2. For Loop Condition
Corrected code:
public class ArrayManipulation {
int[] numbers = {1, 2, 3, 4, 5}; // Correct way to initialize an array using curly braces
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.
class Car {
this.make = make;
this.model = model;
car.start();
car.stop();
Errors:
this.make = make;
this.model = model;
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).
Objective: To identify and fix errors in a Java program that demonstrates exception handling.
try {
System.out.println(numbers[10]);
} catch (ArrayIndexOutOfBoundsException e) {
return a/b;
Errors:
1. Array Index Out of Bounds Exception Handling
2. Arithmetic Exception Handling
Corrected error:
public class ExceptionHandling {
try {
} catch (ArrayIndexOutOfBoundsException e) {
try {
System.out.println("Result: " + result); // This line will not be reached if an exception occurs
} catch (ArithmeticException e) {
if (b == 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:
if (n <= 1)
return n;
else
int n = 6;
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;
if (n <= 1)
return n;
if (memo.containsKey(n)) {
return memo.get(n);
} else {
memo.put(n, fib);
return fib;
int n = 6;
Errors explained:
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.*;
if (i % j == 0) {
isPrime = false;
break;
if (isPrime) {
primes.add(i);
return primes;
int n = 20;
}
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:
Corrected code:
import java.util.*;
if (n < 2) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(i);
return primes;
int n = 20;
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.