## 1.) Consider the following code segment:

int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i * 2;
}
What is the value of arr[3] after this code segment executes?

A) 0
B) 3
C) 6
D) 8
E) 10

Explanation: The code segment initialises an integer array arr with a length of 5, and then populates it with values based on the index of each element. Specifically, arr[0] is set to 0, arr[1] is set to 2, arr[2] is set to 4, arr[3] is set to 6, and arr[4] is set to 8. Therefore, the correct answer is C) 6.

## 2.) Consider the following code segment:

int[] nums = {3, 5, 7, 9, 11};
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
result += nums[i];
}
}
What is the value of the result after this code segment executes?

A) 0
B) 3
C) 5
D) 9
E) 12

Explanation:Â The code segment initialises an integer array nums with five elements, and then initialises an integer variable result to 0. The for loop iterates through each element of the array nums and checks whether it is even. If an element is even, its value is added to the result. Since none of the elements in nums are even, the result remains 0. Therefore, the correct answer is A) 0.

## 3.) Consider the following code segment:

String s1 = “Hello”;
String s2 = “World”;
String s3 = s1 + s2;
What is the value of s3 after this code segment executes?

A) “HelloWorld”
B) “WorldHello”
C) “Hello World”
D) “World Hello”
E) “Hello” + “World”

Explanation:Â The concatenation of s1 and s2 results in the String “HelloWorld”, which is assigned to s3. Therefore, the correct answer is A) “HelloWorld”.

## 4.) Consider the following code segment:

public static void main(String[] args) {
int x = 5;
while (x > 0) {
System.out.print(x);
x–;
}
System.out.print(“Done!”);
}
What is the output of this code segment?

A) “5 4 3 2 1 Done!”
B) “5 4 3 2 1”
C) “1 2 3 4 5 Done!”
D) “1 2 3 4 5”
E) “Done! 1 2 3 4 5”

Explanation: The code segment initialises an integer variable x to 5 and then enters a while loop that prints the value of x and decrements it by 1 until x is no longer greater than 0. After the loop exits, the String literal “Done!” is printed. Therefore, the output of this code segment is A) “5 4 3 2 1 Done!”.

(A) my_variable
(B) \$price
(C) first_name
(D) 1st_place

## 6.) Which of the following code snippets would create an array of integers with length 5 and initialise the first element to 10?

A) int[] arr = {1, 2, 3, 4, 5};
B) int[] arr = new int[5] {1, 2, 3, 4, 5};
C) int[] arr = new int[] {1, 2, 3, 4, 5};
D) int[] arr = new int[5]; arr[0] = 10;

Explanation:Â The correct answer is D. Option A initialises the array to a different set of values. Option B is incorrect because the size of the array has already been specified in the declaration. Option C is incorrect because it initialises all the elements to specific values. Option D initialises an array of length 5 and sets the first element to 10.

## 7.) Which of the following is the output of the following code snippet?

int x = 5;
int y = 7;
System.out.print(x + y + ” “);
System.out.println(x + y);

A) 12 12
B) 12 5
C) 5 12
D) 57

Explanation:Â The correct answer is A. The first line of code prints the sum of x and y (which is 12), followed by a space. The second line of code adds x and y (which is 12) and prints the result on a new line.

## 8.) Consider the following code snippet:

public class MyClass {
private int x;
public MyClass(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
Which of the following code snippets creates an instance of the MyClass class with an x value of 5 and assigns it to the variable myObj?

A) MyClass myObj = MyClass(5);
B) MyClass myObj = new MyClass(5);
C) myObj = new MyClass(5);
D) MyClass myObj = MyClass(5).getX();

Explanation: The correct answer is B. Option A is incorrect because it is missing the “new” keyword. Option C is incorrect because the variable “myObj” has not been declared before it is assigned. Option D is incorrect because it calls the getX() method, which returns an int, rather than creating an instance of the MyClass class.

