Final Exam Review Solutions

Practice Questions

1. Find the syntax/logic errors:

a.

// the class definition:
public class MyClass 
{
	private int counter;
	private String name;

	public void MyClass() {
		counter = 1;
		name = "Kaluha";
	}
	public int setCounter(int counter) {
		if (counter > 0)
			this.counter = counter;
		else 
			throw new IllegalArgumentException("Invalid counter.");
	}

	public int getCounter() { return counter; }

	public String toString() {
		return name + "\n";
	}
}
// the test class:
public class TestMyClass 
{
	public static void main(String[] args) 
	{
		MyClass mc = new MyClass();
		mc.setCounter(5);
		for (int i=1; i<=mc.getCounter(); i++)
		{
			System.out.println(mc);
		}
	}
}

b.

public static void main(String args) {
    int[] numbers = new int[10];
    for (int i=0; i<=numbers.length; i++) {
        numbers[i] = (int)(Math.random() * 100 + 1);
    }
    Scanner in = new Scanner(System.in);
    System.out.print("Enter an index: ");
    int index = in.nextInt();
    int value = numbers[index];
    System.out.println(display(value));
}
public static double display(int value) {
    return Math.sqrt(value);
}

2. Find the Output:

a.

15
10
true

The arguments value1 and value2 are passed by value (a copy of the variable values are passed into the params min and max). Therefore, when min and max are swapped inside the swap() method, they have no effect at all on the value1 and value2 variables in the main() method.

b.

It prints the array contents backwards. The actual output will depend on what you put into the array.

Coding Questions

Question 1

Question 1. Customer Loyalty Program

Question 2

Question 2. Product Class
Question 2. Kiosk Program

Question 3

Question 3. Count Characters

Question 4

Question 4. Student Scores