AP Computer Science Exam A Practice

Table of Contents

AP computer science exam practice questions on java language are presented along with their answers and detailed explanations.

Questions


  1. What is the output of the following Java code snippet?

    public class Main {
        public static void main(String args[]) {
    	int x = 10;
    	int y = x++ + ++x;
    	System.out.println(y);
        }
    }
    

    Select the correct answer

    A) 20
    B) 21
    C) 22
    D) 23




  2. What is the output of the following Java code snippet?

    public class Main {
        public static void main(String args[]) {
    	int x = 5;
    	int y = x / 2;
    	System.out.println(y);
        }
    }
    

    Select the correct answer

    A) 2
    B) 2.5
    C) 7
    D) 10



  3. What is the output of the following Java code snippet?

    public class Main {
    	public static void main(String args[]) {
    	double x = 1.5;
    	int y = (int) x + 2;
    	System.out.println(y);
    		}
    }
    

    Select the correct answer

    A) 3.5
    B) 4
    C) 2.5
    D) 3



  4. What is the output of the following Java code snippet?

    public class Main {
    	public static void main(String args[]) {
    	int x = 7;
    	boolean y = (x > 5) && (x < 10);
    	System.out.println(y);
        }
    }
    

    Select the correct answer

    A) true
    B) false
    C) 7
    D) 10



  5. what is the output to the code:

    public class Main {
    	public static void main(String args[]) {
    	int x = 7;
    	int y = (int)1.5f;
    	int z = (int)0.55d;
    	if ((x > 5 && y > = 1) && z < 0) {System.out.println("one");} 
    	else if(x==7) {System.out.println("two");} 
    	else if(y==1.5) {System.out.println("three");}
    	else if(z==0) {System.out.println("four");}
    		}
    } 
    

    Select the correct answer

    A) one
    B) two
    C) three
    D) four



  6. What is the output of the following Java code snippet?

    public class Main{
        String name;
        int age;
        public static void main(String[] args) {
            Person p = new Person();
            System.out.println(p.name);
            System.out.println(p.age);
        }
    }
    class Person{
        String name;
        int age;
        }
    

    Select the correct answer

    A) null 0
    B) empty empty
    C) null null
    D) 0 null



  7. What is the output of the following Java code snippet?

    public class Main {
        public static void main(String[] args) {
            Car c1 = new Car(2010, "Honda");
            Car c2 = new Car(2015, "Toyota");
            System.out.println(c1.year + " " + c1.make);
            System.out.println(c2.year + " " + c2.make);
        }
    }
    class Car{
    		int year;
    		String make;
    		public Car(int y, String m) {
            year = y;
            make = m;
        }
    }
    

    Select the correct answer

    A) 2010 Honda 2015 Toyota
    B) 2015 Honda 2010 Toyota
    C) Honda 2010 Toyota 2015
    D) Toyota 2015 Honda 2010



  8. What is the output of the following Java code snippet?

    public class Main {
        public static void main(String[] args) {
            int a = Integer.parseInt("10");
            double b = Double.parseDouble("3.14");
            
            System.out.println(a + b);
        }
    }
    

    Select the correct answer

    A) 13
    B) 10.0
    C) 13.14
    D) 3.14



  9. What is the output of the following Java code snippet?

    public class Main {
        public static void main(String[] args) {
            double num1 = 9.0;
            double num2 = 16.0;
            double result = Math.sqrt(num1*num2);
            System.out.println("The result is " + result);
        }
    } 
    

    Select the correct answer

    A) The result is 20736.0
    B) The result is 144.0
    C) The result is 12.0
    D) The result is 15.0



  10. What is the output of the following Java code snippet?

    public class Dog {
        String name;
        
        public Dog(String name) {
            this.name = name;
        }
        
        public void bark() {
            System.out.println(name + " barks!");
        }
        
        public void wagTail(int speed) {
            System.out.println(name + " wags its tail at " + speed + " mph!");
        }
        
        public static void main(String[] args) {
            Dog myDog = new Dog("Buddy");
            myDog.bark();
            myDog.wagTail(10);
        }
    }
    

    Select the correct answer

    A) Buddy barks! Buddy wags its tail at 10!
    B) Buddy wags its tail at 10 mph!
    C) Buddy! Buddy wags its tail at 10 mph!
    D) Buddy barks! Buddy wags its tail at 10 mph!



  11. What will be the output of the following code snippet?

    import java.util.ArrayList;
    
    public class ArrayListExample {
        public static void main(String[] args) {
            ArrayList colors = new ArrayList();
            colors.add("Red");
            colors.add("Green");
            colors.add("Blue");
    
            System.out.println(colors.get(1));
        }
    }
    

    Select the correct answer

    A) Red
    B) Green
    C) Blue
    D) An error will occur



  12. What is the output of the following Java code snippet?

    public class BooleanExample {
        public static void main(String[] args) {
            int num1 = 5;
            int num2 = 7;
    
            boolean result = num1 < = num2 && num2 != 10;
            System.out.println("The result is " + result);
        }
    }
    

    Select the correct answer

    A) The result is false
    B) The code will not compile
    C) The output cannot be determined
    D) The result is true



  13. What is the output of the code below if the variable "grade" is assigned a value of 75?

    public class GradeCalculator {
        public static void main(String[] args) {
            int grade = 80;
    
            if (grade >= 90) {
                System.out.println("You got an A!");
            } else if (grade >= 80) {
                System.out.println("You got a B!");
            } else if (grade >= 70) {
                System.out.println("You got a C!");
            } else if (grade >= 60) {
                System.out.println("You got a D!");
            } else {
                System.out.println("You got an F!");
            }
        }
    }
    

    Select the correct answer

    A) You got an A!
    B) You got a B!
    C) You got a C!
    D) You got a D!



  14. What is the output of the following Java code snippet?

    public class LoopExample {
        public static void main(String[] args) {
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                if (i % 2 == 0) {
                    sum += i;
                }
            }
            System.out.println(sum);
        }
    }
    

    Select the correct answer

    A) 20
    B) 25
    C) 30
    D) 35



  15. What is the output of the following Java code snippet?

    public class LoopExample {
        public static void main(String[] args) {
    int sum = 0;
    for (int i = 1; i <= 3; i++) {
      for (int j = 1; j <= 4; j++) {
        sum += i*j;
      }
    }
    System.out.println(sum);
        }
    }
    

    Select the correct answer

    A) 12
    B) 30
    C) 60
    D) 72



  16. What is the output of the following Java code snippet?

    public class WhileExample {
        public static void main(String[] args) {
    int num = 1;
    while (num < 10) {
        System.out.print(num + " ");
        num++;
    }
        }
    }
    
    

    Select the correct answer

    A) 1 2 3 4 5 6 7 8 9
    B) 1 2 3 4 5 6 7 8 9 10
    C) 2 4 6 8 10
    D) This code will result in an infinite loop



  17. What would be the output of the code?

    public class MyClass {
       public int x = 5;
       private int y = 10;
       
       public static void main(String[] args) {
          MyClass obj1 = new MyClass();
          MyClass obj2 = new MyClass();
          MyClass2 obj3 = new  MyClass2();
          
          System.out.println(obj1.x + obj2.y + obj3.z);
       }
    }
    
    
    public class MyClass2{
        private int z = 10;
    }
    

    Select the correct answer

    A) The output of the code will be a compilation error
    B) 25
    C) 15
    D) The code will run but there is no output



  18. What is the output of the following Java code snippet?

    public class MyClass {
       private static int x = 5;
       private int y = 10;
       
       public static void main(String[] args) {
          MyClass obj1 = new MyClass();
          MyClass obj2 = new MyClass();
          MyClass.printX();
          obj1.printY();
          obj2.printY();
       }
       
       public static void printX() {
          System.out.println(x);
       }
       
       public void printY() {
          System.out.println(y);
       }
    }
    

    Select the correct answer

    A) 5, 10, 10
    B) 10, 10, 5
    C) 5, 5, 10
    D) 10, 5, 10



  19. What is the output of the following Java code snippet?

    public class ArrayChallenge {
       public static void main(String[] args) {
          int[] numbers = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
          int sum = 0;
          int max = numbers[0];
          
          for (int i = 0; i < numbers.length; i++) {
             if (numbers[i] > max) {
                max = numbers[i];
             }
             if (i % 2 == 0) {
                sum += numbers[i];
             }
          }
          
          System.out.println("The sum of even-indexed elements is: " + sum);
          System.out.println("The maximum element is: " + max);
       }
    }
    
    

    Select the correct answer

    A) The sum of even-indexed elements is: 55. The maximum element is: 20.
    B) The sum of even-indexed elements is: 50. The maximum element is: 20.
    C) The sum of even-indexed elements is: 110. The maximum element is: 20.
    D) The sum of even-indexed elements is: 60. The maximum element is: 20.



  20. What is the output of the following Java code snippet?

    public class SortArray {
        public static void main(String[] args) {
            int[] arr = {5, 8, 2, 9, 1, 4, 6, 3, 7};
    
            for (int i = 0; i < arr.length-1; i++) {
                for (int j = 0; j < arr.length-i-1; j++) {
                    if (arr[j] > arr[j+1]) {
                        int temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
                }
            }
    
            System.out.print("The sorted array is: ");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
        }
    }
    

    Select the correct answer

    A) 9 8 7 6 5 4 3 2 1
    B) 1 2 3 4 5 6 7 8 9
    C) 5 8 2 9 1 4 6 3 7
    D) 1 2 3 4 5 6 7 8 9 10



  21. What is the output of the following Java code snippet?

    
    import java.util.ArrayList;
    
    public class ArrayListExample {
        public static void main(String[] args) {
            ArrayList numbers = new ArrayList();
            numbers.add(5);
            numbers.add(3);
            numbers.add(8);
            numbers.add(1);
    
            int sum = 0;
            for (int i = 0; i < numbers.size(); i++) {
                sum += numbers.get(i);
            }
            double average = (double) sum / numbers.size();
    
            System.out.println("The sum of all numbers in the list is: " + sum);
            System.out.println("The average of all numbers in the list is: " + average);
        }
    }
    
    

    Select the correct answer

    A) The sum of all numbers in the list is: 17 The average of all numbers in the list is: 4.0
    B) The sum of all numbers in the list is: 17 The average of all numbers in the list is: 4.0
    C) The sum of all numbers in the list is: 4.0 The average of all numbers in the list is: 1.0
    D) The sum of all numbers in the list is: 17 The average of all numbers in the list is: 4.25



  22. What is the output of the following Java code snippet?

    import java.util.Arrays;
    
    public class SearchAndSortArray {
        public static void main(String[] args) {
            int[] arr = {3, 5, 8, 1, 6, 9, 4, 2, 7};
            Arrays.sort(arr);
            System.out.println("Sorted array: " + Arrays.toString(arr));
            
            int searchElement = 6;
            int index = Arrays.binarySearch(arr, searchElement);
            
            if (index >= 0) {
                System.out.println(searchElement + " found at index " + index);
            } else {
                System.out.println(searchElement + " not found in the array.");
            }
        }
    }
    

    Select the correct answer

    A) Sorted array: [3, 5, 8, 1, 6, 9, 4, 2, 7] 6 found at index 4
    B) Sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9] 6 found at index 4
    C) Sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9] 6 found at index 5
    D) Sorted array: [3, 5, 8, 1, 6, 9, 4, 2, 7] 6 not found in the array.



  23. What is the output of the following Java code snippet?

    public class MatrixTraversal {
        public static void main(String[] args) {
            int[][] matrix = {{1, 7, 9}, {4, 8, 6}, {2, 5, 3}};
    
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    System.out.print(matrix[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    

    Select the correct answer


    A) 1 7 9
    4 8 6
    2 5 3
    
    B) 1 2 3
    4 5 6
    7 8 9
    
    C) 1 4 2
    7 8 5
    9 6 3
    
    D) 9 8 7
    6 5 4
    3 2 1
    



  24. What is the output of the following Java code snippet?

     class Animal {
        public void makeSound() {
            System.out.println("Animal is making a sound");
        }
    }
    
     class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow");
        }
    }
    
    
     class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Animal[] animals = {new Animal(), new Cat(), new Dog()};
    
            for (Animal animal : animals) {
                animal.makeSound();
            }
        }
    }
    
    

    Select the correct answer


    
    A) Meow
    Woof
    Animal is making a sound
    
    B) Animal is making a sound Meow Woof
    C) Animal is making a sound
    D) Meow Woof



  25. What is the output of the following Java code snippet?

    class Animal {
        public void makeSound() {
            System.out.println("Animal is making a sound");
        }
    }
    
    class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow");
        }
    }
    
    class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Animal[] animals = {new Animal(), new Cat(), new Dog()};
    
            for (Animal animal : animals) {
                animal.makeSound();
            }
            
            Animal a = new Cat();
            System.out.println(a instanceof Animal);
            System.out.println(a instanceof Cat);
        }
    }
    
    

    Select the correct answer


    
    
    A) Animal is making a sound
    Meow
    Woof
    true
    false
    
    
    B) Animal is making a sound
    Meow
    Woof
    true
    true
    
    C) Animal is making a sound
    Meow
    Woof
    false
    true
    
    D) Animal is making a sound
    Meow
    Woof
    false
    false
    



  26. What is the output of the following Java code snippet?

    public class RecursiveSum {
        public static int sum(int n) {
            if (n == 1) {
                return 1;
            } else {
                return n + sum(n-1);
            }
        }
        public static void main(String[] args) {
            System.out.println(sum(5));
        }
    }
    

    Select the correct answer

    A) 10
    B) 11
    C) 15
    D) 12



  27. What is the output of the following Java code snippet?

    
    import java.util.Arrays;
    
    public class BinarySearchExample {
    
        public static void main(String[] args) {
            int[] arr = {4, 7, 13, 20, 22, 26, 30};
            int key = 22;
            int result = binarySearch(arr, key);
            if (result == -1) {
                System.out.println("Key not found in array");
            } else {
                System.out.println("Key found at index " + result);
            }
        }
    
        public static int binarySearch(int[] arr, int key) {
            int left = 0;
            int right = arr.length - 1;
    
            while (left < = right) {
                int mid = left + (right - left) / 2;
    
                if (arr[mid] == key) {
                    return mid;
                } else if (arr[mid] < key) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
    
            return -1;
        }
    }
    
    

    Select the correct answer

    A) Key not found in array
    B) Key found at index 4
    C) Key found at index 5
    D) Compilation error