## 9.) What is the output of the following code?

int x = 5;
for (int i = 1; i <= 10; i++) {
x += i;
}
System.out.println(x);

A) 50
B) 55
C) 60
D) 65

Explanation: The correct answer is D. The for loop iterates from i=1 to i=10 and adds the value of i to x in each iteration. After the loop completes, x will be equal to 5 + 1 + 2 + … + 10 = 65.

## 10. Which of the following correctly declares an array of strings with length 3 and initialises the first element to “hello”?

A) String[] arr = [“hello”, “”, “”];
B) String[] arr = new String[] {“hello”, “”, “”};
C) String[] arr = {“hello”, “”, “”};
D) String[] arr = new String[3] {“hello”, “”, “”};

Explanation: The correct answer is C. Option A is incorrect because square brackets cannot be used to initialise arrays in Java. Option B is correct syntax but redundant as the size of the array is already specified. Option D is incorrect because the initialization list and size declaration should be separated by either the equals sign or semicolon, but not both.

## 11.) Which of the following correctly declares and initialises a two-dimensional array of integers with 3 rows and 4 columns?

A) int[][] arr = new int[3, 4];
B) int[][] arr = new int[3][4];
C) int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
D) int[][] arr = new int[4][3] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

Explanation: The correct answer is B. Option A is incorrect because square brackets are used instead of curly braces to declare a two-dimensional array. Option C initialises the array but does not declare it. Option D declares a two-dimensional array of size 4×3 instead of 3×4 and also uses incorrect syntax to initialise it.

## 12.) Which of the following data structures is implemented using a Last-In-First-Out (LIFO) policy?

(A) Queue
(B) Stack
(C) Set
(D) Map

Explanation: The correct answer is (B) Stack. A stack is a data structure where the last item that was added is the first item to be removed.

## 13.) What is the output of the following code?

int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ” “);
}
System.out.println(arr);

A) 1 2 3 [I@3e3abc88
B) 1 2 3 [1, 2, 3]
C) [1, 2, 3]
D) An ArrayIndexOutOfBoundsException is thrown.

Explanation: The correct answer is A. The for loop iterates through the elements of the array and prints them, separated by spaces. The second println statement prints the address of the array object. The [I indicates that it is an array of ints, and the following hexadecimal value is the hash code of the object.

## 14.) Which of the following code snippets creates a new ArrayList object that can hold integers?

A) ArrayList arr = new ArrayList();
B) ArrayList<Integer> arr = new ArrayList<Integer>();
C) ArrayList arr = new ArrayList<Integer>();
D) ArrayList<Integer> arr = new ArrayList();

Explanation: The correct answer is D. Option A declares an ArrayList without specifying the type of objects it can hold. Option B is correct syntax but redundant since Java 7. Option C is incorrect because the type of objects in the ArrayList must be specified in the angle brackets.

## 15.) Consider the following code snippet:

int x = 5;
int y = 7;
if (x > y) {
System.out.println(“x is greater than y”);
} else {
System.out.println(“x is not greater than y”);
}
if (x == y) {
System.out.println(“x is equal to y”);
} else {
System.out.println(“x is not equal to y”);
}
What is the output of the code?

A) x is greater than y, x is not equal to y
B) x is not greater than y, x is not equal to y
C) x is not greater than y, x is equal to y
D) x is greater than y, x is equal to y

Explanation: The correct answer is B. The first if statement is false, so the else block is executed and “x is not greater than y” is printed. The second if statement is also false, so the second else block is executed and “x is not equal to y” is printed.

## 16.) What is the output of the following code?

String str = “hello”;
str.concat(” world”);
System.out.println(str);

A) “hello world”
B) “hello”
C) ” world”
D) An error is thrown.

Explanation: The correct answer is B. The concat method returns a new string that concatenates the calling string with the specified string. However, since the original string object is not modified, the println statement still outputs “hello”.

