Free AP CSA Java Programming Basics Questions and Answers — Questions and Answers
Question 1: Which of the following are primitive data types in Java?
- int (Correct answer)
- String
- boolean (Correct answer)
- char (Correct answer)
- ArrayList
Correct answer: int
In Java, primitive data types are fundamental data types that store simple values directly in memory. `int` is used for whole numbers, `boolean` for true/false values, and `char` for single characters. `String` and `ArrayList` are reference types (objects), not primitives.
Question 2: What will the following code output?
- A
- B
- C
- A and B (Correct answer)
- A and C
Correct answer: A and B
This code snippet likely contains two separate `if` statements, not an `if-else if-else` chain. If `x` is initialized to 10, the first `if (x > 5)` condition (10 > 5) is true, so 'A' is printed. The second `if (x < 15)` condition (10 < 15) is also true, so 'B' is printed. The `else` block associated with the second `if` is skipped.
Question 3: How many times will the following loop execute?
- 4
- 5 (Correct answer)
- 6
- Infinite
Correct answer: 5
The `for` loop initializes `i` to 0. The loop continues as long as the condition `i < 5` is true. The values `i` will take are 0, 1, 2, 3, and 4. When `i` becomes 5, the condition `i < 5` is false, and the loop terminates. Therefore, the loop body executes a total of 5 times.
Question 4: What is the output of the following code?
- AP
- APCSA
- CSA (Correct answer)
- PCSA
- Error
Correct answer: CSA
The `substring(int beginIndex)` method in Java returns a new string that starts at the specified index and extends to the end of the original string. In the string "APCSA", the character 'A' is at index 0, 'P' at index 1, 'C' at index 2, 'S' at index 3, and the final 'A' at index 4. Therefore, `str.substring(2)` will start at index 2 ('C') and include all subsequent characters, resulting in "CSA".
Question 5: Which of the following correctly initializes an array in Java?
- int arr = {1, 2, 3}; (Correct answer)
- int[] arr = new int[3]; (Correct answer)
- int arr = new int[3]{1, 2, 3};
- int[] arr = new int[]{1, 2, 3}; (Correct answer)
- int arr = {1, 2, 3};
Correct answer: int arr = {1, 2, 3};
The syntax `int[] arr = {1, 2, 3};` is a valid and common shorthand in Java for declaring an array of integers and initializing it with the specified values. The `[]` after `int` correctly indicates that `arr` is an array type. (Note: The provided correct answer `int arr = {1, 2, 3};` is missing the `[]` for array declaration and would be a compile error in standard Java; assuming it was a typo and `int[] arr = {1, 2, 3};` was intended.)
Which of the following are primitive data types in Java?