Professional Documents
Culture Documents
Java Revision
Revesion 1
3. What is 1 + 1 + 1 + 1 + 1 == 5?
A. true
B. false
C. There is no guarantee that 1 + 1 + 1 + 1 + 1 == 5 is true.
6. Which of the following code displays the area of a circle if the radius is positive?
A. if (radius != 0) System.out.println(radius * radius * 3.14159);
B. if (radius >= 0) System.out.println(radius * radius * 3.14159);
C. if (radius > 0) System.out.println(radius * radius * 3.14159);
D. if (radius <= 0) System.out.println(radius * radius * 3.14159);
1
7. What is the output of the following code?
int x = 0;
if (x < 4) {
x = x + 1;
}
System.out.println("x is " + x);
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
8. Suppose income is 4001, what is the output of the following code?
if (income > 3000) {
System.out.println("Income is greater than 3000");
}
else if (income > 4000) {
System.out.println("Income is greater than 4000");
}
A. no output
B. Income is greater than 3000
C. Income is greater than 3000 followed by Income is greater than 4000
D. Income is greater than 4000
E. Income is greater than 4000 followed by Income is greater than 3000
9. The following code displays ___________.
double temperature = 50;
if (temperature >= 100)
System.out.println("too hot");
else if (temperature <= 40)
System.out.println("too cold");
else
System.out.println("just right");
A. too hot
B. too cold
C. just right
D. too hot too cold just right
10. Suppose x = 1, y = -1, and z = 1. What is the output of the following statement? (Please
indent the statement correctly first.)
if (x > 0)
if (y > 0)
System.out.println("x > 0 and y > 0");
else if (z > 0)
System.out.println("x < 0 and z > 0");
A. x > 0 and y > 0;
B. x < 0 and z > 0;
C. x < 0 and z < 0;
D. no output.
2
11. Analyze the following code:
boolean even = false;
if (even = true) {
System.out.println("It is even");
}
A. The program has a compile error.
B. The program has a runtime error.
C. The program runs fine, but displays nothing.
D. The program runs fine and displays It is even.
12. Suppose isPrime is a boolean variable, which of the following is the correct and best
statement for testing if isPrime is true?
A. if (isPrime = true)
B. if (isPrime == true)
C. if (isPrime)
D. if (!isPrime = false)
E. if (!isPrime == false)
13. Analyze the following code.
boolean even = false;
if (even) {
System.out.println("It is even!");
}
A. The code displays It is even!
B. The code displays nothing.
C. The code is wrong. You should replace if (even) with if (even == true).
D. The code is wrong. You should replace if (even) with if (even = true).
14. Analyze the following code:
Code 1:
int number = 45;
boolean even;
if (number % 2 == 0)
even = true;
else
even = false;
Code 2:
int number = 45;
boolean even = (number % 2 == 0);
A. Code 1 has compile errors.
B. Code 2 has compile errors.
C. Both Code 1 and Code 2 have compile errors.
D. Both Code 1 and Code 2 are correct, but Code 2 is better.
15. Which of the following is a possible output from invoking Math.random()? Please select
all that apply.
A. 3.43
B. 0.5
C. 0.0
D. 1.0
3
16. What is the output from System.out.println((int)Math.random() * 4)?
A. 0
B. 1
C. 2
D. 3
E. 4
17. What is the possible output from System.out.println((int)(Math.random() * 4))? Please
select all that apply.
A. 0
B. 1
C. 2
D. 3
E. 4
18. Suppose you write the code to display "Cannot get a driver's license" if age is less than
16 and "Can get a driver's license" if age is greater than or equal to 16. Which of the
following code is correct? Please select all that apply.
I:
if (age < 16)
System.out.println("Cannot get a driver's license");
if (age >= 16)
System.out.println("Can get a driver's license");
II:
if (age < 16)
System.out.println("Cannot get a driver's license");
else
System.out.println("Can get a driver's license");
III:
if (age < 16)
System.out.println("Cannot get a driver's license");
else if (age >= 16)
System.out.println("Can get a driver's license");
IV:
if (age < 16)
System.out.println("Cannot get a driver's license");
else if (age > 16)
System.out.println("Can get a driver's license");
else if (age == 16)
System.out.println("Can get a driver's license");
A. I and II
B. II and III
C. I, II, and III
D. III and IV
E. I, II, III, and IV
4
19. Suppose you write the code to display "Cannot get a driver's license" if age is less than
16 and "Can get a driver's license" if age is greater than or equal to 16. Which of the
following code is the best?
I:
if (age < 16)
System.out.println("Cannot get a driver's license");
if (age >= 16)
System.out.println("Can get a driver's license");
II:
if (age < 16)
System.out.println("Cannot get a driver's license");
else
System.out.println("Can get a driver's license");
III:
if (age < 16)
System.out.println("Cannot get a driver's license");
else if (age >= 16)
System.out.println("Can get a driver's license");
IV:
if (age < 16)
System.out.println("Cannot get a driver's license");
else if (age > 16)
System.out.println("Can get a driver's license");
else if (age == 16)
System.out.println("Can get a driver's license");
A. I
B. II
C. III
D. IV
20. The __________ method immediately terminates the program.
A. System.terminate(0);
B. System.halt(0);
C. System.exit(0);
D. System.quit(0);
E. System.stop(0);
21. Which of the Boolean expressions below is incorrect? Please select all that apply.
A. (true) && (3 => 4)
B. !(x > 0) && (x > 0)
C. (x > 0) || (x < 0)
D. (x != 0) || (x = 0)
E. (-10 < x < 0)
5
22. Which of the following is the correct expression that evaluates to true if the number x is
between 1 and 100 or the number is negative?
A. 1 < x < 100 && x < 0
B. ((x < 100) && (x > 1)) || (x < 0)
C. ((x < 100) && (x > 1)) && (x < 0)
D. (1 > x > 100) || (x < 0)
30.Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x++ > 10).
A. 9
B. 10
C. 11
6
31. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) || (x-- > 10).
A. 9
B. 10
C. 11
32. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) || (x++ > 10).
A. 9
B. 10
C. 11
33. Analyze the following code:
if (x < 100) && (x > 10)
System.out.println("x is between 10 and 100");
A. The statement has compile errors because (x<100) & (x > 10) must be enclosed inside
parentheses.
B. The statement has compile errors because (x<100) & (x > 10) must be enclosed inside
parentheses and the println(?) statement must be put inside a block.
C. The statement compiles fine.
D. The statement compiles fine, but has a runtime error.
34. Which of the following are so called short-circuit operators? Please select all that apply.
A. &&
B. &
C. ||
D. |
35. What is y after the following switch statement is executed?
int x = 3; int y = 4;
switch (x + 3) {
case 6: y = 0;
case 7: y = 1;
default: y += 1;
}
A. 1
B. 2
C. 3
D. 4
E. 0
36. Analyze the following program fragment:
int x;
double d = 1.5;
switch (d) {
case 1.0: x = 1;
case 1.5: x = 2;
case 2.0: x = 3; }
A. The program has a compile error because the required break statement is missing in the
switch statement.
B. The program has a compile error because the required default case is missing in the switch
statement.
C. The switch control variable cannot be double.
D. No errors.
7
37. What is y after the following statement is executed?
x = 0;
y = (x > 0) ? 10 : -10;
A. -10
B. 0
C. 10
D. 20
E. Illegal expression
38. Analyze the following code fragments that assign a boolean value to the variable even.
Code 1:
if (number % 2 == 0)
even = true;
else
even = false;
Code 2:
even = (number % 2 == 0) ? true: false;
Code 3:
even = number % 2 == 0;
A. Code 2 has a compile error, because you cannot have true and false literals in the conditional
expression.
B. Code 3 has a compile error, because you attempt to assign number to even.
C. All three are correct, but Code 1 is preferred.
D. All three are correct, but Code 2 is preferred.
E. All three are correct, but Code 3 is preferred.
40. The order of the precedence (from high to low) of the operators binary +, *, &&, ||, ^ is:
A. &&, ||, ^, *, +
B. *, +, &&, ||, ^
C. *, +, ^, &&, ||
D. *, +, ^, ||, &&
E. ^, ||, &&, *, +
8
41. What is y displayed in the following code?
public class Test1 {
public static void main(String[] args) {
int x = 1;
int y = x = x + 1;
System.out.println("y is " + y);
}
}
A. y is 0.
B. y is 1 because x is assigned to y first.
C. y is 2 because x + 1 is assigned to x and then x is assigned to y.
D. The program has a compile error since x is redeclared in the statement int y = x = x + 1.
45. How many times will the following code print "Welcome to Java"?
int count = 0;
while (count < 10) {
System.out.println("Welcome to Java");
count++;
}
A. 8
B. 9
C. 10
D. 11
E. 0
9
46. Analyze the following code. Please select all that apply.
int count = 0;
while (count < 100) {
// Point A
System.out.println("Welcome to Java!");
count++;
// Point B
}
// Point C
A. count < 100 is always true at Point A
B. count < 100 is always true at Point B
C. count < 100 is always false at Point B
D. count < 100 is always true at Point C
E. count < 100 is always false at Point C
47. How many times will the following code print "Welcome to Java"?
int count = 0;
while (count++ < 10) {
System.out.println("Welcome to Java");
}
A. 8
B. 9
C. 10
D. 11
E. 0
48. What is the output of the following code?
int x = 0;
while (x < 4) {
x = x + 1;
}
System.out.println("x is " + x);
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
49. What will be displayed when the following code is executed?
int number = 6;
while (number > 0) {
number -= 3;
System.out.print(number + " ");
}
A. 6 3 0
B. 6 3
C. 3 0
D. 3 0 -3
E. 0 -3
10
50. How many times will the following code print "Welcome to Java"?
int count = 0;
do {
System.out.println("Welcome to Java");
count++;
} while (count < 10);
A. 8
B. 9
C. 10
D. 11
E. 0
51. How many times will the following code print "Welcome to Java"?
int count = 0;
do {
System.out.println("Welcome to Java");
} while (count++ < 10);
A. 8
B. 9
C. 10
D. 11
E. 0
52. How many times will the following code print "Welcome to Java"?
int count = 0;
do {
System.out.println("Welcome to Java");
} while (++count < 10);
A. 8
B. 9
C. 10
D. 11
E. 0
53. What is the value in count after the following loop is executed?
int count = 0;
do {
System.out.println("Welcome to Java");
} while (count++ < 9);
System.out.println(count);
A. 8
B. 9
C. 10
D. 11
E. 0
11
54. Analyze the following statement:
double sum = 0;
for (double d = 0; d < 10;) {
d += 0.1;
sum += sum + d;
}
A. The program has a compile error because the adjustment is missing in the for loop.
B. The program has a compile error because the control variable in the for loop cannot be of the
double type.
C. The program runs in an infinite loop because d < 10 would always be true.
D. The program compiles and runs fine.
A:
for (int count = 1; count <= 10; count++) {
System.out.println("Welcome to Java");
}
B:
for (int count = 0; count < 10; count++) {
System.out.println("Welcome to Java");
}
C:
for (int count = 1; count < 10; count++) {
System.out.println("Welcome to Java");
}
D:
for (int count = 0; count <= 10; count++) {
System.out.println("Welcome to Java");
}
A. BD
B. ABC
C. AC
D. BC
E. AB
12
56. Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?
A: double sum = 0;
for (int i = 1; i <= 99; i++) {
sum = i / (i + 1);
}
System.out.println("Sum is " + sum);
B: double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1);
}
System.out.println("Sum is " + sum);
C: double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += 1.0 * i / (i + 1);
}
System.out.println("Sum is " + sum);
D: double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
E: double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1.0);
}
System.out.println("Sum is " + sum);
A. BCD
B. ABCD
C. B
D. CDE
E. CD
13
58. Do the following two statements in (I) and (II) result in the same value in sum?
(I): for (int i = 0; i < 10; ++i) {
sum += i;
}
14
63. Analyze the following code. Please select all that apply.
public class Test {
public static void main (String[] args) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}
A. The program has a compile error because of the semicolon (;) on the for loop line.
B. The program compiles despite the semicolon (;) on the for loop line, and displays 4.
C. The program compiles despite the semicolon (;) on the for loop line, and displays 14.
D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);
64. How many times is the println statement executed?
for (int i = 0; i < 10; i++)
for (int j = 0; j < i; j++)
System.out.println(i * j)
A. 100
B. 20
C. 10
D. 45
65. Which pattern is produced by the following code?
for (int i = 1; i <= 6; i++) {
for (int j = 6; j >= 1; j--)
System.out.print(j <= i ? j + " " : " " + " ");
System.out.println();
}
A. Pattern A
B. Pattern B
C. Pattern C
D. Pattern D
66. How many times is the println statement executed?
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
System.out.println(i * j);
A. 100
B. 20
C. 10
D. 45
15
68. Analyze the following code.
double sum = 0;
for (double d = 0; d < 10; sum += sum + d) {
d += 0.1;
}
A. The program has a syntax error because the adjustment statement is incorrect in the for loop.
B. The program has a syntax error because the control variable in the for loop cannot be of the
double type.
C. The program compiles but does not stop because d would always be less than 10.
D. The program compiles and runs fine.
69. What is y after the following for loop statement is executed?
int y = 0;
for (int i = 0; i < 10; ++i) {
y += 1;
}
A. 9
B. 10
C. 11
D. 12
70. Will the following program terminate?
int balance = 10;
while (true) {
if (balance < 9)
break;
balance = balance - 9;
}
A. Yes
B. No
71. What is sum after the following loop terminates?
int sum = 0;
int item = 0;
do {
item++;
sum += item;
if (sum > 4)
break;
}
while (item < 5);
A. 5
B. 6
C. 7
D. 8
E. 9
16
72. What is the output after the following loop terminates?
int number = 25;
int i;
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
System.out.println("i is " + i + " isPrime is " + isPrime);
A. i is 5 isPrime is true
B. i is 5 isPrime is false
C. i is 6 isPrime is true
D. i is 6 isPrime is false
17
75. Will the following program terminate?
int balance = 10;
while (true) {
if (balance < 9)
continue;
balance = balance - 9;
}
A. Yes
B. No
76. What balance after the following code is executed?
int balance = 10;
while (balance >= 1) {
if (balance < 9)
continue;
balance = balance - 9;
}
A. -1
B. 0
C. 1
D. 2
E. The loop does not end
77. What is the value of balance after the following code is executed?
int balance = 10;
while (balance >= 1) {
if (balance < 9)
break;
balance = balance - 9;
}
A. -1
B. 0
C. 1
D. 2
78. What is the number of iterations in the following loop?
for (int i = 1; i < n; i++) {
// iteration
}
A. 2*n
B. n
C. n - 1
D. n + 1
79. What is the number of iterations in the following loop?
for (int i = 1; i <= n; i++) {
// iteration }
A. 2*n
B. n
C. n - 1
D. n + 1
18
80.Suppose the input for number is 9. What is the output from running the following
program?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
int i;
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
System.out.println("i is " + i);
if (isPrime)
System.out.println(number + " is prime");
else
System.out.println(number + " is not prime");
}
}
A. i is 3 followed by 9 is prime
B. i is 3 followed by 9 is not prime
C. i is 4 followed by 9 is prime
D. i is 4 followed by 9 is not prime
19
Sheet2 : Methods
Java Revision
Revesion 2
Sheet 2
1. To obtain the sine of 35 degrees, use _______.
A. Math.sin(35)
B. Math.sin(Math.toRadians(35))
C. Math.sin(Math.toDegrees(35))
D. Math.sin(Math.toRadian(35))
E. Math.sin(Math.toDegree(35))
2. To obtain the arc sine of 0.5, use _______.
A. Math.asin(0.5)
B. Math.asin(Math.toDegrees(0.5))
C. Math.sin(Math.toRadians(0.5))
D. Math.sin(0.5)
3. Math.asin(0.5) returns _______.
A. 30
B. Math.toRadians(30)
C. Math.PI / 4
D. Math.PI / 2
4. Math.sin(Math.PI) returns _______.
A. 0.0
B. 1.0
C. 0.5
D. 0.4
5. Math.cos(Math.PI) returns _______.
A. 0.0
B. 1.0
C. -1.0
D. 0.5
6. Which of the following is correct to obtain the square root of 5? Please select all that
apply.
A. Math.sqrt(5)
B. Math.sqrt(25)
C. Math.pow(5, 0.5)
D. Math.pow(5, 2)
7. What is Math.rint(3.6)?
A. 3.0
B. 3
C. 4.0
D. 5.0
1
8. What is Math.round(3.6)?
A. 3.0
B. 3
C. 4
D. 4.0
9. What is Math.rint(3.5)?
A. 3.0
B. 3
C. 4
D. 4.0
E. 5.0
10. What is Math.ceil(3.6)?
A. 3.0
B. 3
C. 4.0
D. 5.0
11. What is Math.floor(3.6)?
A. 3.0
B. 3
C. 4
D. 5.0
12. Which of the following is correct to obtain the min of x, y, z? Please select all that apply.
A. Math.min(x, Math.min(y, z))
B. Math.min(Math.min(x, y), z)
C. Math.min(Math.min(y, z), x)
D. Math.min(z, Math.min(x, y))
13. Which of the following is correct to obtain a random integer between 5 and 10?
A. 5 + Math.random() * 6
B. 5 + (int)(Math.random() * 6)
C. 5 + Math.random() * 5
D. 5 + (int)(Math.random() * 5)
14. Which of the following is the correct expression of character 4?
A. 4
B. "4"
C. '\0004'
D. '4'
15. A Java character is stored in __________.
A. one byte
B. two bytes
C. three bytes
D. four bytes
16. The Unicode of 'a' is 97. What is the Unicode for 'c'?
A. 96
B. 97
C. 98
D. 99
2
17. Which of the following statements prints smith\exam1\test.txt?
A. System.out.println("smith\exam1\test.txt");
B. System.out.println("smith\\exam1\\test.txt");
C. System.out.println("smith\"exam1\"test.txt");
D. System.out.println("smith"\exam1"\test.txt");
18.Suppose x is a char variable with a value 'b'. What is the output of the statement
System.out.println(++x)?
A. a
B. b
C. c
D. d
19.Suppose i is an int type variable. Which of the following statements display the
character whose Unicode is stored in variable i?
A. System.out.println(i);
B. System.out.println((char)i);
C. System.out.println((int)i);
D. System.out.println(i + " ");
20. Will System.out.println((char)4) display 4?
A. Yes
B. No
21. What is the output of System.out.println('z' - 'a')?
A. 25
B. 26
C. a
D. z
22. An int variable can hold __________.
A. 'x'
B. 120
C. 120.0
D. "x"
E. "120"
23. Which of the following assignment statements is correct? Please select all that apply.
A. char c = 'd';
B. char c = 100;
C. char c = "d";
D. char c = "100";
24. '3' - '2' + 'm' / 'n' is ______.
A. 0
B. 1
C. 2
D. 3
25. To check whether a char variable ch is an uppercase letter, you write ___________.
A. (ch >= 'A' && ch >= 'Z')
B. (ch >= 'A' && ch <= 'Z')
C. (ch >= 'A' || ch <= 'Z')
D. ('A' <= ch <= 'Z')
3
28. The expression "Java " + 1 + 2 + 3 evaluates to ________.
A. Java123
B. Java6
C. Java 123
D. java 123
E. Illegal expression
29.Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to ______.
A. 66
B. B
C. A1
D. Illegal expression
30.Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to _______.
A. 66
B. B
C. A1
D. Illegal expression
31. Suppose s1 and s2 are two strings. What is the result of the following code?
s1.equals(s2) == s2.equals(s1)
A. true
B. false
41. The __________ method parses a string s to an int value.
A. integer.parseInt(s);
B. Integer.parseInt(s);
C. integer.parseInteger(s);
D. Integer.parseInteger(s);
42. The __________ method parses a string s to a double value.
A. double.parseDouble(s);
B. Double.parsedouble(s);
C. double.parse(s);
D. Double.parseDouble(s);
43. Which of the following is an invalid specifier for the printf statement?
a. %4c
b. %6d
c. %8.2d
44. The statement System.out.printf("%3.1f", 1234.56) outputs ___________.
A. 123.4
B. 123.5
C. 1234.5
D. 1234.56
E. 1234.6
46. The statement System.out.printf("%5d", 123456) outputs ___________.
A. 12345
B. 23456
C. 123456
D. 12345.6
4
47. The statement System.out.printf("%10d", 123456) outputs ________. (Note: * represents
a space)
A. 123456****
B. 23456*****
C. 12345*****
D. ****123456
48. Analyze the following code:
int i = 3434; double d = 3434;
System.out.printf("%5.1f %5.1f", i, d);
A. The code compiles and runs fine to display 3434.0 3434.0.
B. The code compiles and runs fine to display 3434 3434.0.
C. i is an integer, but the format specifier %5.1f specifies a format for double value. The code has
an error.
49. Suppose your method does not return any value, which of the following keywords can
be used as a return type?
A. void
B. int
C. double
D. public
E. None of the above
50. The signature of a method consists of ____________.
A. method name
B. method name and parameter list
C. return type, method name, and parameter list
D. parameter list
51. All Java applications must have a method __________.
A. public static Main(String[] args)
B. public static Main(String args[])
C. public static void main(String[] args)
D. public void main(String[] args)
52. Arguments to methods always appear within __________.
A. brackets
B. parentheses
C. curly braces
D. quotation marks
53. Does the method call in the following method cause compile errors?
5
54. Each time a method is invoked, the system stores parameters and local variables in an
area of memory, known as _______, which stores elements in last-in first-out fashion.
A. a heap
B. storage area
C. a stack
D. an array
55. Which of the following should be defined as a void method?
A. Write a method that prints integers from 1 to 100.
B. Write a method that returns a random integer from 1 to 100.
C. Write a method that checks whether a number is from 1 to 100.
D. Write a method that converts an uppercase letter to lowercase.
56. A variable defined inside a method is referred to as __________.
A. a global variable
B. a method variable
C. a block variable
D. a local variable
57. When you invoke a method with a parameter, the value of the argument is passed to the
parameter. This is referred to as _________.
A. method invocation
B. pass by value
C. pass by reference
D. pass by name
58. Does the return statement in the following method cause compile errors?
public static void main(String[] args) {
int max = 0;
if (max != 0)
System.out.println(max);
else
return;
}
A. Yes
B. No
##. Consider the following incomplete code. The missing method body should be ________.
public class Test {
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int number) {
// Missing body
}
}
A. return "number";
B. System.out.println(number);
C. System.out.println("number");
D. return number;
6
59. You should fill in the blank in the following code with ______________.
public class Test {
public static void main(String[] args) {
System.out.print("The grade is ");
printGrade(78.5);
A. int
B. double
C. boolean
D. char
E. void
7
60. You should fill in the blank in the following code with ______________.
public class Test {
public static void main(String[] args) {
System.out.print("The grade is " + getGrade(78.5));
System.out.print("\nThe grade is " + getGrade(59.5));
}
public static _________ getGrade(double score) {
if (score >= 90.0)
return 'A';
else if (score >= 80.0)
return 'B';
else if (score >= 70.0)
return 'C';
else if (score >= 60.0)
return 'D';
else
return 'F';
}
}
A. int
B. double
C. boolean
D. char
E. void
61. Given the following method, what is the output of the call nPrint('a', 4)?
static void nPrint(String message, int n) {
while (n > 0) {
System.out.print(message);
n--;
}
}
A. aaaaa
B. aaaa
C. aaa
D. invalid call
62. Given the following method
static void nPrint(String message, int n) {
while (n > 0) {
System.out.print(message);
n--;
}
}
What is k after invoking nPrint("A message", k)?
int k = 2;
nPrint("A message", k);
A. 0
B. 1
C. 2
8
63. Analyze the following code:
public class Test {
public static void main(String[] args) {
System.out.println(xMethod(5, 500L)); }
public static int xMethod(int n, long l) {
System.out.println("int, long");
return n; }
public static long xMethod(long n, long l) {
System.out.println("long, long");
return n; }
}
A. The program displays int, long followed by 5.
B. The program displays long, long followed by 5.
C. The program runs fine but displays things other than 5.
D. The program does not compile because the compiler cannot distinguish which xmethod to
invoke.
64.Analyze the following code:
class Test {
public static void main(String[] args) {
System.out.println(xmethod(5));
}
public static int xmethod(int n, long t) {
System.out.println("int");
return n;
}
public static long xmethod(long n) {
System.out.println("long");
return n;
}
}
A. The program displays int followed by 5.
B. The program displays long followed by 5.
C. The program runs fine but displays things other than 5.
9
65. Analyze the following code.
public class Test {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
System.out.println("max(int, double) is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
System.out.println("max(double, int) is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
}
A. The program cannot compile because you cannot have the print statement in a non-void
method.
B. The program cannot compile because the compiler cannot determine which max method
should be invoked.
C. The program runs and prints 2 followed by "max(int, double)" is invoked.
D. The program runs and prints 2 followed by "max(double, int)" is invoked.
E. The program runs and prints "max(int, double) is invoked" followed by 2.
10
68. What is k after the following block executes?
{
int k = 2;
nPrint("A message", k);
}
System.out.println(k);
A. 0
B. 1
C. 2
D. k is not defined outside the block. So, the program has a compile error
69. (int)(Math.random() * (65535 + 1)) returns a random number __________.
A. between 1 and 65536
B. between 1 and 65535
C. between 0 and 65535
D. between 0 and 65536
70. (int)('a' + Math.random() * ('z' - 'a' + 1)) returns a random number __________.
A. between 0 and (int)'z'
B. between (int)'a' and (int)'z'
C. between 'a' and 'z'
D. between 'a' and 'y'
71. (char)('a' + Math.random() * ('z' - 'a' + 1)) returns a random character __________.
A. between 'a' and 'z'
B. between 'a' and 'y'
C. between 'b' and 'z'
D. between 'b' and 'y'
11
Sheet3 : Arrays
Java Revision
Revesion 3
Sheet 3
1. Once an array is created, its size _______.
A. can be changed
B. is fixed
C. is not determined
2. Which of the following are correct to declare an array of int values?
A. int[] a;
B. int a[];
C. int a;
D. double[] a;
3. Which of the following are incorrect?
A. int[] a = new int[2];
B. int a[] = new int[2];
C. int[] a = new int(2);
D. int a = new int[2];
E. int a() = new int[2];
4. If you declare an array double[] list = new double[5], the highest index in array list is ___.
A. 0
B. 1
C. 2
D. 3
E. 4
5. How many elements are in array double[] list = new double[5]?
A. 4
B. 5
C. 6
D. 0
6. Analyze the following code.
public class Test {
public static void main(String[] args) {
int[] x = new int[3];
System.out.println("x[0] is " + x[0]);
}
}
A. The program has a compile error because the size of the array wasn't specified when declaring
the array.
B. The program has a runtime error because the array elements are not initialized.
C. The program runs fine and displays x[0] is 0.
D. The program has a runtime error because the array element x[0] is not defined.
1
7. What is the correct term for numbers[99]?
A. index
B. index variable
C. indexed variable
D. array variable
E. array
9. Suppose int i = 5, which of the following can be used as an index for array double[] t =
new double[100]?
A. i
B. (int)(Math.random() * 100))
C. i + 10
D. i + 6.5
E. Math.random() * 100
10. If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is ________.
A. 3.4
B. 2.0
C. 3.5
D. 5.5
E. undefined
12. How can you initialize an array of two characters to 'a' and 'b'?
A. char[] charArray = new char[2]; charArray = {'a', 'b'};
B. char[2] charArray = {'a', 'b'};
C. char[] charArray = {'a', 'b'};
D. char[] charArray = new char[2]; charArray[0] = 'a'; charArray[1] = 'b';
2
14. What is the output of the following code?
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
A. 0
B. 1
C. 2
D. 3
E. 4
3
17. Analyze the following code:
public class Test {
public static void main(String[] args) {
double[] x = {2.5, 3, 4};
for (double value: x)
System.out.print(value + " ");
}
}
A. The program displays 2.5, 3, 4
B. The program displays 2.5 3 4
C. The program displays 2.5 3.0 4.0
D. The program displays 2.5, 3.0 4.0
E. The program has a syntax error because value is undefined.
4
20. In the following code, what is the output for list2?
public class Test {
public static void main(String[] args) {
int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
list2 = list1;
list1[0] = 0; list1[1] = 1; list2[2] = 2;
5
23. Analyze the following code.
int[] list = new int[5];
list = new int[6];
A. The code has compile errors because the variable list cannot be changed once it is assigned.
B. The code has runtime errors because the variable list cannot be changed once it is assigned.
C. The code can compile and run fine. The second line assigns a new array to list.
D. The code has compile errors because you cannot assign a different size array to list.
24. Analyze the following code:
public class Test {
public static void main(String[] args) {
int[] a = new int[4];
a[1] = 1;
a = new int[2];
System.out.println("a[1] is " + a[1]);
}
}
A. The program has a compile error because new int[2] is assigned to a.
B. The program has a runtime error because a[1] is not initialized.
C. The program displays a[1] is 0.
D. The program displays a[1] is 1.
26. In the following code, what is the output for list1?
public class Test {
public static void main(String[] args) {
int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
list2 = list1;
list1[0] = 0; list1[1] = 1; list2[2] = 2;
6
27. Analyze the following code:
public class Test {
public static void main(String[] args) {
int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
7
29. Analyze the following code:
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
list = newList;
}
}
A. The program displays 1 2 3 4 5.
B. The program displays 1 2 3 4 5 and then raises an ArrayIndexOutOfBoundsException.
C. The program displays 5 4 3 2 1.
D. The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException.
30. Analyze the following code:
public class Test1 {
public static void main(String[] args) {
xMethod(new double[]{3, 3});
xMethod(new double[5]);
xMethod(new double[3]{1, 2, 3}); }
public static void xMethod(double[] a) {
System.out.println(a.length); }
}
A. The program has a compile error because xMethod(new double[]{3, 3}) is incorrect.
B. The program has a compile error because xMethod(new double[5]) is incorrect.
C. The program has a compile error because xMethod(new double[3]{1, 2, 3}) is incorrect.
D. The program has a runtime error because a is null.
31. What would be the result of attempting to compile and run the following code?
public class Test {
public static void main(String[] args) {
double[] x = new double[]{1, 2, 3};
System.out.println("Value is " + x[1]);
}
}
A. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it
should be replaced by {1, 2, 3}.
B. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it
should be replaced by new double[3]{1, 2, 3};
C. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it
should be replaced by new double[]{1.0, 2.0, 3.0};
D. The program compiles and runs fine and the output "Value is 1.0" is printed.
E. The program compiles and runs fine and the output "Value is 2.0" is printed.
8
32. Do the following two programs produce the same result?
Program I:
public class Test {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5};
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " "); }
}
Program II:
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
list = newList;
}
}
A. Yes
B. No
33. When you pass an array to a method, the method receives __________.
A. a copy of the array
B. a copy of the first element
C. the reference of the array
D. the length of the array
34. The JVM stores the array in an area of memory, called _____, which is used for dynamic
memory allocation where blocks of memory are allocated and freed in an arbitrary order.
A. stack
B. heap
C. memory block
D. dynamic memory
35. Which of the following is correct?
A. String[] list = new String{"red", "yellow", "green"};
B. String[] list = new String[]{"red", "yellow", "green"};
C. String[] list = {"red", "yellow", "green"};
D. String list = {"red", "yellow", "green"};
E. String list = new String{"red", "yellow", "green"};
36. When you return an array from a method, the method returns __________.
A. a copy of the array
B. a copy of the first element
C. the reference of the array
D. the length of the array
9
37. Suppose a method p has the following header:
public static int[] p()
What return statement may be used in p()?
A. return 1;
B. return {1, 2, 3};
C. return int[]{1, 2, 3};
D. return new int[]{1, 2, 3};
38 Which correctly creates an array of five empty Strings?
A. String[] a = new String [5];
B. String[] a = {"", "", "", "", ""};
C. String[5] a;
D. String[ ] a = new String [5]; for (int i = 0; i < 5; a[i++] = null);
39. Analyze the following code:
public class Test {
public static void main(String argv[]) {
System.out.println("argv.length is " + argv.length);
}
}
A. The program has a compile error because String argv[] is wrong and it should be replaced by
String[] args.
B. The program has a compile error because String argv[] is wrong and it should be replaced by
String args[].
C. If you run this program without passing any arguments, the program would have a runtime
error because argv is null.
D. If you run this program without passing any arguments, the program would display argv.length
is 0.
40. Which of the following is the correct header of the main method?
A. public static void main(String[] args)
B. public static void main(String args[])
C. public static void main(String[] x)
D. public static void main(String x[])
E. static void main(String[] args)
10
58. When you create an array using the following statement, the element values are
automatically initialized to 0.
int[][] matrix = new int[5][5];
A. True
B. False
59. Assume double[][] x = new double[4][5], what are x.length and x[2].length?
A. 4 and 4
B. 4 and 5
C. 5 and 4
D. 5 and 5
60. How many elements are in array matrix (int[][] matrix = new int[5][5])?
A. 14
B. 20
C. 25
D. 30
61. Assume int[][] x = {{1, 2}, {3, 4}, {5, 6}}, what are x.length and x[0].length?
A. 2 and 1
B. 2 and 2
C. 3 and 2
D. 2 and 3
E. 3 and 3
62. Analyze the following code:
public class Test {
public static void main(String[] args) {
boolean[][] x = new boolean[3][];
x[0] = new boolean[1];
x[1] = new boolean[2];
x[2] = new boolean[3];
63. Assume int[][] x = {{1, 2}, {3, 4, 5}, {5, 6, 5, 9}}, what are x[0].length, x[1].length, and
x[2].length?
A. 2, 3, and 3
B. 2, 3, and 4
C. 3, 3, and 3
D. 3, 3, and 4
E. 2, 2, and 2
11
64. What is the output of the following code?
public class Test {
public static void main(String[] args) {
int[][] matrix =
{{1, 2, 3, 4},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15}};
int v = values[0][0];
for (int row = 0; row < values.length; row++)
for (int column = 0; column < values[row].length; column++)
if (v < values[row][column])
v = values[row][column];
System.out.print(v);
}
}
A. 1
B. 3
C. 5
D. 6
E. 33
12
68. What is the output of the following code?
public class Test5 {
public static void main(String[] args) {
int[][] matrix =
{{1, 2, 3, 4},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15}};
70. Suppose a method p has the following header. What return statement may be used in
p()?
public static int[][] p()
A. return 1;
B. return {1, 2, 3};
C. return int[]{1, 2, 3};
D. return new int[]{1, 2, 3};
E. return new int[][]{{1, 2, 3}, {2, 4, 5}};
13
71. What is the output of the following program?
public class Test {
public static void main(String[] args) {
int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};
14
Sheet4 : OOP
Java Revision
Revesion 4
Sheet 4
1.__________ represents an entity in the real world that can be distinctly identified.
A. A class
B. An object
C. A method
D. A data field
2. _________ is a template that defines objects of the same type.
A. A class
B. An object
C. A method
D. A data field
3. An object is an instance of a __________.
A. program
B. class
C. method
D. data
4. The keyword __________ is required to define a class.
A. static
B. void
C. class
D. int
5 What is the output of the following code?
public class A {
boolean x;
1
8. Analyze the following code.
class TempClass {
int i;
public void TempClass(int j) {
int i = j;
}
}
public class C {
public static void main(String[] args) {
TempClass temp = new TempClass(2);
}
}
A. The program has a compile error because TempClass does not have a default constructor.
B. The program has a compile error because TempClass does not have a constructor with an int
argument.
C. The program compiles fine, but it does not run because class C is not public.
D. The program compiles and runs fine.
9. Which of the following statements are true?
A. A default constructor is provided automatically if no constructors are explicitly defined in the
class.
B. At least one constructor must always be defined explicitly.
C. Every class has a default constructor.
D. The default constructor is a no-arg constructor.
10. Analyze the following code:
public class Test {
public static void main(String[] args) {
A a = new A();
a.print();
}
}
class A {
String s;
A(String s) {
this.s = s;
}
void print() {
System.out.println(s);
}
}
A. The program has a compile error because class A is not a public class.
B. The program has a compile error because class A does not have a default constructor.
C. The program compiles and runs fine and prints nothing.
D. The program would compile and run if you change A a = new A() to A a = new A("5").
2
11. Given the declaration Circle x = new Circle(), which of the following statements is most
accurate.
A. x contains an int value.
B. x contains an object of the Circle type.
C. x contains a reference to a Circle object.
D. You can assign an int value to x.
12. Which of the following statements are correct?
A. A reference variable is an object.
B. A reference variable references to an object.
C. A data field in a class must be of a primitive type.
D. A data field in a class can be of an object type.
13. Analyze the following code.
public class Test {
int x;
public Test(String t) {
System.out.println("Test");
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.x);
}
}
A. The program has a compile error because System.out.println method cannot be invoked from
the constructor.
B. The program has a compile error because x has not been initialized.
C. The program has a compile error because you cannot create an object from the class that
defines the object.
D. The program has a compile error because Test does not have a default constructor.
14. Analyze the following code.
public class Test {
int x;
public Test(String t) {
System.out.println("Test");
}
public static void main(String[] args) {
Test test = null;
System.out.println(test.x);
}
}
A. The program has a compile error because test is not initialized.
B. The program has a compile error because x has not been initialized.
C. The program has a compile error because you cannot create an object from the class that
defines the object.
D. The program has a compile error because Test does not have a default constructor.
E. The program has a runtime NullPointerException because test is null while executing test.x.
3
15.The default value for data field of a boolean type, numeric type, object type is
___________, respectively.
A. true, 1, Null
B. false, 0, null
C. true, 0, null
D. true, 1, null
E. false, 1, null
16. Which of the following statements are true?
A. Local variables do not have default values.
B. Data fields have default values.
C. A variable of a primitive type holds a value of the primitive type.
D. A variable of a reference type holds a reference to where an object is stored in the memory.
E. You may assign an int value to a reference variable.
17. Analyze the following code:
public class Test {
public static void main(String[] args) {
double radius;
final double PI = 3.15169;
double area = radius * radius * PI;
System.out.println("Area is " + area);
}
}
A. The program has compile errors because the variable radius is not initialized.
B. The program has a compile error because a constant PI is defined inside a method.
C. The program has no compile errors but will get a runtime error because radius is not initialized.
D. The program compiles and runs fine.
21. A method that is associated with an individual object is called __________.
A. a static method
B. a class method
C. an instance method
D. an object method
22. What is the output of the second println statement in the main method?
public class Foo {
int i;
static int s;
public Foo() {
i++;
4
s++;
}
}
A. f2.i is 1 f2.s is 1
B. f2.i is 1 f2.s is 2
C. f2.i is 2 f2.s is 2
D. f2.i is 2 f2.s is 1
24. You csn add the static keyword in the place of ? in Line _______ in the following code:
5
27. What is the output of the third println statement in the main method?
public class Foo {
int i;
static int s;
public static void main(String[] args) {
Foo f1 = new Foo();
System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s);
Foo f2 = new Foo();
System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s);
Foo f3 = new Foo();
System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s);
}
public Foo() {
i++;
s++;
}
}
A. f3.i is 1 f3.s is 1
B. f3.i is 1 f3.s is 2
C. f3.i is 1 f3.s is 3
D. f3.i is 3 f3.s is 1
E. f3.i is 3 f3.s is 3
28. Suppose the xMethod() is invoked in the following constructor in a class, xMethod() is
_________ in the class.
public MyClass() {
xMethod();
}
A. a static method
B. an instance method
C. a static method or an instance method
29. Suppose the xMethod() is invoked from a main method in a class as follows, xMethod()
is _________ in the class.
public static void main(String[] args) {
xMethod();
}
A. a static method
B. an instance method
C. a static method or an instance method
30. Variables that are shared by every instance of a class are __________.
A. public variables
B. private variables
C. instance variables
D. class variables
6
31. Analyze the following code:
public class Test {
public static void main(String args[]) {
NClass nc = new NClass();
nc.t = nc.t++;
}
}
class NClass {
int t;
private NClass() {
}
}
A. The program has a compile error because the NClass class has a private constructor.
B. The program does not compile because the parameter list of the main method is wrong.
C. The program compiles, but has a runtime error because t has no initial value.
D. The program compiles and runs fine.
32. Analyze the following code:
public class Test {
private int t;
7
34. To prevent a class from being instantiated, _____________________
A. don't use any modifiers on the constructor.
B. use the public modifier on the constructor.
C. use the private modifier on the constructor.
D. use the static modifier on the constructor.
36. Which of the following statements are true?
A. Use the private modifier to encapsulate data fields.
B. Encapsulating data fields makes the program easy to maintain.
C. Encapsulating data fields makes the program short.
D. Encapsulating data fields helps prevent programming errors.
38. Encapsulation means ______________.
A. that data fields should be declared private
B. that a class can extend another class
C. that a variable of supertype can refer to a subtype object
D. that a class can contain another class
39. What is the value of myCount.count displayed?
public class Test {
public static void main(String[] args) {
Count myCount = new Count();
int times = 0;
class Count {
int count;
Count(int c) {
count = c;
}
Count() {
count = 1;
}
}
A. 101
B. 100
C. 99
D. 98
8
40. What is the value of times displayed?
class Count {
int count;
Count(int c) {
count = c;
}
Count() {
count = 1;
}
}
A. 101
B. 100
C. 99
D. 98
E. 0
9
42. When invoking a method with an object argument, ___________ is passed.
A. the contents of the object
B. a copy of the object
C. the reference of the object
43. Given the declaration Circle[] x = new Circle[10], which of the following statements is most
accurate?
A. x contains an array of ten int values.
B. x contains an array of ten objects of the Circle type.
C. x contains a reference to an array and each element in the array can hold a reference to a Circle object.
46. What is the output for the first print statement in the main method?
public class Foo {
static int i = 0;
static int j = 0;
10
48. What is the output for the third print statement in the main method?
public class Foo {
static int i = 0;
static int j = 0;
public static void main(String[] args) {
int i = 2;
int k = 3;
{
int j = 3;
System.out.println("i + j is " + i + j);
}
k = i + j;
System.out.println("k is " + k);
System.out.println("j is " + j);
}
}
A. j is 0
B. j is 1
C. j is 2
D. j is 3
49. You can declare two variables with the same name in __________.
A. a method, one as a formal parameter and the other as a local variable
B. a block
C. two nested blocks in a method (two nested blocks means one being inside the other)
D. different methods in a class
50. Analyze the following code:
class Circle {
private double radius;
public Circle(double radius) {
radius = radius;
}
}
A. The program has a compile error because it does not have a main method.
B. The program will compile, but you cannot create an object of Circle with a specified radius. The
object will always have radius 0.
C. The program has a compile error because you cannot assign radius to radius.
D. The program does not compile because Circle does not have a default constructor.
51. Which of the following can be placed in the blank line in the following code?
public class Test {
private int id;
public void m1() {
_____.id = 45; }
}
A. this
B. Test
C. self
D. This
11
52. Analyze the following code:
class Test {
private double i;
public Test(double i) {
this.t();
this.i = i;
}
public Test() {
System.out.println("Default constructor");
this(1);
}
12
Sheet5 : Inheritance & Interface & Abstract_Class
Java Revision
Revesion 5
Sheet 5 part 1
1. Object-oriented programming allows you to derive new classes from existing classes.
This is called ____________.
A. encapsulation
B. inheritance
C. abstraction
D. generalization
2. Which of the following statements are true? Please select all that apply.
A. A subclass is a subset of a superclass.
B. A subclass is usually extended to contain more functions and more detailed information than its
superclass.
C. "class A extends B" means A is a subclass of B.
D. "class A extends B" means B is a subclass of A.
Square(double length) {
GeometricObject(length);
}
}
A. The program compiles fine, but you cannot create an instance of Square because the
constructor does not specify the length of the Square.
B. The program has a compile error because you attempted to invoke the GeometricObject
class's constructor illegally.
C. The program compiles fine, but it has a runtime error because of invoking the Square class's
constructor illegally.
1
5. Analyze the following code. Please select all that apply.
public class A extends B {
}
class B {
public B(String s) {
}
}
A. The program has a compile error because A does not have a default constructor.
B. The program has a compile error because the default constructor of A invokes the default
constructor of B, but B does not have a default constructor.
C. The program would compile fine if you add the following constructor into A: A(String s) { }
D. The program would compile fine if you add the following constructor into A: A(String s) {
super(s); }
A(String s) {
this.s = s;
}
public void print() {
System.out.println(s);
}
}
A. The program does not compile because Test does not have a default constructor Test().
B. The program has an implicit default constructor Test(), but it cannot be compiled, because its
super class does not have a default constructor. The program would compile if the constructor in
the class A were removed.
C. The program would compile if a default constructor A(){ } is added to class A explicitly.
D. The program compiles, but it has a runtime error due to the conflict on the method name print.
2
8. What is the output of running class C?
class A {
public A() {
System.out.println(
"The default constructor of A is invoked");
}
}
class B extends A {
public B() {
System.out.println(
"The default constructor of B is invoked");
}
}
public class C {
public static void main(String[] args) {
B b = new B();
}
}
A. Nothing displayed
B. "The default constructor of B is invoked"
C. "The default constructor of A is invoked" followed by "The default constructor of B is invoked"
D. "The default constructor of B is invoked" followed by "The default constructor of A is invoked"
E. "The default constructor of A is invoked"
10. Which of the following statements are true? Please select all that apply.
A. To override a method, the method must be defined in the subclass using the same signature
and compatible return type as in its superclass.
B. Overloading a method is to provide more than one method with the same name but with
different signatures to distinguish them.
C. It is a compile error if two methods differ only in return type in the same class.
E. A static method cannot be overridden. If a static method defined in the superclass is redefined
in a subclass, the method defined in the superclass is hidden.
3
11. Analyze the following code:
public class Test {
public static void main(String[] args) {
B b = new B();
b.m(5);
System.out.println("i is " + b.i);
}
}
class A {
int i;
public void m(int i) {
this.i = i;
}
}
class B extends A {
public void m(String s) {
}
}
A. The program has a compile error, because m is overridden with a different signature in B.
B. The program has a compile error, because b.m(5) cannot be invoked since the method m(int)
is hidden in B.
C. The program has a runtime error on b.i, because i is not accessible from b.
D. The method m is not overridden in B. B inherits the method m from A and defines an
overloaded method m in B.
12. Which of the following statements are true? Please select all that apply.
A. A method can be overloaded in the same class.
B. A method can be overridden in the same class.
C. If a method overloads another method, these two methods must have the same signature.
D. If a method overrides another method, these two methods must have the same signature.
E. A method in a subclass can overload a method in the superclass.
4
13. The getValue() method is overridden in two ways. Which one is correct?
I:
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getValue());
}
}
class B {
public String getValue() {
return "Any object";
}
}
class A extends B {
public Object getValue() {
return "A string";
}
}
II:
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getValue());
}
}
class B {
public Object getValue() {
return "Any object";
}
}
class A extends B {
public String getValue() {
return "A string";
}
}
A. I
B. II
C. Both I and II
D. Neither
5
14. Analyze the following code:
public class Test {
public static void main(String[] args) {
new B();
}
}
class A {
int i = 7;
public A() {
System.out.println("i from A is " + i);
}
public void setI(int i) {
this.i = 2 * i;
}
}
class B extends A {
public B() {
setI(20);
// System.out.println("i from B is " + i);
}
@Override
public void setI(int i) {
this.i = 3 * i;
}
}
A. The constructor of class A is not called.
B. The constructor of class A is called and it displays "i from A is 7".
C. The constructor of class A is called and it displays "i from A is 40".
D. The constructor of class A is called and it displays "i from A is 60".
public A() {
setI(20);
System.out.println("i from A is " + i);
}
public void setI(int i) {
this.i = 2 * i;
}
}
class B extends A {
public B() {
// System.out.println("i from B is " + i);
}
@Override
public void setI(int i) {
this.i = 3 * i;
}
}
A. The constructor of class A is not called.
B. The constructor of class A is called and it displays "i from A is 7".
C. The constructor of class A is called and it displays "i from A is 40".
D. The constructor of class A is called and it displays "i from A is 60".
18. Which of the following are Java keywords?
A. instanceOf
B. instanceof
C. cast
D. casting
19. Analyze the following code:
public class Test {
public static void main(String[] args) {
String s = new String("Welcome to Java");
Object o = s;
String d = (String)o;
}
}
A. When assigning s to o in Object o = s, a new object is created.
B. When casting o in String d = (String)o, a new object is created.
C. When casting o in String d = (String)o, the contents of o is changed.
D. s, o, and d reference the same String object.
7
20. Analyze the following code. Please select all that apply.
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new Object();
System.out.println(a1);
System.out.println(a2);
}
}
class A {
int x;
@Override
public String toString() {
return "A's x is " + x;
}
}
A. The program cannot be compiled, because System.out.println(a1) is wrong and it should be
replaced by System.out.println(a1.toString());
B. When executing System.out.println(a1), the toString() method in the Object class is invoked.
C. When executing System.out.println(a2), the toString() method in the Object class is invoked.
D. When executing System.out.println(a1), the toString() method in the A class is invoked.
21. What is the output of the following code?
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
@Override
public String getInfo() {
return "Student";
}
}
class Person {
public String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
}
A. Person Person
B. Person Student
C. Student Student
D. Student Person
8
22. Given the following code, find the compile error. Please select all that apply.
public class Test {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Student x) {
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
@Override
public String toString() {
return "Student";
}
}
class Person extends Object {
@Override
public String toString() {
return "Person";
}
}
A. m(new GraduateStudent()) causes an error
B. m(new Student()) causes an error
C. m(new Person()) causes an error
D. m(new Object()) causes an error
9
25. What is the output of the following code?
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
private String getInfo() {
return "Student";
}
}
class Person {
private String getInfo() {
return "Person";
}
public void printPerson() {
System.out.println(getInfo());
}
}
A. Person Person
B. Person Student
C. Student Student
D. Student Person
C2 c2 = new C2();
C3 c3 = new C3();
c2 = (C2)((C1)c3);
A. c3 is cast into c2 successfully.
B. You will get a runtime error because you cannot cast objects from sibling classes.
C. You will get a runtime error because the Java runtime system cannot perform multiple casting
in nested form.
D. The statement is correct.
27. You can assign _________ to a variable of Object[] type. Please select all that apply.
A. new char[100]
B. new int[100]
C. new double[100]
D. new String[100]
E. new java.util.Date[100]
10
28. Given the following code, which of the following expressions evaluates to false?
class C1 {}
class C2 extends C1 { }
class C3 extends C2 { }
class C4 extends C1 {}
C1 c1 = new C1();
C2 c2 = new C2();
C3 c3 = new C3();
C4 c4 = new C4();
A. c1 instanceof C1
B. c2 instanceof C1
C. c3 instanceof C1
D. c4 instanceof C2
29. Analyze the following code.
// Program 1:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
System.out.println(a1.equals(a2));
}
}
class A {
int x;
public boolean equals(Object a) {
return this.x == ((A)a).x;
}
}
// Program 2:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
System.out.println(a1.equals(a2));
}
}
class A {
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
A. Program 1 displays true and Program 2 displays true
B. Program 1 displays false and Program 2 displays true
C. Program 1 displays true and Program 2 displays false
D. Program 1 displays false and Program 2 displays false
11
30. Analyze the following code.
// Program 1:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
System.out.println(a1.equals(a2));
}
}
class A {
int x;
12
33. Analyze the following code.
// Program 1
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
System.out.println(((A)a1).equals((A)a2));
}
}
class A {
int x;
13
35. What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Java");
String s2 = new String("Java");
System.out.print((s1 == s2) + " " + (s1.equals(s2)));
}
}
A. false false
B. true true
C. false true
D. true false
36. Given two reference variables t1 and t2, if t1 == t2 is true, t1.equals(t2) must be ______.
A. true
B. false
37. Given two reference variables t1 and t2, if t1.equals(t2) is true, t1 == t2 ___________.
A. is always true
B. is always false
C. may be true or false
38. Analyze the following code. Please select all that apply.
ArrayList<String> list = new ArrayList<>();
list.add("Beijing");
list.add("Tokyo");
list.add("Shanghai");
list.set(3, "Hong Kong");
A. The last line in the code causes a runtime error because there is no element at index 3 in the
array list.
B. The last line in the code has a compile error because there is no element at index 3 in the
array list.
C. If you replace the last line by list.add(3, "Hong Kong"), the code will compile and run fine.
D. If you replace the last line by list.add(4, "Hong Kong"), the code will compile and run fine.
14
40. What is the output of the following code?
ArrayList<String> list = new ArrayList<>();
String s1 = new String("Java");
String s2 = new String("Java");
list.add(s1);
list.add(s2);
System.out.println((list.get(0) == list.get(1)) + " "
+ (list.get(0)).equals(list.get(1)));
A. true false
B. false true
C. true true
D. false false
41. You can create an ArrayList using _________.
A. new ArrayList[]
B. new ArrayList[100]
C. new ArrayList<>()
D. ArrayList()
42. Invoking _________ removes all elements in an ArrayList x.
A. x.remove()
B. x.clean()
C. x.delete()
D. x.empty()
E. x.clear()
43. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following
methods will cause the list to become [Beijing, Chicago, Singapore]?
A. x.add("Chicago")
B. x.add(0, "Chicago")
C. x.add(1, "Chicago")
D. x.add(2, "Chicago")
44. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following
method will cause the list to become [Beijing]? Please select all that apply.
A. x.remove("Singapore")
B. x.remove(0)
C. x.remove(1)
D. x.remove(2)
45. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following
method will cause runtime errors? Please select all that apply.
A. x.get(1)
B. x.set(2, "New York");
C. x.get(2)
D. x.remove(2)
E. x.size()
46. Invoking _________ returns the first element in an ArrayList x.
A. x.first()
B. x.get(0)
C. x.get(1)
D. x.get()
15
47. Invoking _________ returns the number of the elements in an ArrayList x.
A. x.getSize()
B. x.getLength(0)
C. x.length(1)
D. x.size()
48. Suppose an ArrayList list contains {"red", "green", "red", "green"}. What is the list after
the following code?
list.remove("red");
A. {"red", "green", "red", "green"}
B. {"green", "red", "green"}
C. {"green", "green"}
D. {"red", "green", "green"}
49. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the
following code?
String element = "red";
for (int i = 0; i < list.size(); i++)
if (list.get(i).equals(element))
list.remove(element);
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
50. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the
following code?
String element = "red";
for (int i = 0; i < list.size(); i++)
if (list.get(i).equals(element)) {
list.remove(element);
i--;
}
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
51. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the
following code?
String element = "red";
for (int i = list.size() - 1; i >= 0; i--)
if (list.get(i).equals(element))
list.remove(element);
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
16
52. The output from the following code is __________.
java.util.ArrayList<String> list = new java.util.ArrayList<>();
list.add("New York");
java.util.ArrayList<String> list1 = list;
list.add("Atlanta");
list1.add("Dallas");
System.out.println(list1);
A. [New York]
B. [New York, Atlanta]
C. [New York, Atlanta, Dallas]
D. [New York, Dallas]
17
58. A class design requires that a particular member variable must be accessible by any
subclasses of this class, but otherwise not by classes which are not members of the same
package. What should be done to achieve this?
A. The variable should be marked public.
B. The variable should be marked private.
C. The variable should be marked protected.
D. The variable should have no special access modifier.
E. The variable should be marked private and an accessor method provided.
18
62. What modifier should you use on a class so that a class in the same package can
access it but a class (including a subclass) in a different package cannot access it?
A. public
B. private
C. protected
D. Use the default modifier.
63. What modifier should you use on the members of a class so that they are not
accessible to another class in a different package, but are accessible to any subclasses in
any package?
A. public
B. private
C. protected
D. Use the default modifier.
19
Java Revision
Revesion 6
Sheet 5 part 2
1. Which of the following class definitions defines a legal abstract class?
A. class A { abstract void unfinished() { } }
B. class A { abstract void unfinished(); }
C. abstract class A { abstract void unfinished(); }
D. public class abstract A { abstract void unfinished(); }
2. Which of the following declares an abstract method in an abstract Java class?
A. public abstract method();
B. public abstract void method();
C. public void abstract method();
D. public void method() {}
E. public abstract void method() {}
3. Which of the following statements regarding abstract methods is false?
A. An abstract class can have instances created using the constructor of the abstract class.
B. An abstract class can be extended.
C. A subclass of a non-abstract superclass can be abstract.
D. A subclass can override a concrete method in a superclass to declare it abstract.
E. An abstract class can be used as a data type.
4. Which of the following statements regarding abstract methods is false?
A. Abstract classes have constructors.
B. A class that contains abstract methods must be abstract.
C. It is possible to define an abstract class that contains no abstract methods.
D. An abstract method cannot be contained in a nonabstract class.
E. A data field can be declared abstract.
5. Suppose A is an abstract class, B is a concrete subclass of A, and both A and B have a
no-arg constructor. Which of the following is correct?
A. A a = new A();
B. A a = new B();
C. B b = new A();
D. B b = new B();
1
6. What is the output of running class Test?
public class Test {
public static void main(String[] args) {
new Circle9();
}
}
public abstract class GeometricObject {
protected GeometricObject() {
System.out.print("A");
}
protected GeometricObject(String color, boolean filled) {
System.out.print("B");
}
}
public class Circle9 extends GeometricObject {
/** No-arg constructor */
public Circle9() {
this(1.0);
System.out.print("C");
}
/** Construct circle with a specified radius */
public Circle9(double radius) {
this(radius, "white", false);
System.out.print("D");
}
/** Construct a circle with specified radius, filled, and color */
public Circle9(double radius, String color, boolean filled) {
super(color, filled);
System.out.print("E");
}
}
A. ABCD
B. BACD
C. CBAE
D. AEDC
E. BEDC
7. Which of the following is a correct interface?
A. interface A { void print() { }; }
B. abstract interface A { print(); }
C. abstract interface A { abstract void print() { };}
D. interface A { void print();}
8. _______ is not a reference type.
A. A class type
B. An interface type
C. An array type
D. A primitive type
2
9. Suppose A is an interface, B is a concrete class with a no-arg constructor that
implements A. Which of the following is correct?
A. A a = new A();
B. A a = new B();
C. B b = new A();
D. B b = new B();
10. Show the output of running the class Test in the following code lines:
interface A {
}
class C {
}
class D extends C {
}
class B extends D implements A {
}
public class Test {
public static void main(String[] args) {
B b = new B();
if (b instanceof A)
System.out.println("b is an instance of A");
if (b instanceof C)
System.out.println("b is an instance of C");
}
}
A. Nothing.
B. b is an instance of A.
C. b is an instance of C.
D. b is an instance of A followed by b is an instance of C.
11. The relationship between an interface and the class that implements it is
_____________.
A. Composition
B. Aggregation
C. Inheritance
D. None
3
True or false?
a. An abstract class can be used just like a nonabstract class except that you cannot use the new
operator to create an instance from the abstract class.
b. An abstract class can be extended.
c. A subclass of a nonabstract superclass cannot be abstract.
d. A subclass cannot override a concrete method in a superclass to define it as abstract.
e. An abstract method must be nonstatic.
Ans:
a. True
b. True
c. False
d. False
e. True
interface A {
void m1();
}
class B implements A {
void m1() {
System.out.println("m1");
}
}
interface A {
void m1();
}
class B implements A {
public void m1() {
System.out.println("m1");
}
}
4
: سؤال في الشيت
(a)
class A {
abstract void unfinished() {
}
}
(b)
public class abstract A {
abstract void unfinished();
}
(c)
class abstract A {
abstract void unfinished();
}
(d)
abstract class A {
protected void unfinished();
}
(e)
abstract class A {
abstract void unfinished();
}
(f)
abstract class A {
abstract int unfinished();
}
Ans:
e and f
5
Sheet6 : JavaFX
Java Revision
Revesion 7
Sheet6
1 Why is JavaFX preferred?
A. JavaFX is much simpler to learn and use for new Java programmers.
B. JavaFX provides a multi-touch support for touch-enabled devices such as tablets
and smart phones.
C. JavaFX has a built-in 3D, animation support, and video and audio playback.
D. JavaFX incorporates modern GUI technologies to enable you to develop rich
Internet applications.
1
4 What is the output of the following JavaFX program?
import javafx.application.Application;
import javafx.stage.Stage;
2
7 Which of the following statements are correct?
A. new Scene(new Button("OK"));
B. new Scene(new Circle());
C. new Scene(new ImageView());
D. new Scene(new Pane());
3
12 To add a node into a pane, use ______.
A. pane.add(node);
B. pane.addAll(node);
C. pane.getChildren().add(node);
D. pane.getChildren().addAll(node);
13 To add two nodes node1 and node2 into a pane, use ______.
A. pane.add(node1, node2);
B. pane.addAll(node1, node2);
C. pane.getChildren().add(node1, node2);
D. pane.getChildren().addAll(node1, node2);
16 To remove two nodes node1 and node2 from a pane, use ______.
A. pane.remove(node1, node2);
B. pane.removeAll(node1, node2);
C. pane.getChildren().remove(node1, node2);
D. pane.getChildren().removeAll(node1, node2);
18 To add a node to the the first row and second column in a GridPane pane, use
________.
A. pane.getChildren().add(node, 1, 2);
B. pane.add(node, 1, 2);
C. pane.getChildren().add(node, 0, 1);
D. pane.add(node, 0, 1);
E. pane.add(node, 1, 0);
4
19 To add two nodes node1 and node2 to the the first row in a GridPane pane, use
________.
A. pane.add(node1, 0, 0); pane.add(node2, 1, 0);
B. pane.add(node1, node2, 0);
C. pane.addRow(0, node1, node2);
D. pane.addRow(1, node1, node2);
E. pane.add(node1, 0, 1); pane.add(node2, 1, 1);
20 To place a node in the left of a BorderPane p, use ___________.
A. p.setEast(node);
B. p.placeLeft(node);
C. p.setLeft(node);
D. p.left(node);
21 To place two nodes node1 and node2 in a HBox p, use ___________.
A. p.add(node1, node2);
B. p.addAll(node1, node2);
C. p.getChildren().add(node1, node2);
D. p.getChildren().addAll(node1, node2);
22 The _________ properties are defined in the javafx.scene.shape.Line class.
A. startX
B. startY
C. endX
D. endY
E. strikethrough
23The _________ properties are defined in the javafx.scene.shape.Rectangle class.
A. width
B. x
C. y
D. height
E. arcWidth
24 The _________ properties are defined in the javafx.scene.shape.Ellipse class.
A. centerX
B. centerY
C. radiusX
D. radiusY
25 The _________ properties are defined in the javafx.scene.shape.Arc class.
A. centerX
B. centerY
C. radiusX
D. radiusY
E. startAngle
5
26 A JavaFX action event handler is an instance of _______.
A. ActionEvent
B. Action
C. EventHandler
D. EventHandler<ActionEvent>
27 A JavaFX action event handler contains a method ________.
A. public void actionPerformed(ActionEvent e)
B. public void actionPerformed(Event e)
C. public void handle(ActionEvent e)
D. public void handle(Event e)
28 Which of the following are the classes in JavaFX for representing an event?
A. ActionEvent
B. MouseEvent
C. KeyEvent
29 To register a source for an action event with a handler, use __________.
A. source.addAction(handler)
B. source.setOnAction(handler)
C. source.addOnAction(handler)
D. source.setActionHandler(handler)
30 The properties _________ are defined in the FadeTransition class.
A. duration
B. node
C. fromValue
D. toValue
E. byValue
31 To create a KeyFrame with duration 1 second, use ______________.
A. new KeyFrame(1000, handler)
B. new KeyFrame(1, handler)
C. new KeyFrame(Duration.millis(1000), handler)
D. new KeyFrame(Duration.seconds(1), handler)
32 __________ is a subclass of Animation.
A. PathTransition
B. FadeTransition
C. Timeline
D. Duration
6
33 Analyze the following code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
/**
* The main method is only needed for the IDE with limited JavaFX
* support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
A. When clicking the button, the program displays OK1 OK2.
B. When clicking the button, the program displays OK1.
C. When clicking the button, the program displays OK2.
D. The program has a compile error, because the setOnAction method is invoked twice.
34 Which of the following code correctly registers a handler with a button btOK?
A. btOK.setOnAction(e -> System.out.println("Handle the event"));
B. btOK.setOnAction((e) -> {System.out.println("Handle the event");});
C. btOK.setOnAction((ActionEvent e) -> System.out.println("Handle the event"));
D. btOK.setOnAction(e -> {System.out.println("Handle the event");});
7
35 To handle the mouse click event on a pane p, register the handler with p using ______.
A. p.setOnMouseClicked(handler);
B. p.setOnMouseDragged(handler);
C. p.setOnMouseReleased(handler);
D. p.setOnMousePressed(handler);
36 Fill in the code in the underlined location to display the mouse point location when
the mouse is pressed in the pane.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
/**
* The main method is only needed for the IDE with limited JavaFX
* support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
A. pane.setOnMouseClicked((e) -> System.out.println(e.getX() + ", " + e.getY()));
B. pane.setOnMouseReleased(e -> {System.out.println(e.getX() + ", " + e.getY())});
C. pane.setOnMousePressed(e -> System.out.println(e.getX() + ", " + e.getY()));
D. pane.setOnMouseDragged((e) -> System.out.println(e.getX() + ", " + e.getY()));
8
37 To handle the key pressed event on a pane p, register the handler with p using ______.
A. p.setOnKeyClicked(handler);
B. p.setOnKeyTyped(handler);
C. p.setOnKeyReleased(handler);
D. p.setOnKeyPressed(handler);
9
Sheet7 : File_Handling & Thread & Excepation
Java Revision
Revesion 8
Exception Handling
2
11. What exception type does the following program throw?
public class Test {
public static void main(String[] args) {
Object o = null;
System.out.println(o);
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. No exception
E. NullPointerException
12 Show the output of the following code.
(a)
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.print(i + " ");
try {
System.out.println(1 / 0);
}
catch (ArithmeticException ex) {
System.out.println("Exception occurred");
}
}
}
}
(b)
public class Test {
public static void main(String[] args) {
try {
for (int i = 0; i < 2; i++) {
System.out.print(i + " ");
System.out.println(1 / 0);
}
}
catch (ArithmeticException ex) {
System.out.println("Exception occurred");
}
}}
a.
0 Exception occurred
1 Exception occurred
b.
0 Exception occurred
3
14. What exception type does the following program throw?
public class Test {
public static void main(String[] args) {
Object o = new Object();
String d = (String)o;
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
15. Analyze the following code:
public class Test {
public static void main(String[] args) {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
}
catch (Exception ex) {
System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
}
}
A. The program displays NumberFormatException.
B. The program displays RuntimeException.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compile error.
4
17. Analyze the following program.
public class Test {
public static void main(String[] args) {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
A. An exception is raised due to Integer.parseInt(s);
B. An exception is raised due to 2 / i;
C. The program has a compile error.
D. The program compiles and runs without exceptions.
18. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
p();
System.out.println("After the method call");
}
catch (NumberFormatException ex) {
System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
}
static void p() {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
}
A. The program displays NumberFormatException.
B. The program displays NumberFormatException followed by After the method call.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compile error.
E. The program displays RuntimeException.
5
19. What is wrong in the following program?
public class Test {
public static void main (String[] args) {
try {
System.out.println("Welcome to Java");
}
}
}
A. You cannot have a try block without a catch block.
B. You cannot have a try block without a catch block or a finally block.
C. A method call that does not declare exceptions cannot be placed inside a try block.
D. Nothing is wrong.
20. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
p();
System.out.println("After the method call");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
catch (Exception ex) {
System.out.println("Exception");
}
}
static void p() throws Exception {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
catch (Exception ex) {
System.out.println("Exception");
}
}
}
A. The program displays RuntimeException twice.
B. The program displays Exception twice.
C. The program displays RuntimeException followed by After the method call.
D. The program displays Exception followed by RuntimeException.
E. The program has a compile error.
6
21. What is displayed on the console when running the following program?
public class Test {
public static void main (String[] args) {
try {
System.out.println("Welcome to Java");
}
finally {
System.out.println("The finally clause is executed");
}
}
}
A. Welcome to Java
B. Welcome to Java followed by The finally clause is executed in the next line
C. The finally clause is executed
D. None of the above
22. What is displayed on the console when running the following program?
public class Test {
public static void main (String[] args) {
try {
System.out.println("Welcome to Java");
return;
}
finally {
System.out.println("The finally clause is executed");
}
}
}
A. Welcome to Java
B. Welcome to Java followed by The finally clause is executed in the next line
C. The finally clause is executed
D. None of the above
7
23. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
System.out.println("Welcome to Java");
int i = 0;
int y = 2 / i;
System.out.println("Welcome to HTML");
}
finally {
System.out.println("The finally clause is executed");
}
}
}
A. Welcome to Java, then an error message.
B. Welcome to Java followed by The finally clause is executed in the next line, then an error
message.
C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is
executed, then an error message.
D. None of the above.
24. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
System.out.println("Welcome to Java");
int i = 0;
double y = 2.0 / i;
System.out.println("Welcome to HTML");
}
finally {
System.out.println("The finally clause is executed");
}
}
}
A. Welcome to Java.
B. Welcome to Java followed by The finally clause is executed in the next line.
C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is
executed.
D. None of the above.
8
25. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
System.out.println("Welcome to Java");
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
catch (RuntimeException ex) {
System.out.println("Welcome to Java");
}
finally {
System.out.println("End of the block");
}
}
}
A. The program displays Welcome to Java three times followed by End of the block.
B. The program displays Welcome to Java two times followed by End of the block.
C. The program displays Welcome to Java three times.
D. The program displays Welcome to Java two times.
26. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
System.out.println("Welcome to Java");
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
catch (RuntimeException ex) {
System.out.println("Welcome to Java");
}
finally {
System.out.println("End of the block");
}
System.out.println("End of the block");
}
}
A. The program displays Welcome to Java three times followed by End of the block.
B. The program displays Welcome to Java two times followed by End of the block.
C. The program displays Welcome to Java two times followed by End of the block two times.
D. You cannot catch RuntimeException errors.
9
27. What is displayed on the console when running the following program?
public class Test {
public static void main(String[] args) {
try {
System.out.println("Welcome to Java");
int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");
}
finally {
System.out.println("End of the block");
}
System.out.println("End of the block");
}
}
A. The program displays Welcome to Java three times followed by End of the block.
B. The program displays Welcome to Java two times followed by End of the block.
C. The program displays Welcome to Java two times followed by End of the block two times.
D. The program displays Welcome to Java and End of the block, and then terminates because of
an unhandled exception.
What is displayed when running the following program?
28 public class Test {
public static void main(String[] args) {
try {
int[] list = new int[10];
System.out.println("list[10] is " + list[10]);
}
catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
catch (Exception ex) {
System.out.println("Exception");
}
}
}
RuntimeException
10
29 What RuntimeException will the following programs throw, if any?
(a)
public class Test {
public static void main(String[] args) {
System.out.println(1 / 0);
}
}
(b)
public class Test {
public static void main(String[] args) {
int[] list = new int[5];
System.out.println(list[5]);
}
}
(c)
public class Test {
public static void main(String[] args) {
String s = "abc";
System.out.println(s.charAt(3));
}
}
(d)
public class Test {
public static void main(String[] args) {
Object o = new Object();
String d = (String)o;
}
}
(e)
public class Test {
public static void main(String[] args) {
Object o = null;
System.out.println(o.toString());
}
}
(f)
public class Test {
public static void main(String[] args) {
System.out.println(1.0 / 0);
}
}
a. ArithmeticException
b. ArrayIndexOutOfBoundsException
c. StringIndexOutOfBoundsException
d. ClassCastException
e. NullPointerException
f. No exception
11