## 17.) Consider the following code snippet:

public class MyClass {
private int x;
public MyClass() {
this(0);
}
public MyClass(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
Which of the following instantiates a new MyClass object with an x value of 5?

A) MyClass obj = new MyClass();
B) MyClass obj = new MyClass(5);
C) obj.setX(5);
D) obj = 5;

Explanation: The correct answer is B. The constructor MyClass(int x) initialises the private instance variable x to the value passed as an argument. Option A calls the default constructor, which initialises x to 0. Option C attempts to access a non-existent method, and option D assigns an integer value to an object reference.

## 18.) What is the output of the following code?

int[] arr = {1, 2, 3};
for (int i = arr.length – 1; i >= 0; i–) {
System.out.print(arr[i] + ” “);
}

A) “3 2 1”
B) “1 2 3”
C) “3 1 2”
D) An error is thrown.

Explanation: The correct answer is A. The for loop iterates through the elements of the array in reverse order, starting from the last element and ending with the first element. The elements are printed in reverse order, separated by spaces.

## 19.) Which of the following code snippets correctly removes the first occurrence of the element “dog” from an ArrayList of strings named “animals”?

A) animals.delete(“dog”);
B) animals.remove(“dog”);
C) animals.remove(0);
D) animals.removeFirst(“dog”);

Explanation: The correct answer is B. The remove method of ArrayList removes the first occurrence of the specified element from the list, if it exists. Option A is not a valid method of ArrayList. Option C removes the first element of the list, regardless of its value. Option D is not a method of ArrayList.

## 20. What is the output of the following code?

public class MyClass {
public static int x = 0;
public MyClass() {
x++;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println(x);
}
}

A) 1
B) 2
C) 3
D) An error is thrown.

Explanation: The correct answer is B. The static variable x is incremented each time a MyClass object is instantiated, and the main method creates two objects. Therefore, x is equal to 2 when it is printed.

## 21.) What is the output of the following code?

int x = 5;
int y = 10;
int z = 15;
System.out.println(x + y + “” + z);

A) 30
B) 515
C) 5 + 10 + 15
D) 25 + 15
E) 51015

Explanation: The code concatenates the values of x, y, and z as strings and prints the result. The output will be “51515” because the addition operator “+” is used for both arithmetic addition and string concatenation in Java. Therefore, x + y is evaluated as 15, which is then concatenated with the string value of z, resulting in “515”. Hence, the answer isÂ B) 515

## 22.) What is the output of the following code?

String s = “APCS”;
System.out.println(s.substring(0,2) + s.charAt(2) + s.substring(2));

A) “APCS”
B) “APSC”
C) “APC”
D) “APS”
E) “ASPC”

Explanation: The substring method returns the portion of the string starting at the specified index and ending at the specified index minus one. The charAt method returns the character at the specified index. The code outputs “APCS” because s.substring(0,2) returns “AP”, s.charAt(2) returns “C”, and s.substring(2) returns “S”. Therefore, the concatenation of these three strings is “APCS”.

## 23.) What is the output of the following code?

int[] a = {1, 2, 3};
int[] b = a;
b[0] = 4;
System.out.println(a[0]);

A) 1
B) 2
C) 3
D) 4
E) It will throw an ArrayIndexOutOfBoundsException.

Explanation: The code creates an array a with the values {1, 2, 3} and assigns it to array b. The statement b[0] = 4 changes the value of the first element in the array b to 4. Since a and b refer to the same array in memory, this change affects both arrays. Therefore, the output is 4.

## 24.) What is the output of the following code?

int x = 5;
int y = 3;
System.out.println((double) x / y);

A) 1.6666666666666667
B) 1
C) 1.5
D) 2
E) 5 / 3

Explanation: The expression (double) x / y first casts x to a double and then performs a floating-point division of x by y. Therefore, the output is the quotient of 5.0 and 3.0, which is 1.6666666666666667.

