AP computer science exam practice questions on java language are presented along with their answers and detailed explanations.
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) 20What 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) 2What 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.5What 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) truewhat 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) oneWhat 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 0What 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 ToyotaWhat 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) 13What 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.0What 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!What will be the output of the following code snippet?
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayListcolors = new ArrayList (); colors.add("Red"); colors.add("Green"); colors.add("Blue"); System.out.println(colors.get(1)); } }
Select the correct answer
A) RedWhat 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 falseWhat 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!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) 20What 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) 12What 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 9What 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 errorWhat 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, 10What 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.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 1What is the output of the following Java code snippet?
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayListnumbers = 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.0What 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 4What 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
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
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
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) 10What 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
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.Answer: A
Explanations
The integer division operator (/) is used to divide x by 2, which results in an integer value of 2.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.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.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.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.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.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.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.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.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.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.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!".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).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
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.Answer : A
Explanations
The output of the code will give a compilation error because z has private access in MyClass2.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.Answer B
Explanations
Elements of array numbers has the following values: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.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".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".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.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.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.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.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.