Answers with Detailed Explanations



  1. Answer: C

    Explanations

    The value of x is first used in a post-increment operation (x++), which evaluates to 10. Then, x is incremented with a pre-increment operation (++x), which makes x equal to 12. Finally, the sum of these two values (10 + 12 = 22) is assigned to y.



  2. Answer: A

    Explanations

    The integer division operator (/) is used to divide x by 2, which results in an integer value of 2.



  3. Answer: D

    Explanations

    The double value of x (=1.5) is cast to an integer value using the (int) type cast operator. This results in the value 1. Then, 2 is added to 1, resulting in 3. Finally, the value of y (=3) is printed.



  4. Answer: A

    Explanations

    The boolean expression (x > 5) && (x < 10) evaluates to true, since x is greater than 5 and less than 10. This value (true) is then assigned to the boolean variable y, which is printed by the output statement.



  5. Answer: B

    Explanations

    The integer variable x is initialized with the value 7. The integer variable y is initialized with the value of a typecasted float 1.5, which evaluates to 1. The integer variable z is initialized with the value of a typecasted double 0.55, which evaluates to 0.
    The if statement condition checks if x is greater than 5 and y is greater than or equal to 1 and z is less than 0. However, z is not less than 0, so the first if statement block is not executed.
    The else if condition checks if x is equal to 7, which evaluates to true.
    The message "two" is printed to the console as a result of the second else if statement block being executed.
    The rest of the else if statements are not evaluated because the second else if statement condition evaluates to true.



  6. Answer: A

    Explanations

    The Person class has two instance variables, name and age. When a new object of this class is created in the main() method using the new keyword, its instance variables are initialized to their default values of null for name and 0 for age. Therefore, the output of the two System.out.println() statements will be null and 0, respectively.



  7. Answer: A

    Explanations

    The Car class has two instance variables, year and make, and a constructor that takes two parameters to initialize them. In the main() method, two new objects of this class are created by calling the constructor with different arguments. Therefore, the output of the two System.out.println() statements will be 2010 Honda and 2015 Toyota, respectively.



  8. Answer: C

    Explanations

    The Integer.parseInt() method converts a string representation of an integer to an actual int value (a = 10). The Double.parseDouble() method converts a string representation of a double to an actual double value (b = 3.14). Hence a + b = 13.14.



  9. Answer: C

    Explanations

    num1 is assigned the value of 9.0 and num2 is assigned the value of 16.0. The product of these two numbers is 144.0. "Math.sqrt" takes the square root of a number. Hence the square root of 144.0 is 12.0.



  10. Answer: D

    Explanations

    In the main() method, a new instance of the Dog class is created with the name "Buddy". The bark() method is then called on the myDog object, which prints "Buddy barks!" to the console. Finally, the wagTail() method is called on the myDog object with a parameter of 10, which prints "Buddy wags its tail at 10 mph!" to the console.



  11. Answer: B

    Explanations

    "import java.util.ArrayList;" is a statement in Java that imports the ArrayList class from the java.util package into the current program.
    The code creates an ArrayList of Strings called colors and adds three elements to it. Then, it uses the get() method to retrieve the element at index 1, which is "Green". Therefore, the output will be "Green".



  12. Answer: D

    Explanations

    The integer num1 is less than or equal to num2 and num2 is not equal to 10. Therefore, the expression num1 <= num2 && num2 != 10 evaluates to true. Therefore, the output of the code will be "The result is true", and the correct answer is D.



  13. Answer: C

    Explanations

    When the variable grade is assigned a value of 75, the code will check the first if statement which evaluates to false. It will then move to the second else if statement which evaluates to false as well. The code will then move to the third else if statement which evaluates to true since 75 is greater than or equal to 70. As a result, the output will be "You got a C!".



  14. Answer: C

    Explanations

    This program creates a loop that iterates over the numbers 1 through 10. For each number, the program checks whether it is even (i.e. divisible by 2), and if so, adds it to a running total. Finally, the program prints out the sum of all even numbers between 1 and 10 (which should be 2+4+6+8+10 = 30).



  15. Answer: C

    Explanations

    This code uses nested loops to iterate over all combinations of i and j values from 1 to 3 and 1 to 4 respectively, computing the product of i and j for each pair and adding it to the sum variable. The output will be the final value of sum, which is computed as follows:
    sum = 1*1 + 1*2 + 1*3 + 1*4 +
          2*1 + 2*2 + 2*3 + 2*4 +
          3*1 + 3*2 + 3*3 + 3*4
        = 10 + 20 + 30
        = 60
    



  16. Answer: A

    Explanations

    The while loop will continue to execute the block of code as long as the condition num < 10 is true. In this case, num is initially set to 1 and each time the loop iterates, num is incremented by 1. The System.out.print(num + " ") statement prints the value of num followed by a space.
    So the output of this code will be a sequence of numbers from 1 to 9 separated by spaces. The loop will terminate when num is incremented to 10 and the condition num < 10 is no longer true.



  17. Answer : A

    Explanations

    The output of the code will give a compilation error because z has private access in MyClass2.



  18. Answer: A

    Explanations

    The output of the code will be "5, 10, 10". The "printX" method is a static method that prints the value of the static variable "x". When this method is called, it prints the value of "x", which is 5. The "printY" method is an instance method that prints the value of the instance variable "y". When this method is called on both "obj1" and "obj2", it prints the value of "y", which is 10 in both cases.



  19. Answer B

    Explanations

    Elements of array numbers has the following values:
    numbers[0] = 2, numbers[1] = 4, numbers[2] = 6, numbers[3] = 8, numbers[4] = 10, numbers[5] = 12, numbers[6] = 14, numbers[7] = 16, numbers[8] = 18, numbers[9] = 20
    The sum of elements with index such that i % 2 == 0 (even-indexed) is calculated as follows:
    numbers[0] + numbers[2] + numbers[4] + numbers[6] + numbers[8] = 2 + 6 + 10 + 14 + 18 = 50.
    The the maximum element in the array is numbers[9] = 20.



  20. Answer : B

    Explanations

    The code is an example of a sorting algorithm that uses a nested loop to compare adjacent elements of an array and swap them if they are not in the correct order.
    Inside the nested loops, the code compares adjacent elements and swaps them if they are not in the correct order. This continues until the entire array is sorted in ascending order. Finally, the sorted array is printed to the console using a for loop and the Arrays.toString() method.



  21. Answer: D

    Explanations

    The code creates an ArrayList of integers, adds four values to it, and then uses a for loop to iterate over all the elements in the list and calculate the sum of all the numbers. It then divides the sum by the size of the list to compute the average. Finally, it prints out the sum and average values using the System.out.println() method. The correct output is "The sum of all numbers in the list is: 17" and "The average of all numbers in the list is: 4.25".



  22. Answer: C

    Explanations

    The code sorts the array using the Arrays.sort() method, which results in the sorted array [1, 2, 3, 4, 5, 6, 7, 8, 9]. Then it searches for the element 6 in the array using the Arrays.binarySearch() method, which returns the index of the element if found. In this case, it finds 6 at index 5 and the output is "6 found at index 5".



  23. Answer: A

    Explanations

    The code above is traversing a 2D array using nested iteration statements and printing out each element of the matrix on a separate line. The outer loop iterates through each row of the matrix, while the inner loop iterates through each element in the row.



  24. Answer: B

    Explanations

    The code defines an Animal class with a makeSound() method, and two subclasses, Cat and Dog, that override the makeSound() method to produce different sounds. In the main() method, an array of Animal objects is created with an Animal, Cat, and Dog object. A for loop iterates over the animals array, and for each element, it calls the makeSound() method. Since the array contains one Animal, one Cat, and one Dog object, the output will be "Animal is making a sound", "Meow", and "Woof" in that order.



  25. Answer: B

    Explanations

    The loop iterates through the array of Animal objects and calls the makeSound() method on each object. Since the second object is an instance of the Cat class, the makeSound() method from the Cat class is called and "Meow" is printed to the console. Similarly, for the third object, the makeSound() method from the Dog class is called and "Woof" is printed to the console. After the loop, an object of the Cat class is created and assigned to a variable of the Animal class. Then, the instanceof operator is used to check if the object is an instance of the Animal and Cat classes, respectively. Since the Cat class extends the Animal class, an instance of the Cat class is also an instance of the Animal class, hence the first output is true. The second output is also true since the object is indeed an instance of the Cat class.



  26. Answer: C

    Explanations

    The sum method is a recursive method that calculates the sum of all positive integers from n down to 1. When sum(5) is called in the main method, the else block is executed since n is not equal to 1. This block calls sum(n-1), which will call sum(4) next, and so on until sum(1) is called, which returns 1. Then each previous method call will return the sum of n and the result of the next method call until sum(5) is returned with the value of 15. Therefore, the output will be 15.



  27. Answer B

    Explanations

    The binarySearch method is used to search for the key value of 22 in the array of integers. The binary search algorithm works by dividing the array into two halves and checking if the middle element is equal to the key. If the middle element is smaller than the key, it means that the key is in the right half of the array. If the middle element is greater than the key, it means that the key is in the left half of the array. This process is repeated until the key is found or the left and right indices meet.
    In this example, the key value of 22 is present in the array at index 4, so the binarySearch method returns 4, and the program prints "Key found at index 4".