## 25.) What is the output of the following code?

public class MyClass {
public static void main(String[] args) {
String s = “APCS”;
for (int i = 0; i < s.length(); i += 2) {
System.out.print(s.charAt(i) + ” “);
}
}
}

A) “A C”
B) “AC”
C) “A C S”
D) “ACS”
E) It will throw a NullPointerException.

Explanation: The code loops through the characters of the string s using an index variable that increments by 2 on each iteration. Therefore, it prints the characters at the even positions in the string, which are ‘A’ and ‘C’. The output is “A C”.

## 26.) What is the output of the following code?

public class MyClass {
public static void main(String[] args) {
int x = 3;
while (x > 0) {
x–;
System.out.print(x + ” “);
}
}
}

A) “0 1 2”
B) “1 2 3”
C) “2 1 0”
D) “2 1”
E) “0 1”

Explanation: The code initialises x to 3 and enters a while loop that continues as long as x is greater than 0. Inside the loop, x is decremented by 1 and its value is printed. Therefore, the output is “2 1 0”.

## 27.) Which of the following is an advantage of using an interface in Java?

A) An interface can provide a default implementation for methods.
B) A class can implement multiple interfaces.
C) An interface can have instance variables.
D) An interface can be instantiated.

Explanation: The correct answer is B) A class can implement multiple interfaces. One of the key advantages of using interfaces in Java is that a class can implement multiple interfaces, allowing for more flexibility and modularity in software design. Options A and C are incorrect because interfaces cannot have instance variables or default method implementations. Option D is incorrect because interfaces cannot be instantiated.

## 28.) What is the output of the following code?

int x = 4;
int y = 2;
while (x > y) {
x -= y;
}
System.out.println(x);

A) 0
B) 1
C) 2
D) 3
E) 4

Explanation: The while loop subtracts y from x repeatedly until x is no longer greater than y. In this case, x will become 0, so the output is A) 0.

## 29.) What is the value of the variable z after the following code is executed?

int x = 5;
int y = 3;
int z = x % y;

A) 0
B) 1
C) 2
D) 3
E) 5

Explanation: The % operator performs modulus division, which calculates the remainder of dividing x by y. In this case, x divided by y is 1 with a remainder of 2, so z is assigned the value of 2.Â The correct answer is C) 2.

## 30.) Which of the following code segments correctly swaps the values of two variables x and y?

A) int temp = x;
x = y;
y = x;

B) int temp = x;
x = y;
y = temp;

C) int x = y;
int y = x;

D) int temp = x;
x = y;
x = temp;

E) int temp = x;
y = x;
x = temp;

Explanation: Option B) is the correct answer. It uses a temporary variable temp to store the value of x before overwriting it with the value of y, and then assigns the value of temp to y. This correctly swaps the values of x and y. Options A), C), D), and E) all contain errors and would not correctly swap the values of the variables.

## 31.) Which of the following statements is true about a recursive method?

A) A recursive method must have a return statement.
B) A recursive method can only call itself once.
C) A recursive method can result in a stack overflow error if it calls itself too many times.
D) A recursive method cannot have any parameters.
E) A recursive method must have a base case.

Explanation: Option C) is the correct answer. A recursive method can call itself multiple times, but if it does so too many times, it can cause the call stack to overflow and result in a stack overflow error. Options A), B), and D) are incorrect; a recursive method does not necessarily have to have a return statement, can call itself more than once, and can have parameters. Option E) is partially correct; a recursive method should have a base case to prevent infinite recursion, but it is not strictly required.

## 32.) What is the output of the following code?

int i = 0;
while (i < 5) {
i++;
}
System.out.println(i);

A) 0
B) 4
C) 5
D) 6
E) 7

Explanation: The while loop increments i until it reaches the value of 5, and then the loop terminates. The value of i is then printed, which is 5. Therefore, the output is C) 5.

## 33.) What is the output of the following code?

String s = “hello”;
s.toUpperCase();
System.out.println(s);
A) hello
B) Hello
C) HELLO
D) The code will not compile due to an error.
E) The output cannot be determined.

Explanation: The toUpperCase() method converts the characters in the string to uppercase. However, in this code, the result of the method call is not assigned to a variable, so the original value of s remains unchanged. Therefore, the output is A) hello.

## 34.) Which of the following code segments correctly declares an array of integers with a length of 5 and assigns the value 2 to the first element?

A) int[] a = new int[5] {2};

B) int[] a = new int[5];
a[1] = 2;

C) int[] a = new int[5];
a[0] = 2;

D) int[] a = {2, 0, 0, 0, 0};

E) int[] a = new int[]{2, 0, 0, 0, 0};

Explanation: Option C) is the correct answer. It declares an array of integers with a length of 5 and assigns the value 2 to the first element, which has an index of 0. Option A) contains a syntax error; the length of the array should be specified in the declaration, not in the initializer. Option B) assigns the value 2 to the second element of the array, which has an index of 1. Option D) initialises the array with 5 elements, but the value 2 is assigned to the first element, not the zeroth element. Option E) initialises the array with 5 elements and assigns the value 2 to the first element, but it is more verbose than option C).

## 35.) What is the output of the following code?

for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.print(i);
}

A) 01234
B) 0123
C) 012
D) 1234
E) 12345

Explanation: The for loop iterates from 0 to 4, but when i reaches the value of 3, the break statement is executed and the loop terminates early. Therefore, the output is B) 0123.

## 36.) What is the output of the following code?

public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println(sum / arr.length);
}

A) 5
B) 6
C) 7
D) 8
E) 10

Explanation: The code calculates the average value of the elements in the arr array by summing them and dividing by the length of the array. The sum of the elements is 30, and the length of the array is 5, so the average is 6. Therefore, the output is B) 6.

## 37.) What is the output of the following code?

int x = 5;
while (x > 0) {
x–;
System.out.print(x);
}

A) 543210
B) 43210
C) 54321
D) 4321
E) 3210

Explanation: The while loop decrements x from 5 to 0, and then the loop terminates. The value of x is printed at each iteration of the loop, so the output is A) 543210.

## 38.) What is the output of the following code?

int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println(arr[1][2]);

A) 1
B) 2
C) 3
D) 4
E) 6

Explanation: The code initialises a 2D array arr with three rows and three columns, and then prints the value of the element in the second row and third column, which is 6. Therefore, the output is E) 6.

## 39.) What is the output of the following code?

for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}

A) 12345
1234
123
12
1
B) 54321
4321
321
21
1
C) 11111
2222
333
44
5
D) 11111
22222
33333
44444
55555

Explanation: The code contains a nested loop that prints a series of numbers in a pattern. At each iteration of the outer loop, the inner loop prints the numbers 1 through the value of i, inclusive. Then the outer loop prints a newline character. Therefore, the output is:
1
12
123
1234
12345

So the answer is A) 12345.

## 40. What is the output of the following code snippet?

public class Example {
public static void main(String[] args) {
String s = “Hello, world!”;
for (int i = 0; i < s.length(); i += 2) {
System.out.print(s.charAt(i));
}
}
}

A) Hlo ol!
B) Hlo,wrd
C) Hl,o!l
D) H,eolrd
E) Hlwrd

Explanation: The code loops through the characters in the string s, starting at index 0 and incrementing i by 2 each time. Therefore, it prints the characters at indices 0, 2, 4, 6, 8, and 10, which are “H”, “l”, “o”, ” “, “!”, and the end of the string. The correct answer is (A).

Our Guide is written by counselors from Cambridge University for colleges like MIT and other Ivy League colleges.

## Question 1

a)Write a program that reads in a list of integers from the user and sorts them using the bubble sort algorithm.Â

b)Your program should print out the sorted list of integers.Â

c)In addition, write a short paragraph explaining the efficiency of the bubble sort algorithm and compare it to at least one other sorting algorithm.

### Solution:

import java.util.Scanner;

public class BubbleSort {

Â Â Â Â public static void main(String[] args) {

Â Â Â Â Â Â Â Â Scanner input = new Scanner(System.in);

Â Â Â Â Â Â Â Â System.out.print(“Enter the number of integers you want to sort: “);

Â Â Â Â Â Â Â Â int n = input.nextInt();

Â Â Â Â Â Â Â Â int[] arr = new int[n];

Â Â Â Â Â Â Â Â System.out.print(“Enter ” + n + ” integers: “);

Â Â Â Â Â Â Â Â for (int i = 0; i < n; i++) {

Â Â Â Â Â Â Â Â Â Â Â Â arr[i] = input.nextInt();

Â Â Â Â Â Â Â Â }

Â Â Â Â Â Â Â Â bubbleSort(arr);

Â Â Â Â Â Â Â Â System.out.print(“Sorted integers: “);

Â Â Â Â Â Â Â Â for (int i = 0; i < n; i++) {

Â Â Â Â Â Â Â Â Â Â Â Â System.out.print(arr[i] + ” “);

Â Â Â Â Â Â Â Â }

Â Â Â Â }

public static void bubbleSort(int[] arr) {

Â Â Â Â Â Â Â Â int n = arr.length;

Â Â Â Â Â Â Â Â for (int i = 0; i < n – 1; i++) {

Â Â Â Â Â Â Â Â Â Â Â Â for (int j = 0; j < n – i – 1; j++) {

Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if (arr[j] > arr[j + 1]) {

Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int temp = arr[j];

Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â arr[j] = arr[j + 1];

Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â arr[j + 1] = temp;

Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }

Â Â Â Â Â Â Â Â Â Â Â Â }

Â Â Â Â Â Â Â Â }

Â Â Â Â }

}

The bubble sort algorithm is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

The efficiency of the bubble sort algorithm is O(n^2), where n is the number of elements in the list. This means that the time it takes to sort the list increases exponentially with the number of elements.

In comparison to other sorting algorithms, such as merge sort or quicksort, the bubble sort algorithm is not very efficient for large data sets. Merge sort and quicksort have a time complexity of O(n log n), which means they are much faster than bubble sort for large data sets. However, bubble sort is still useful for small data sets or when simplicity is more important than efficiency.

## Question 2

a)Create a class named Car with the following properties: make, model, year, price, and mileage.Â

b)Write a constructor for the class that takes in values for each property and initialises them.Â

c)Create a toString() method that returns a string representation of the Car object in the following format: Year Make Model, Mileage miles, \$Price.

d)In addition, create a method named isExpensive() that returns true if the car is priced over \$20,000 and false otherwise.

e)Finally, write a program that creates an array of Car objects and sorts them by price from lowest to highest using the Arrays.sort() method. Print out the sorted array of Car objects.

### Solution:

import java.util.Arrays;

public class Car implements Comparable<Car> {

Â Â Â Â private String make;

Â Â Â Â private String model;

Â Â Â Â private int year;

Â Â Â Â private double price;

Â Â Â Â private int mileage;

public Car(String make, String model, int year, double price, int mileage) {

Â Â Â Â Â Â Â Â this.make = make;

Â Â Â Â Â Â Â Â this.model = model;

Â Â Â Â Â Â Â Â this.year = year;

Â Â Â Â Â Â Â Â this.price = price;

Â Â Â Â Â Â Â Â this.mileage = mileage;

Â Â Â Â }

public String toString() {

Â Â Â Â Â Â Â Â return year + ” ” + make + ” ” + model + “, ” + mileage + ” miles, \$” + price;

Â Â Â Â }

public boolean isExpensive() {

Â Â Â Â Â Â Â Â return price > 20000;

Â Â Â Â }

public int compareTo(Car other) {

Â Â Â Â Â Â Â Â return Double.compare(this.price, other.price);

Â Â Â Â }

public static void main(String[] args) {

Â Â Â Â Â Â Â Â Car[] cars = new Car[3];

Â Â Â Â Â Â Â Â cars[0] = new Car(“Toyota”, “Corolla”, 2010, 15000, 50000);

Â Â Â Â Â Â Â Â cars[1] = new Car(“Honda”, “Civic”, 2015, 18000, 30000);

Â Â Â Â Â Â Â Â cars[2] = new Car(“Ford”, “Mustang”, 2018, 30000, 20000);

Arrays.sort(cars);

Â Â Â Â Â Â Â Â for (Car car : cars) {

Â Â Â Â Â Â Â Â Â Â Â Â System.out.println(car);

Â Â Â Â Â Â Â Â }

Â Â Â Â }

}

The Car class has five properties: make, model, year, price, and mileage. The constructor takes in values for each property and initialises them. The toString() method returns a string representation of the Car object in the format specified in the question. The isExpensive() method returns true if the car is priced over \$20,000 and false otherwise.

The Car class implements the Comparable interface so that it can be sorted by price using the Arrays.sort() method. The compareTo() method compares two Car objects based on their price.

In the main method, an array of Car objects is created and initialised with three Car objects. The array is then sorted using Arrays.sort(). Finally, the sorted array is printed out using a for-each loop.

## Question 3

Consider the following PigLatinConverter class that allows a line of text to be converted to Pig Latin.

a.) Write the method toPig in the PigLatinConverter class. This method should convert a word to Pig Latin according to the following rules:

If the word begins with a consonant, move the consonant to the end of the word and add “ay” after it.
If the word begins with a vowel, add “yay” to the end of the word.
public class PigLatinConverter {
public static String toPig(String word) {
// Write the implementation for converting a word to Pig Latin
// If the word begins with a consonant, move the consonant to the end of the word and add “ay” after it
// If the word begins with a vowel, add “yay” to the end of the word
// Return the converted word
}
}

b.) Write the method getLineWords in the PigLatinConverter class. This method should extract words from a given line of text and store them in an ArrayList. Assume that the line contains at least one word, has no punctuation, and words are separated by a single space.

import java.util.ArrayList;
public class PigLatinConverter {
public static ArrayList<String> getLineWords(String line) {
// Write the implementation for extracting words from the line and storing them in an ArrayList
// Assume that line contains at least one word, no punctuation, and words are separated by one space
// Return the ArrayList of words
}
}

(c) Write the method pigLatin in the PigLatinConverter class. This method should convert all the words in a given line of text to Pig Latin. You can use the toPig and getLineWords methods as specified in parts A and B. The modified line, converted to Pig Latin, should be returned as a String.

import java.util.ArrayList;
public class PigLatinConverter {
// Incomplete declarations
public static String pigLatin(String line) {
// Write the implementation for converting all the words in the line to Pig Latin
// You may call the toPig and getLineWords methods as specified in parts A and B
Â // Return the modified line in Pig Latin
}
}

### Solution:

a.)
public class PigLatinConverter {
public static String toPig(String word) {
char firstChar = Character.toLowerCase(word.charAt(0));
String pigLatinWord = “”;

if (isVowel(firstChar)) {
pigLatinWord = word + “yay”;
} else {
pigLatinWord = word.substring(1) + word.charAt(0) + “ay”;
}
return pigLatinWord;
}
private static boolean isVowel(char ch) {
return ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’;
}
}

b.)
import java.util.ArrayList;
public class PigLatinConverter {
public static ArrayList<String> getLineWords(String line) {
String[] words = line.split(” “);
ArrayList<String> wordList = new ArrayList<>();
for (String word : words) {
}
return wordList;
}
}

c.)
import java.util.ArrayList;
public class PigLatinConverter {
public static String pigLatin(String line) {
ArrayList<String> wordList = getLineWords(line);
StringBuilder pigLatinLine = new StringBuilder();
for (String word : wordList) {
pigLatinLine.append(toPig(word)).append(” “);
}
return pigLatinLine.toString().trim();
}
// Rest of the code from parts (a) and (b)
}

## Question 4

The NumberCode class fills a two-dimensional square array, in row-major order, with integer values of digits from the input string. Then, the number code is created by building an integer from the digits in the major diagonal (starting in the top left-hand corner) of the matrix. You need to complete the implementation of the NumberCode class by filling in the missing methods.

a.) Write the fillArray method that fills the two-dimensional square array numMatrix with single-digit values obtained from its string parameter str. The array must be filled in row-major order, meaning the first row is filled from left to right, then the second row is filled from left to right, and so on, until all rows are filled. If the length of the parameter str is smaller than the number of elements of the array, the value 0 is placed in each of the unfilled cells. If the length of str is larger than the number of elements in the array, the remaining characters are ignored. The digits of str need to be converted to their integer values before being placed in the matrix. The NumberCode class provides a method for doing this.

public class NumberCode {
private int[][] numMatrix;
public NumberCode(int size) {
numMatrix = new int[size][size];
}
// Write the implementation for fillArray method
// The array must be filled in row-major order
return code;
}
}

b.) Write the getNumberCode method that extracts and builds a number code from its string parameter digitStr. The method fills numMatrix with the values of the digits in digitStr and then constructs a code number from the digits of the major diagonal of numMatrix, starting with the top left-hand corner.

public int getNumberCode(String digitStr) {
// Write the implementation for getNumberCode method
// It should fill numMatrix with the values of the digits in digitStr
// Then, construct a code number from the digits of the major diagonal of numMatrix
// Starting with the top left-hand corner
// You should utilize the fillArray method
fillArray(digitStr);

### Solution:

(Solution consists of (a) and (b) combined)

public class NumberCode {
private int[][] numMatrix;
public NumberCode(int size) {
numMatrix = new int[size][size];
}
public void fillArray(String str) {
int size = numMatrix.length;
int index = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (index < str.length()) {
numMatrix[i][j] = Integer.parseInt(str.substring(index, index + 1));
index++;
} else {
numMatrix[i][j] = 0;
}
}
}
}

public int getNumberCode(String digitStr) {
fillArray(digitStr);
int size = numMatrix.length;
int code = 0;
for (int i = 0; i < size; i++) {
code = code * 10 + numMatrix[i][i];
}
return code;
}
}

The NumberCode class is defined with a two-dimensional integer array numMatrix as its instance variable.

The fillArray method takes a string str as a parameter and fills the numMatrix array with the single-digit values obtained from str. The method iterates over the rows and columns of the matrix, checking if there are still digits remaining in str. If there are, the digits are converted to integers using Integer.parseInt and placed in the corresponding cell of numMatrix. If there are no more digits in str, the remaining cells are filled with zeros.

The getNumberCode method takes a string digitStr as a parameter. It calls the fillArray method to populate the numMatrix with the digits from digitStr. Then, it iterates over the major diagonal of numMatrix, constructing the code number by concatenating the digits. The code number is returned as the result.

With this complete implementation of the NumberCode class, you can create an instance of NumberCode, call the fillArray method to fill the matrix, and then call the getNumberCode method to extract the number code from the major diagonal of the matrix.

## Our Expert Tutors!

### Jinu James

IBDP Physics
ap physics c mechanics

IBDP MATH AAHL
ap calculus bc

### Shimaila Mushtaq

IBDP Economics
ap microeconomics

IBDP Chemistry
AP Chemistry

IBDP Psychology
AP Psychology

Edit Template

View Here

get it here

Explore Here

Know More

Edit Template