Sunteți pe pagina 1din 145

Terms and Conditions. 1. This is top secret, walang laglagan pag nagkahulihan. 2.

Please don't forget to thank the people who are making this. Di porket pumas a na kayo ganun ganun nalang? Comments section:

Creators: 1. ChupulsMaster1 2. ChupulsMaster2 Lesson 2: 1. True The ? is a special symbol in Java. T 2. True static is a reserved word in Java. T 3. False The following is a legal Java identifier: !Hello! T 4. False An identifier can be any sequence of characters and integers. T 5.False A byte is an example of a boolean data type. T 6. True The symbol '*' belongs to the char data type. T 7. True The data type double is a floating-point data type. T 8.True The number of significant digits in a float variable is up to 6 or 7. T 9. False An operator that has only one operand is called a unique operator. F F F F F F F F

T 10. True Multiplication and division have the same operator precedence. T 11.True Operators of the same precedence are evaluated from left to right. T

12. False If a Java arithmetic expression has no parentheses, operators are evaluated from left to right. T 13. True In Java, the value of the expression 32 / 5.0 is 6.4. T F F

14. False When evaluating a mixed expression, all integer operands are converted to floati ng-point numbers with zero decimal part. T F

15. True When a value of one data type is automatically changed to another data type, an implicit type coercion has occurred. T 16. True Suppose x = 6.7. The value of the expression (int)(x + 0.5) is 7.0. T F F

17. True Suppose x = 15.7. The output of the statement -- System.out.println((int)(x) / 2 ); is 7. T F

18. False Suppose x = 18.9. The output of the statement -- System.out.println((int(x) % 3) ; is 1. T 19. False The null string contains one character. T 20. True A string is a sequence of zero or more characters. F F

T 21. False The value of a variable cannot change during program execution. T

22. False If a = 4; and b = 3; then after the statement a = b; executes the value of b is erased. T 23. False Java automatically initializes all variables. T F F

24. False Suppose console is a Scanner object initialized with the standard input device. The expression console.nextInt(); is used to read one int value and the expressi on console.nextDouble();is used to read two int values. T F

25. False Suppose console is a Scanner object initialized with the standard input device a nd x and y are int variables. Cosider the following statements: x = console.nextInt(); y = console.nextInt(); These statements require the value of x and y to be input on separate lines. T 26. False The class Scanner is contained in the package java.io. T 27. True The statement count = count + 1; is equivalent to count++; T F F F

28. False If ++x is used in an expression, first the expression is evaluated, then the val ue of x is incremented by 1. T F

29. True Suppose that count is an int variable. The statements --count; and count--; toge ther decrement the value of count by 2. T F

30. False Suppose x = 8. After the execution of the statement y = x++; y is 9 and x is 8.

31. False Suppose a = 4. After the execution of the statement b = ++a; b is 4 and a is 5. T F

32. True Suppose a = 5. After the execution of the statement ++a; the value of a is 6. T F

33. False Suppose a = 15. After the execution of the statement --a; the value of a is 13. T F

34. False Suppose that alpha and beta are int variables. The statement alpha = beta++; is equivalent to the statement alpha = ++beta;. T F

35. False Suppose that alpha and beta are int variables. The statement alpha = --beta; is equivalent to the statement alpha = 1 - beta; while the statement alpha = beta--; is equivalent to the statement alpha = beta - 1;. T F

36. True The operator + can be used to concatenate two strings, as well as a string and a numeric value or a character. T F

37. True Both System.out.println and System.out.print can be used to output a string on t he standard output device. T F

38. True The expression System.out.println(); inserts the newline character at the end of the line. T 39. True \n (Newline) moves the insertion point to the beginning of the next line. T 40. False \r (Return) moves the insertion point to the beginning of the next line. T F F F

41. True A package is a collection of related classes. T 42. False The Java source file must have a .class extension. T F F

43. True Executable statements perform calculations, manipulate data, create output, and accept input. T 44. False A comma is also called a statement terminator. T 45. True The pair of characters // is used for single line comments. T 46. False Multi line comments are enclose between */ and /*. T 47. False The following two statements are equivalent. a. x *= y + 2; b. x = x * y + 2; T 48. True Suppose that sum is an int variable. The statement sum += 7; is equivalent to the statement sum = sum + 7; T F F F F F F

49. True Suppose that prod is a double variable. The statement prod *= 0; is equivalent t o the statement prod = 0;. Lesson 2: String and Operators 1. True The word new is an operator. T F

2. False Given String name; the value of name is directly stored in its memory space. T 3. False The + operator is used to instantiate a class. T 4. True The new operator can be used to create a class object. T 5. True Java provides automatic garbage collection. T 6. True Primitive type variables directly store data into their memory space. T 7. False The class Math is contained in the java.text package. T F F F F F F

8. True Contents of the java.lang package do not need to be imported into a program in o rder to be used. T F

9. False In order to use a predefined method, you simply need to know the name of the met hod. T 10. True The . (dot) operator is also called the member access operator. T F F

11. True In the class String, the substring method extracts a string from within another string. T 12. True indexOf(String str) is a method in the class String. T F F

13. False The method length in the class String returns the number of characters in the st

ring not including whitespace characters. T 14. False String variables are primitive variable types. T 15. False The method printf is used only to format the output of decimal numbers. T 16. False The default output of decimal numbers of the type float is 9 decimal places. T 17. True Suppose x = 15.674. The output of the statement System.out.printf("%.2f", x); is 15.67. T 18. False Suppose z = 9525.9864./ The output of the statement System.out.printf("%.2f", z); is 9525.98. T F F F F F F

19. True A string consisting of only an integer or a decimal number is called a numeric s tring. T 20. False The value of the expression Integer.parseInt("-823") is -"823" T 21. True The value of the expression Float.parseFloat("-542.97") is -542.97. T F F F

22. True The method, parseInt is used to convert a numeric integer string into a value of the type int. T 23. True F

The classes Integer, Float, and Double are called wrapper classes. T 24. False The class JOptionPane is part of the package java.io. T F F

25. True The class JOptionPane allows a programmer to use graphical interface components to obtain input from a user. T F

26. False The statement System.exit(0); is found at the end of every working Java program. T F

27. True Given a decimal number, the method format of the class String returns the string containing the digits of the formatted number. T F

28. True When writing output to a file, if the file is not closed at the end of the progr am, you may not be able to view your output properly. T 29. False If the output file does not exist you will get a FileNotFoundException. T F F

30. True If the specified output file does not exist, the computer prepares an empty file for output. C 1. Which of the following is a valid statement? a. b. c. d. String String String name = name("Doe"); ("Doe"); name = "Doe"; new String; and the ma

C 2. If the String variable str is assigned the string Java Programming chine allocates the memory location to 2500 then str contains ____. a. b. c. d. the value 2500 the value Java Programming. the address 2500 None of these

B 3. In Java, all variables declared using a class are ____. a. primitive variables

b. reference variables c. constants d. operators A 4. Which statement instructs a program to run the garbage collector? a. b. c. d. System.gc(); System.flush(); System.out(); There is only automatic garbage collection in Java.

A 5. There are ____ types of methods in a class. a. b. c. d. 2 3 4 5

B 6. Which package is automatically imported by the Java system? a. b. c. d. C java.io java.lang java.util java.swing

7. What is the value of the following statement? Math.pow(2,4) a. b. c. d. 6 8 16 24

B 8. Which of the following methods is contained in the package java.util? a. b. c. d. format showMessageDialog nextInt printf

C 9. Which of the following is the member access operator? a. b. c. d. + . ->

C 10. Suppose str is a String variable. The statement str = new String("Hello World"); is equivalent to which of the following? a. b. c. d. new String = "Hello World"; String new = "Hello World"; str = "Hello World"; "Hello World";

C 11. What will most probably happen if you omit the dot operator when accessin

g a method? a. b. c. d. An exception will be thrown. The computer will crash. A syntax error will be reported. The program will execute as planned.

C 12. Consider the following statements. String sentence; String str1; sentence = "Today is Wednesday."; What is the value of str1 after the following statement executes? str1 = sentence.substring(9, 18); What is the value of str1? a. b. c. d. Today is Wednesday Wednesday Wednesday.

B 13. Consider the following statements String sentence; String str1, str2; sentence = "Today is Wednesday."; What is the value of str2 after the following statements execute? str1 = sentence.substring(9, 18); str2 = str1.substring(0, 3); a. b. c. d. Tod Wed Wedn is

C 14. Consider the following statements. String sentence; int length1; sentence = "Today is Wednesday."; What is the value of length1 after the following statement executes? length1 = sentence.length(); a. b. c. d. 16 17 19 20

B 15.Consider the following statements.

String sentence; String str; sentence = "Today is Wednesday."; What is the value of str after the following statement executes? str = sentence.replace('d', '*'); a. b. c. d. Today To*ay Today **d** is Wednesday. is We*nes*ay. * Wednesday ** **d***d**

D 16. An expression such as str.length(); is an example of a(n) ____. a. b. c. d. system call string object class operation

B 17. Which of the following outputs 56734.987 to three decimal places? a. b. c. d. System.out.printf("3f%", 56734.9875); System.out.printf(".3f%", 56734.9875); System.out.printf(".03f%", 56734.9875); None of these

D 18. What is the output of the following statement? System.out.printf(".3f%", 56.1); a. b. c. d. 56 56.1 56.000 56.100

D 19. The showMessageDialog method has ____ parameters. a. b. c. d. 1 2 3 4

A 20. Suppose that you have the declaration: int num = 763; double x = 658.75; String str = "Java Program."; What is the output of the following statements? System.out.println("123456789012345678901234567890"); System.out.printf("%5d%7.2f%15s%n", num, x, str); a. 123456789012345678901234567890 763 658.75 Java Program. b. 123456789012345678901234567890 763 658.75 Java Program. c. 123456789012345678901234567890

763 658.75 Java Program. d. None of these B 21. Suppose that you have the declaration: int num = 763; double x = 658.75; String str = "Java Program."; What is the output of the following statements? System.out.println("123456789012345678901234567890"); System.out.printf("%-5d%-7.2f%-15s ***%n", num, x, str); a. 123456789012345678901234567890 763 658.75 Java Program. *** b. 123456789012345678901234567890 763 658.75 Java Program. *** c. 123456789012345678901234567890 763 658.75 Java Program. *** d. None of these A 22. Which of the following statements would produce a Java Input dialog box w ith the text Enter your name and press OK ? a. name = JOptionPane.showInputDialog("Enter your name and press OK"); b. name = JOptionPane.showMessageDialog("Enter your name and press OK", JOptionPane.QUESTION_MESSAGE, null); c. name = System.in(); d. System.out.println("Enter your name and press OK"); D 23. What happens when JOptionPane.WARNING_MESSAGE is chosen as the messageTy pe parameter? a. b. c. d. No icon is displayed in the dialog box. An X is displayed in the dialog box. A question mark is displayed in the dialog box. An exclamation point is displayed in the dialog box.

A 24. Consider the following statements. double x; String y; y = String.format("%.2f", x); If x = 43.579, what is the value of y? a. b. c. d. "43" "43.57" "43.58" None of these

A 25. Which of the following is an area of secondary storage used to hold infor mation? a. file b. variable

c. constant d. buffer Lesson 4: 1. False A program uses repetition to implement a branch. T 2. True Conditional statements help incorporate decision making into programs. T 3. False The symbol > is a logical operator. T 4. True != is a relational operator. T 5. False All relational operators are ternary operators. T 6. False A computer program will recognize both = = and == as the equality operator. T 7. False In Java, both ! and != are relational operators. T 8. True Determine whether the statement 6.9 <= 7.6 is true or false. T 9. True Determine whether the expression 'A' < 'T' is true or false. T 10. True F F F F F F F F F

The method compareTo is part of the class String. T 11. False Consider the following the statements. String str1 = "cat"; String str2 = "cats"; Determine whether the statement str1.equals(str2); is true or false. T 12. False In Java, !, &&, and || are called relational operators. T 13. False Determine whether the expression !('F' > 'A') is true or false. T 14. False The expression !(x > 10) is equivalent to the expression x < 10. T 15. False The expression !(x < 0) is true only if x is a positive number. T 16. True ! is a logical operator. T 17. True Determine whether the expression ('M' > 'S') || (5 <= 8) is true or false. T 18. False Determine whether the expression (10 >= 5) && (7 <= 4) F F F F F F F F

is true or false. T F

19. True Suppose P and Q are logical expressions. The logical expression P && Q is true i f both P and Q are true. T F

20. True Suppose x = 10 and y = 20. The value of the expression ((x >= 10) && (y <= 20)) is true. T F

21. False The expression (x >= 0 && x <= 100) evaluates to false if either x < 0 or x >= 1 00. T F

22. False Suppose P and Q are logical expressions. The expression P || Q is false if eithe r P is false or Q is false. T 23. True The operators != and == have the same order of precedence. T 24. True In Java, && has a higher precedence than ||. T 25. False Determine whether the expression 6 < 5 || 'g' > 'a' && 7 < 4 is true or false. T 26. True Suppose found = true; and num = 6; The value of the expression (!found) || (num > 6) is false. T 27. False In Java. the expression F F F F F

'A' < ch < 'Z' is equivalent to the expression 'A' < ch && ch < 'Z' T 28. False Every if statement must be accompanied by an else statement. T 29. True The following blocks of Java code are equivalent. (Assume that score is an int variable and grade is a char variable.) (i) if (score grade if (score grade (ii) if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; T 30. True The output of the Java code int x = 5; if (x > 10) System.out.println("Hello "); else System.out.println("There. "); System.out.println("How are you?"); is: There. How are you? T F F >= 90) = 'A'; >= 80 && score < 90) = 'B'; F F

31. False Including a semicolon before the action statement in a one-way selection causes a syntax error. T 32. False The output of the Java code: int num = 20; if (num <= 10) //Line 1 if (num >= 0) //Line 2 System.out.println("Num is between 0 and 10"); F

//Line 3

else is:

//Line 4 System.out.println("Num is greater than 10"); Num is greater than 10. T

//Line 5

33. True Consider the following statements. int score; String grade; if (score >= 65) grade = "pass"; else grade = "fail"; If score is equal to 75, the value of grade is pass. T 34. False Consider the following statements. int num = 5; if (num >= 5) System.out.println(num); else System.out.println(num + 5); The output of this code is 10. T 35. True An else statement must be paired with an if statement. T 36. True A compound statement or block of statements is treated as a single statement. T 37. True When one control statement is located within another it is said to be nested. T 38. False All switch structures include default cases. T 39. False In Java, case is a reserved word, but break is not a reserved word. T 40. True F F F F F F F

The output of the Java code: (Assume that console is a Scanner object initialize d to the standard input device.) int alpha = 3; int beta = console.nextInt(); switch (beta) { case 3: alpha = alpha + 3; case 4: alpha = alpha + 4; case 5: alpha = alpha + 5; default: alpha = alpha + 6; } is: 14 T F //Assume input is 5

41. False The output of the Java code: (Assume that console is a Scanner object initialize d to the standard input device.) int alpha = 5; int beta = console.nextInt(); switch (beta) { case 1 : alpha = alpha + 1; case 2 : alpha = alpha + 2; case 3 : alpha = alpha + 3; default : alpha = alpha + 4; } is: 7 T 42. False All switch cases include a break statement. T F F //Assume input is 2

43. False The execution of a break statement in a switch statement automatically exits the program. Practice Test Chapter 04: Control Structures I D Question 1 What is the output of the following code fragment if the input value is 4? (Assu me that console is a Scanner object initialized to the standard input device.) int num; int alpha = 10; num = console.nextInt(); switch (num) {

case 3: alpha++; break; case 4: case 6: alpha = alpha + 3; case 8: alpha = alpha + 4; break; default: alpha = alpha + 5; } System.out.println(alpha); a. b. c. d. 13 14 15 17

True Question 2 Suppose P and Q are logical expressions. The logical expression P && Q is true i f both P and Q are true. a. True b. False

A Question 3 What is the value of the following expression? 5 < 3 || 6 < 7 || 4 > 1 && 5 > 3 || 2 < x

a. b. c. d.

true false x It cannot be determined.

True Question 4 ! is a logical operator. a. True b. False

F Question 5

A program uses repetition to implement a branch. a. True b. False

C Question 6 In a ____ control structure, the computer executes particular statements dependi ng on some condition(s). a. b. c. d. looping repetition selection sequence

True Question 7 Conditional statements help incorporate decision making into programs. a. True b. False

False Question 8 The execution of a break statement in a switch statement automatically exits the program. a. True b. False

False Question 9 Suppose that you have the following code. int num = 5; if (num >= 5) System.out.println(num); else System.out.println(num + 5); The output of this code is 10.

a. True b. False

B Question 10 Suppose that you have the following code: int sum = 0; int num = 10; if (num > 0) sum = sum + num; else if (num > 5) sum = num + 15; After this code executes, what is the value of sum? a. b. c. d. 0 10 20 25

D Question 11 Consider the following statement. int y = !(12 < 5 || 3 <= 5 && 3 > x) ? 7 : 9; What is the value of y if x = 2? a. b. c. d. 2 3 7 9

A Question 12 What is the output of the following Java code? int x = 55; int y = 5; switch (x % 7) { case 0: case 1: y++; case 2: case 3: y = y + 2;

case 4: break; case 5: case 6: y = y 3; } System.out.println(y); a. b. c. d. 2 5 8 None of these

C Question 13 Consider the following statement int y = !(12 < 5 || 3 <= 5 && 3 > x) ? 7 : 9; What is the value of y if x = 4? a. b. c. d. 3 5 7 9

C Question 14 Suppose x and y are int variables. Consider the following statements. if (x > 5) y = 1; else if (x < 5) { if (x < 3) y = 2; else y = 3; } else y = 4; What is the value y if x = 3? a. b. c. d. 1 2 3 4

T Question 15 The output of the Java code: (Assume that console is a Scanner object initialize d to the standard input device.) int alpha = 3; int beta = console.nextInt(); switch (beta) { case 3: alpha = alpha + 3; case 4: alpha = alpha + 4; case 5: alpha = alpha + 5; default: alpha = alpha + 6; } is: 14 a. True b. False //Assume input is 5

C Question 16 Which of the following is NOT a relational operator in Java? a. b. c. d. != <= << >=

D Question 17 Which of the following has the highest value? a. b. c. d. '+' '*' 'R' 'a'

False Question 18 All switch cases include a break statement. a. True b. False

True Question 19 Determine whether the expression ('M' > 'S') || (5 <= 8) is true or false. a. True b. False

False Question 20 In Java. the expression 'A' < ch < 'Z' is equivalent to the expression 'A' < ch && ch < 'Z' a. True b. False

True Question 21 When one control statement is located within another it is said to be nested. a. True b. False

C Question 22 Two-way selection in Java is implemented using ____. a. b. c. d. if statements for loops if...else statements sequential statements

A Question 23

Consider the following statements. String str1 = "car"; String str2 = "cars"; What is the value of the expression str2.compareTo(str1)? a. b. c. d. a positive integer a negative integer 0 a boolean value

A Question 24 What is the output of the following code? if ( 6 > 8) { System.out.println(" ** "); System.out.println("****"); } else if (9 == 4) System.out.println("***"); else System.out.println("*");

a. b. c. d.

* ** *** ****

True Question 25 Consider the following statements. int score; String grade; if (score >= 65) grade = "pass"; else grade = "fail"; If score is equal to 75, the value of grade is pass. a. True b. False

A Question 26 Suppose x and y are int variables. Consider the following statements. if (x > 5) y = 1; else if (x < 5) { if (x < 3) y = 2; else y = 3; } else y = 4; What is the value of y if x = 6? a. b. c. d. 1 2 3 4

C Question 27 After the execution of the following code, what will be the value of num if the input value is 4? (Assume that console is a Scanner object initialized to the st andard input device.) int num = console.nextInt(); if (num > 0) num = num + 10; else if (num >= 5) num = num + 15; a. b. c. d. 4 5 14 15

B Question 28 Consider the following statement. String str = "cat";

What would be the value of the expression str3.compareTo("cat")? a. b. c. d. < 0 = 0 > 0 false

B Question 29 Which of the following will cause a semantic error, if you are trying to compare x to 5? a. b. c. d. if if if if (x (x (x (x == 5) = 5) <= 5) >= 5)

T Question 30 A compound statement or block of statements is treated as a single statement. a. True b. False

False Question 31 In Java, case is a reserved word, but break is not a reserved word. a. True b. False

False Question 32 Determine whether the expression !('F' > 'A') is true or false. a. True b. False

False Question 33 A computer program will recognize both = = and == as the equality operator. a. True b. False

True Question 34 Suppose found = true and num = 6. The value of the expression (!found) || (num > 6) is false. a. True b. False

True Question 35 The method compareTo is part of the class String. a. True b. False

B Question 36 The conditional operator ?: takes _____ arguments. a. b. c. d. 2 3 4 5

B Question 37 What is the output of the following Java code? int x = 6; if (x > 10) System.out.println("One "); System.out.println("Two ");

a. b. c. d.

One Two One Two None of these

False Question 38 In Java, !, &&, and || are called relational operators. a. True b. False Lesson 5: true 1. A loop is a control structure that causes certain statements to be executed over and over until certain conditions are met..

false 2. The statement in the body of a while loop is the decision-maker.

true 3. The loop condition is reevaluated after every iteration of the loop.

false 4. If the initial condition of any while loop is false it will still execute once.

true 5. An infinite loop executes indefinitely.

true 6. In the case of an infinite while loop, initially the while expression (that is, the decision maker) is true.

false 7. If the while expression becomes false in the middle of the while loop body, the loop terminates immediately.

false 8. When a while loop terminates the control first goes back to the statement just b efore the while statement and then the control goes to the statement immediately following the while loop.

true 9. The output of the Java code (Assume all variables are properly declared.) num = 100; while (num <= 148) num = num + 5; System.out.println(num); is: 150

false 10. The output of the Java code (Assume all variables are properly declared.) num = 450; while (num > 500) num = num + 5; System.out.println(num); is: 500

false 11. The while loop int j = 0; while (j < 20) j++; terminates when j > 20.

false 12. Control variables are automatically initialized in a loop.

true 13. A counter-controlled loop is used when the exact number of data entries is known .

true 14. The output of the Java code (Assume all variables are properly declared.) n = 1; while (n < 5) { n++; System.out.print(n + " "); } System.out.println(); is: 2 3 4 5

false 15. The output of the Java code (Assume all variables are properly declared.) n = 1; while (n < 5) { System.out.print(n + " "); n++; } System.out.println(); is: 1 2 3 4

true 16. The output of the Java code (Assume all variables are properly declared.) n = 0; while (n < 5) { System.out.print(n + " "); n++; } System.out.println(); is: 0 1 2 3 4 5

true 17. In the case of the sentinel-controlled while loop, the first item is read before the while loop is entered.

false 18. In a sentinel-controlled while loop, the body of the loop continues to execute u

ntil the EOF symbol is read.

false 19. The output of the following Java code (Assume all variables are properly declare d and the input is 6 8 5 3 1). num = console.nextInt(); sum = num; while (num != -1) { num = console.nextInt(); sum = sum + num; } System.out.println(sum); is: 22

true 20. The output of the following Java code (Assume all variables are properly declare d and the input is 4 3 2 6 1). sum = 0; num = console.nextInt(); while (num != -1) { num = console.nextInt(); sum = sum + num; } System.out.println(sum); is: 10

true 21. The control variable in a flag-controlled while loop is a boolean variable.

false 22. EOF-controlled while loop is another name for sentinel-controlled while loop.

false 23. To read data from a file of unspecified length, a sentinel-controlled while loop is a better choice.

true 24. The method hasNext returns false when the end of the input file is reached.

true 25. A number in a Fibonacci sequence is found by taking the sum of the previous two numbers in the sequence.

true 26. A for loop is typically called an indexed for loop.

true 27. The control statements in the for loop include the initial statement, loop condi tion, and update statement.

false 28. As in the while loop, the body of the for loop eventually changes the loop condi tion to false.

false 29. The following for loop executes 20 times. (Assume all variables are properly dec lared.) for (i = 0; i <= 20; i++) System.out.println(i);

true 30. The following for loop executes 26 times. (Assume all variables are properly dec lared.) for (i = 0; i <= 50; i = i + 2) System.out.println(i);

false 31. The output of the Java code (Assume all variables are properly declared.) for (i = 1; i <= 10; i++); System.out.print(i + " "); System.out.println();

is: 1 2 3 4 5 6 7 8 9 10

false 32. The output of the Java code (Assume all variables are properly declared.) System.out.print("St"); for (count = 5; count <= 3; count--) System.out.print('o'); System.out.println('p'); is: Stoop

true 33. The output of the Java code (Assume all variables are properly declared.) System.out.print("St"); for (count = 4; count <= 4; count++) System.out.print('o'); System.out.println('p'); is: Stop

false 34. In the for statement, if the loop condition is omitted, it is assumed to be fals e.

false 35. A syntax error will result if the control statements of a for loop are omitted.

false 36. If a semicolon is placed at the end of a for loop, an infinite loop will result.

false 37. The output of the Java code int count = 5; System.out.print("St"); do { System.out.print('o');

count--; } while (count < 5); System.out.println('p'); is: Stop

true 38. Unlike a while loop, the body of a do...while loop executes at least once.

false 39. A for loop is a post-test loop.

true 40. The do...while loop has an exit condition but no entry condition.

false 41. Because a do...while loop is a post-test loop, the body of the loop may not exec ute at all.

false 42. It is possible that the body of a while loop may not execute at all, but the bod y of a for loop executes at least once.

true 43. After a break statement executes, the program continues to execute with the firs t statement after the structure.

false 44. A break statement is legal in a while loop, but not in a for loop.

true 45. If a continue statement is placed in a do...while structure, the loop-continue t est is evaluated immediately after the continue statement.

false 46. If a continue statement executes in a while loop, the remaining statements will always execute in the next iteration.

false 47. Consider the following while loop. int counter = 1; while (counter < 10) { //... counter++; if (counter % 4 == 0) continue; counter = 0; //... } If the continue statement executes, counter is set to 0. Practice Test Chapter 05: Control Structures II Question 1 True If a continue statement is placed in a do...while structure, the loop-continue t est is evaluated immediately after the continue statement. a. True b. False

Question 2 False In the for statement, if the loop condition is omitted, it is assumed to be fals e. a. True b. False

Question 3 C Which of the following does not have an entry condition? a. EOF-controlled while loop

b. sentinel-controlled while loop c. do...while loop d. for loop

Question 4 D What is the output of the following Java code? int count = 1; int num = 25; while (count < 25) { num = num - 1; count++; } System.out.println(count + " " + num); a. b. c. d. 24 24 25 25 0 1 0 1

Question 5 A Suppose sum, num and j are int variables, and the input is

4 7 12 9 -1 What is the output of the following code? sum = console.nextInt(); num = console.nextInt(); for (j = 1; j <= 3; j++) { num = console.nextInt(); sum = sum + num; } System.out.println(sum); a. b. c. d. 24 25 41 42

Question 6 D

What is the output of the following code? int x = 0; for (int i = 0; i < 4; i++); x++; if (x == 3) System.out.println("*");

a. b. c. d.

* ** *** There is no output

Question 7 F To read data from a file of unspecified length, a sentinel-controlled while loop is a better choice. a. True b. False

Question 8 A What is the output of the following Java code? int num = 10; while (num > 10) num = num - 2; System.out.println(num); a. b. c. d. 10 8 0 None of these

Question 9 T Unlike a while loop, the body of a do...while loop executes at least once. a. True b. False

Question 10 T The loop condition is reevaluated after every iteration of the loop. a. True b. False

Question 11 A What is the output of the following Java code? int x = 1; do { System.out.print(x + " "); x--; } while (x > 0); System.out.println(); a. b. c. d. 1 1 0 1 0 -1 None of these

Question 12 C Suppose sum and num are int variables, and the input is

18 25 61 6 -1 What is the output of the following code? (Assume that console is a Scanner obj ect initialized to the standard input device.) sum = 0; num = console.nextInt(); while (num != -1) { sum = sum + num; num = console.nextInt(); } System.out.println(sum);

a. b. c. d.

92 109 110 None of these

Question 13 T The output of the Java code (Assume all variables are properly declared.) n = 1; while (n < 5) { n++; System.out.print(n + " "); } System.out.println(); is: 2 3 4 5 a. True b. False

Question 14 F A for loop is a post-test loop. a. True b. False

Question 15 F Control variables are automatically initialized in a loop. a. True b. False

Question 16

Consider the following statements. int x = 5; int y = 30;

do x = x * 2; while (x < y); If y = 0, how many times would the do...while loop execute? a. b. c. d. 0 1 2 3

Question 17 D What is the value of x after the following statements execute? int x = 5; int y = 30; do x = x * 2; while (x < y);

a. b. c. d.

5 10 20 40

Question 18 C Which of the following loops is guaranteed to execute at least once? a. b. c. d. counter-controlled while loop for loop do...while loop sentinel-controlled while loop

Question 19 C What is the output of the following Java code? int num = 0; while (num < 5) { System.out.print(num + " "); num = num + 1; } System.out.println();

a. b. c. d.

0 1 2 3 1 2 3 4 0 1 2 3 None of

4 5 5 4 these

Question 20 A What is the output of the following Java code?

int x = 1; int j; for (j = 0; j <= 2; j++) x = x * j; System.out.println(x); a. b. c. d. 0 1 2 None of these

Lesson 6: GUI Practice Test Chapter 06: Graphical User Interface (GUI) and Object-Oriented Design (OOD) Question 1 JLabels are used to get input and show output. b. False

Question 2 JFrame is a package. b. False

Question 3 What is the name for Java classes that are provided so that values of primitive data types can be treated as objects? c. wrappers

Question 4 Which of the following is NOT a required attribute of a window? d. color

Question 5 Given the declaration, Integer num; The statement num = 25; is known as autoboxing of the int type. a. True

Question 6 The method getContentPane of the class JFrame is used to access the content pane of the window. b. False

Question 7 An action event is handled by the class JFrame. b. False

Question 8 Which modifier is used to build classes on top of classes that are interfaces? d. implements

Question 9 Consider the following sentence. If Shape is a class and you create a new class Circle that extends Shape, then S hape is a(n) ____ and Circle is a(n) ____.

Which word goes in the first blank of this sentence? b. superclass

Question 10 Which of the following is not a method of the class JTextField? d. setVisible

Question 11 Every window has a title, width, and height. a. True

Question 12 The Java class that you use to create windows is ____. b. JFrame

Question 13 Which of the following GUI component is used to get input into a GUI program? c. JTextField

Question 14 GUI stands for Graphical User Interface. a. True

Question 15 Consider the following problem statement. Write a program that takes as input the radius of a circle and finds the circumf erence and area of the circle.

Based on this problem statement, which of the following would most likely be cho sen as the class? b. Circle

Question 16 Which of the following statements is NOT true about GUI programs? c. All components are added directly to the GUI window.

Question 17 The class Container is included in the package javax.swing. b. False

Question 18 An interface is a class that contains only the method headings, and each method heading is terminated with a period. b. False

Question 19 The first step in solving a problem using object-oriented design is to write dow n a detailed description of the problem. a. True

Question 20 When you click a JButton an event is created, known as an action event. a. True

Question 21 The class JFrame contains the method add.

b. False

Question 22 Both private and implements are modifiers in Java. a. True

Question 23 Consider the following problem statement. Write a program to input 5 test scores of a student and calculate and print the mean, median, and mode of the scores. Which words from this problem statement could we use to determine the operations for this program? a. input, calculate, print

Question 24 Given the declaration, Integer num; The following statements are equivalent: num = 25; num = new Integer(25); a. True

Question 25 In object-oriented design, the nouns found in the problem specification can be u sed to select the operations in the program. b. False

Question 26 Which package will you most likely have to import in order to write a GUI progra m?

a. java.awt.*

Question 27 The method addWindowListener is included in the class JFrame. a. True

Question 28 Whenever there is a superclass-subclass relationship, the superclass inherits al l data members and methods of the subclass. b. False

Question 29 Which class is part of the package java.awt? d. Container

Question 30 Consider the following sentence. If Shape is a class and you create a new class Circle that extends Shape, then S hape is a(n) ____ and Circle is a(n) ____. Which word goes in the second blank of this sentence? a. subclass True 1. GUI stands for Graphical User Interface. T F

False 2. Inputs and outputs are always displayed one dialog box at a time when using a GU I. T False 3. JLabels are used to get input and show output. T F F

True. 4. GUI components are placed in a window called JFrame. T False 5. When a user types input into a JTextField, an event has occurred. T False 6. JFrame is a package. T True 7. Every window has a title, width, and height. T True 8. The method addWindowListener is included in the class JFrame. T True 9. In Java, extends is a reserved word. T True 10. The term pixel stands for picture element. T True 11. The height and width of a window are measured in pixels. T F F F F F F F F

False 12. Whenever there is a superclass-subclass relationship, the superclass inherits al l data members and methods of the subclass. T False 13. The class Container is included in the package javax.swing. T False 14. The class JFrame contains the method add. T F F F

False 15. The method getContentPane of the class JFrame is used to access the content pan e of the window.

True 16. If lengthL is a JTextField and pane is a container, then the statement pane.add( lengthL); adds the text field to the content pane of a window. T True 17. The class ActionListener contains only one method, actionPerformed. T False 18. An action event is handled by the class JFrame. T F F F

False 19. An interface is a class that contains only the method headings, and each method heading is terminated with a period. T True 20. When you click a JButton an event is created, known as an action event. T True 21. Both private and implements are modifiers in Java. T F F F

True 22. The first step in solving a problem using object-oriented design is to write dow n a detailed description of the problem. T F

False 23. In object-oriented design, the verbs in the problem specification can be used to identify the objects in the program. T F

False 24. In object-oriented design, the nouns found in the problem specification can be u sed to select the operations in the program. T True 25. In Java, data members are also known as fields. T False 26. Wrapper class objects are mutable. F F

T True 27. Given the declaration, Integer num; The following statements are equivalent: num = 25; num = new Integer(25); T True 28. Given the declaration, Integer num; The statement num = 25; is known as autoboxing of the int type. T

True 29. To compare the values of two Integer objects for equality we can use the method equal of the class Integer. T F

False 30. To determine whether two reference variables of the Integer type point to the sa me Integer object, we can use either the method equal of the class Integer or th e operator ==. Lesson 7: Practice Test Chapter 07: User-Defined Methods Question 1 Given the method heading int larger(int x, int y) which of the following does NOT demonstrate method overloading? c. int max(int x, int y) Question 2 Within a class, outside of every method definition (and every block), an identif ier can be declared anywhere. a. True

Question 3 Suppose that the folowing statement is included in a program. import static java.lang.Math.*; After this statement a static method of the class Math cannot be called using th e name of the class and the dot operator. b. False

Question 4 The return statement must be the last line of the method. b. False

Question 5 Within a method, an identifier used to name a variable in the outer block of the method can be used to name any other variable in an inner block of the method. b. False

Question 6 Which of the following identifiers is NOT visible in block three? a. z (before main)

Question 7 Given the method heading public static String exampleMethod(int n, char ch) what is the return type of the value returned? c. String Question 8 How can a method send a primitive value back to the caller? b. By using the return statement Question 9 Which of the following is NOT a modifier? c. void

Question 10 Value-returning methods must have parameters. b. False

Question 11 The value returned by a value-returning method can be saved for further calculat ion in the program. a. True

Question 12 Two methods are said to have different formal parameter lists if both methods ha ve a different number of formal parameters, or if the number of formal parameter s is the same, then the data type of the formal parameters, in the order you lis t, must differ in at most one position. b. False

Question 13 Which of the following is NOT true about return statements? b. Return statements can be used in void methods to return values.

Question 14 Actual and formal parameters have a many-to-one correspondence. b. False

Question 15 Void methods never have parameters. b. False

Question 16 A local identifier is an identifier that is declared within a method or block an d that is visible only within that method or block. a. True

Question 17 Consider the following method. public static int minimum(int x, int y) { int smaller; if (x < y) smaller = x; else smaller = y; return smaller; } What is the value of s after the following statement executes? int s = minimum(5, minimum(3, 7)); a. 3

Question 18 You can use the class String to pass strings as parameters to a method and chang e the actual parameter. b. False

Question 19 A formal parameter is a variable declared in the method heading. a. True

Question 20 In order to use the method toLowerCase of the class Character, the package java. lang must be imported. a. True

Question 21 Which of the following statements about strings is NOT true? c. The class String contains many methods that allow you to change an existin g string.

Question 22 To use a predefined method you must know the code in the body of the method. b. False

Question 23 Which of the following identifiers is visible in main? b. w (before method two)

Question 24 The class Math is contained in the package java.io. b. False

Question 25 Java allows the programmer to declare a variable in the initialization statement of the for statement. a. True

Question 26 Given the method heading int larger(int x, int y) which of the following would be an incorrect demonstration of method overloading ? a. int larger(int a, int b)

Question 27 Which of the following statements is NOT true? c. The operator new must always be used to allocate space of a specific type, regardless of the type.

Question 28 Which of the following is NOT an actual parameter? c. Variables defined in a method heading

Question 29 Which of the following statements about the following method heading is NOT true ? public static String exampleMethod(int n, char ch) b. The method cannot be used outside the class.

Question 30 Formal parameters of primitive data types provide ____ between actual parameters and formal parameters. a. a one-way link

Question 31 Just like the nesting of loops, Java allows the nesting of methods. b. False 1. True Methods are often called modules. T 2.False The class Math is contained in the package java.io. T 3. True In Java, predefined methods are organized in class libraries. T F F F

4. True In order to use the method toLowerCase of the class Character, the package java. lang must be imported. T 5. False Suppose that the folowing statement is included in a program. import static java.lang.Math.*; After this statement a static method of the class Math cannot be called using th e name of the class and the dot operator. T F F

6. True The value returned by a value-returning method can be saved for further calculat

ion in the program. T 7. False Value-returning methods must have parameters. T 8. True Void methods have no return type. T 9. False To use a predefined method you must know the code in the body of the method. T 10. True A formal parameter is a variable declared in the method heading. T 11. False The word void is a modifier in Java. T 12. False The word final is a return type in Java. T 13. True In Java, return is a reserved word. T 14. False The return statement must be the last line of the method. T 15. True Methods other than the main method only execute when called. T F F F F F F F F F F

16. True When a program executes, the first statement to execute is always the first stat ement in the main method. T 17. False Actual and formal parameters have a many-to-one correspondence. T F F

18. False Void methods never have parameters. T F

19. True If a formal parameter is a variable of a primitive data type, then after copying the value of the actual parameter, there is no connection between the formal pa rameter and actual parameter. T F

20. True Reference variables as parameters allow you to return more than one value from a method. T F

21. False You can use the class String to pass strings as parameters to a method and chang e the actual parameter. T 22. True Strings assigned to StringBuffer variables can be altered. T F F

23. True A local identifier is an identifier that is declared within a method or block an d that is visible only within that method or block. T 24. False Just like the nesting of loops, Java allows the nesting of methods. T F F

25. True Within a class, outside of every method definition (and every block), an identif ier can be declared anywhere. T F

26. False Within a method, an identifier used to name a variable in the outer block of the method can be used to name any other variable in an inner block of the method. T F

27. True Java allows the programmer to declare a variable in the initialization statement of the for statement. T F

28. False Suppose x is an identifier declared within a class and outside of every method s d

efinition (block). If x is declared without the reserved word static, then it ca n be accessed in a static method. T 29. False No two methods in the same class can have the same name. T F F

30. False Two methods are said to have different formal parameter lists if both methods ha ve a different number of formal parameters, or if the number of formal parameter s is the same, then the data type of the formal parameters, in the order you lis t, must differ in at most one position. T 31. False The signature of a method consists of only its formal parameter list. Chapter 8: Practice Test Chapter 08: User-Defined Classes and ADTs Question 1 Finalizers are value-returning methods that return the final value of a variable . b. False Question 2 The ____ of a class are called the members of the class. c. components Question 3 Members of a class consist of packages, methods, and libraries. b. False Question 4 You can import your classes in the same way that you import classes from the pac kages provided by Java. a. True Question 5 Consider the following class definition. public class Rectangle { private double length; private double width; private double area; private double perimeter; F

public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(10, 4); Which of the following set of statements are valid in Java? (i) bigRect.area(); bigRect.perimeter(); bigRect.print(); (ii) bigRect.area = bigRect.area(); bigRect.perimeter = bigRect.perimeter(); bigRect.print(); a. Only (i) Question 6 public class Illustrate { private int x; private static int y; public static int count; public static int z; public Illustrate()

{ x = 1; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y + ", count = " + count); } public static void incrementY() { y++; } }

Which of the following statements would you use to declare a new reference varia ble of the type Illustrate and instantiate the object with a value of 9? a. Illustrate illObject = new Illustrate(9); Question 7 What is the function of the reserved word class? b. It defines only a data type; it does not allocate memory. Question 8 An accessor method of a class first accesses the values of the data members of t he class and then changes the values of the data members. b. False Question 9 In ____ copying, each reference variable refers to its own object. b. deep Question 10 In shallow copying, each reference variable refers to its own object. b. False Question 11 The method finalize automatically executes when the class object goes out of sco pe. a. True

Question 12 Consider the following class definition. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public double perimeter() { return 2 * length + 2 * width; } } Which of the following statements correctly instantiate the Rectangle object myR ectangle? (i) myRectangle Rectangle = new Rectangle(10, 12); (ii) class Rectangle myRectangle = new Rectangle(10, 12); (iii) Rectangle myRectangle = new Rectangle(10, 12); c. Only (iii) Question 13 Given the declaration public class MyClass { private int x;

public void print() { System.out.println("x = " + x); } } MyClass aa = new MyClass(); The following statement is legal. aa.print(); a. True Question 14 What is the main use of inner classes? b. To handle events Question 15 The components of a class are called fields. b. False

Question 16 Modifiers are used to alter the behavior of the class. a. True Question 17 When does the method finalize execute? d. When the class object goes out of scope Question 18 How many constructors can a class have? d. Any number Question 19 Consider the following statements. public class Circle { private double radius; public Circle()

{ radius = 0.0; } public Circle(double r) { radius = r; } public void set(double r) { radius = r; } public void print() { System.out.println(radius + " " + area + " " + circumference); } public double area() { return 3.14 * radius * radius; } public double circumference() { return 2 * 3.14 * radius; } } Circle myCircle = new Circle(); double r; Which of the following statements are valid in Java? (Assume that console is Sca nner object initialized to the standard input device.) (i) r = console.nextDouble(); myCircle.area = 3.14 * r * r; System.out.println(myCircle.area); (ii) r = console.nextDouble(); myCircle.set(r); System.out.println(myCircle.area()); b. Only (ii) Question 20 Which of the following is a constructor without parameters? b. default constructor Question 21 The built-in operation that is valid for classes is the dot operator (.). a. True

Question 22 public class Illustrate { private int x; private static int y; public static int count; public static int z; public Illustrate() { x = 1; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y + ", count = " + count); } public static void incrementY() { y++; } }

What does the default constructor do in the class definition above? b. Sets the value of x to 1 Question 23 Suppose that a class method is used to implement a binary operation on the class objects; then the method must have two parameters of the class type. b. False Question 24 Given the declaration public class MyClass { private int x; public void print() { System.out.println("x = " + x); } }

MyClass aa = new MyClass(); The following statement is legal. aa.x = 10; b. False

Question 25 public class Illustrate { private int x; private static int y; public static int count; public static int z; public Illustrate() { x = 1; } public Illustrate(int a) { x = a; } public void print() { System.out.println("x = " + x + ", y = " + y + ", count = " + count); } public static void incrementY() { y++; } }

Based on the class definition above, which of the following statements is illega l? d. Illustrate.x++;

Question 26 Consider the following class definition. public class Rectangle { private double length;

private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { length = l; width = w; } public void set(double l, double w) { length = l; width = w; } public void print() { System.out.println(length + " " + width); } public double area() { return length * width; } public void perimeter() { return 2 * length + 2 * width; } } Suppose that you have the following declaration. Rectangle bigRect = new Rectangle(); Which of the following set of statements are valid in Java? (i) bigRect.set(10, 5}; (ii) bigRect.length = 10; bigRect.width = 5; a. Only (i) Question 27 A class and its members can be described graphically using Unified Modeling Lang uage (UML) notation. a. True Question 28 If the object is created in a user program, then the object can access both the public and private members of the class.

b. False Question 29 When no object of the class type is instantiated static data members of the clas s fail to exist. b. False Question 30 Consider the following statements. public class PersonalInfo { private String name; private int age; private double height; private double weight; public void set(String s, int a, double h, double w) { name = s; age = a; height = h; weight = w; } public String getName() { return name; } public int getAge() { return age; } public double getHeight() { return height; } public double getWeight { return weight; } } PersonalInfo person1 = new PersonalInfo(); PersonalInfo person1 = new PersonalInfo(); String n; int a; double h, w; Which of the following statements are valid in Java? (i) person2 = person1; (ii) n = person1.getName(); a = person1.getAge();

h = person1.getHeight(); w = person1.getWeight(); person2.set(n, a, h, w); c. Both (i) and (ii) Question 31 If a member of a class is public you cannot access it outside the class. b. False

Question 32 If a member of a class is a method, it can (directly) access any member of the c lass. a. True Question 33 A constructor has the same name as the class. a. True Question 34 You cannot override the default definition of the method toString because it is provided by Java. b. False Question 35 Which of the following words indicates an object s reference to itself? a. this

Question 36 A class can have only one constructor. b. False 1. F The components of a class are called fields. T 2. T Modifiers are used to alter the behavior of the class. T 3. F F F

Members of a class are usually classified into three categories: static, public, and void. T 4. F If a member of a class is public you cannot access it outside the class. T F F

5. T If a member of a class is a method, it can (directly) access any member of the c lass. T 6. F Members of a class consist of packages, methods, and libraries. T 7. F The methods of a class must be public. T 8. T The (non-static) data members of a class are called instance variables. T 9. F A constructor has no type and is therefore a void method. T 10. T A constructor has the same name as the class. T 11. F A class can have only one constructor. T 12. F Constructors are called like any other method. T F F F F F F F F

13. T A class and its members can be described graphically using Unified Modeling Lang uage (UML) notation. T F

14. T If the object is created in the definition of a method of the class, then the ob ject can access both the public and private members of the class.

15. F If the object is created in a user program, then the object can access both the public and private members of the class. T 16. F In shallow copying, each reference variable refers to its own object. T 17. T In deep copying, each reference variable refers to its own object. T 18. F Given the declaration public class MyClass { private int x; public void print() { System.out.println("x = " + x); } } MyClass aa = new MyClass(); The following statement is legal. aa.x = 10; T 19. T Given the declaration public class MyClass { private int x; public void print() { System.out.println("x = " + x); } } MyClass aa = new MyClass(); The following statement is legal. aa.print(); T F F F F F

20. T The built-in operation that is valid for classes is the dot operator (.). T F

21. F Suppose that a class method is used to implement a binary operation on the class objects; then the method must have two parameters of the class type. T F

22. T The copy constructor executes when an object is instantiated and initialized usi ng an existing object. T 23. T The method toString is used to convert an object to a String object. T F F

24. F You cannot override the default definition of the method toString because it is provided by Java. T F

25. T The modifier static in the heading specifies that the method can be invoked by u sing the name of the class. T F

26. F When no object of the class type is instantiated static data members of the clas s fail to exist. T F

27. F Finalizers are value-returning methods that return the final value of a variable . T F

28. T The method finalize automatically executes when the class object goes out of sco pe. T F

29. F An accessor method of a class first accesses the values of the data members of t he class and then changes the values of the data members. T 30. T F

A mutator method of a class changes the values of the data members of the class. T F

31. T You can import your classes in the same way that you import classes from the pac kages provided by Java. T 32. T Every object has access to a reference to itself. T F F

33. F In Java, the reference this is used to refer to only the instance variables not the methods of a class. T 34. F Classes that are defined within other classes are called nested classes. T 35. F The term ADT stands for Abstract Definition Type. T F F F

36. T The abstract data type specifies the logical properties without the implementati on details. Lesson 9: Arrays Practice Test Chapter 09: Arrays Question 1 Suppose you have the following declaration: char[] nameList = new char[100]; Which of the following range is valid for the index of the array nameList. (i) 1 through 100 (ii) 0 through 100 c. Both are invalid

Question 2 Suppose alpha is an array of 50 components. Which of the following about alpha i s true?

(i) The base address of alpha is the address of alpha[0]. (ii) The base address of alpha is the address of alpha[1]. a. Only (i)

Question 3 Arrays can be initialized when they are created. a. True

Question 4 int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100;

What is the value at index 10 of the array above? c. 10

Question 5 What is the value of alpha[2] after the following code executes? int[] alpha = new int[5]; int j; for (j = 0; j < 5; j++) alpha[j] = 2 * j + 1; c. 5

Question 6 The instance variable length is a public member and can be directly accessed usi ng the dot operator. a. True

Question 7 If an array index is less than zero, an InvalidIndexException exception is throw n. b. False

Question 8 int[] num = new int[100]; for (int i = 0; i < 50; i++) num[i] = i; num[5] = 10; num[55] = 100;

What is the data type of the array above? a. int

Question 9 double[] as = new double[7]; double[] bs; bs = as;

How many objects are present after the code fragment above is executed? a. 1

Question 10 Which of the following about Java arrays is true? (i) Array components must be of the type double. (ii) The array index must evaluate to an integer. b. Only (ii)

Question 11 What is the output of the following Java code? int[] alpha = {2, 4, 6, 8, 10}; int j; for (j = 4; j >= 0; j--) System.out.print(alpha[j] + " "); System.out.println(); b. 10 8 6 4 2

Question 12 Given the declaration int[] gamma = new int[50]; int j; Which of the following for loop sets the index of gamma out of bounds? (i) for (j = 0; j <= 49; j++) System.out.print(gamma[j] + " "); (ii) for (j = 1; j < 50; j++) System.out.print(gamma[j] + " "); (iii) for (j = 0; j <= 50; j++) System.out.print(gamma[j] + " "); c. Only (iii)

Question 13 If the value in each index of an array is related to the value in the correspond ing index of a different array, the two arrays are parallel. a. True

Question 14 int[] array1 = {1, 3, 5, 7} for (int i = 0; i <array.length; i++) if (array1[i] > 5) System.out.println(i + " " + array1[i]);

Which indices are in bounds for the array array1, given the declaration above? a. 0, 1, 2, 3

Question 15 What is the value of alpha[4] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 2; for (j = 1; j < 5; j++) alpha[j] = alpha[j d. 14

1] + 3;

Question 16 Which of the following statements creates, alpha, an array of 5 components of th e type int and initialize each component to 10?

(i) int[] alhpa = {10, 10, 10, 10, 10}; (ii) int[5] alpha = {10, 10, 10, 10, 10}; a. Only (i)

Question 17 Loops can be used to step through the elements of a one-dimensional array. a. True

Question 18 Given the declaration int[] list = new int[50]; the statement System.out.println(list);

outputs all 50 components of the array list, one component per line. b. False

Question 19 double[][] vals = {{1.1, {3.1, {5.1, {7.1,

1.3, 3.3, 5.3, 7.3,

1.5}, 3.5}, 5.5}, 7.5}}

How many columns are in the array above? c. 3

Question 20 Suppose you have the following declaration: double[] salesData = new double[1000]; Which of the following range is valid for the index of the array salesData. (i) 0 through 999 (ii) 1 through 1000 a. Only (i)

Question 21 A method can have both a variable length formal parameter and other formal param eters. a. True

Question 22 If a method has both a variable length formal parameter and other types of forma l parameters, then the variable length formal parameter must be the last formal parameter of the formal parameter list. a. True

Question 23 Arrays are made up only of integers. b. False

Question 24 What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j; alpha[0] = 5; for (j = 1; j < 5; j++) { if (j % 2 == 0) alpha[j] = alpha[j else alpha[j] = alpha[j } b. 13

1] + 2; 1] + 3;

Question 25 Given the following method heading public static void mystery(int list[], int size) and the declaration int[] alpha = new int[50]; Which of the following is a valid call to the method mystery? c. mystery(alpha, 50);

Question 26 char[][] array1 = new char[15][10];

What is the value of array1.length? d. 15

Question 27 An ArrayOutOfBoundsException is thrown if an index is greater than or equal to t he size of the array minus 1. b. False

Question 28 double[][] vals = {{1.1, {3.1, {5.1, {7.1,

1.3, 3.3, 5.3, 7.3,

1.5}, 3.5}, 5.5}, 7.5}}

What is in vals[2][1]? d. 5.3

Question 29 Consider the following method definition.

public static int strange(int[] list, int listSize, int item) { int count; for (int j = 0; j < listSize; j++) if (list[j] == item) count++; return count; } Which of the following statements best describe the behavior of this method? c. This method returns the number of times item is stored in list.

Question 30 What is the value of alpha[3] after the following code executes? int[] alpha = new int[5]; int j;

for (j = 4; j >= 0; j--) { alpha[j] = j + 5; if (j <= 2) alpha[j + 1] = alpha[j] + 3; } d. 10

Question 31 int[] hit = new hit[5]; hit[0] hit[1] hit[2] hit[3] hit[4] = = = = = 3; 5; 2; 6; 1;

System.out.println(hit[1 + 3]);

What is the output of the code fragment above? a. 1

Question 32 The statement int[] list = new int[25]; creates list to be an array of 26 components because array index starts at 0. b. False

Question 33 The base address of an array is the memory location of the first array component . a. True

Question 34 Which of the following declares an array of int named hits?

b. int[] hits;

Question 35 Suppose list is a one dimensional array, wherein each component is of the type i nt. Further, suppose that sum is an int variable. The following for loop correct ly find the sume of the elements of list. sum = 0; for (double num : list) sum = sum + num; a. True

Question 36 Consider the following declaration: int[] list = new int[10]; int j; int sum; Which of the following correctly finds the sum of the elements of list? (i) sum = 0; for (j = 0; j < 10; j++) sum = sum + list[j]; (ii) sum = list[0]; for (j = 1; j < 10; j++) sum = sum + list[j]; c. Both (i) and (ii)

Question 37 When you pass an array as a parameter, the base address of the actual array is p assed to the formal parameter. a. True

Question 38 Consider the following declaration:

double[] sales = new double[50]; int j; Which of the following correctly initializes all the components of the array sal es to 10. (i) for (j = 0; j < 49; j++) sales[j] = 10; (ii) for (j = 1; j <= 50; j++) sales[j] = 10; d. None of these

Question 39 Only one-dimensional arrays can be passed as parameters. b. False

Question 40 In row processing, a two-dimensional array is processed one row at a time. a. True

Question 41 In Java, the array index starts at 1. b. False

Question 42 A single array can hold components of many different data types. b. False

Question 43 int[] hits = {10, 15, 20, 25, 30}; copy(hits);

What is being passed into copy in the method call above? c. A reference to the array object hits

Question 44 char[][] array1 = new char[15][10];

How many columns are in the array above? c. 10

Question 45 In column processing, a two-dimensional array is processed one column at a time. a. True

Question 46 Consider the following declaration: int[] beta = new int[3]; int j; Which of the following input statements correctly inputs values into beta? (Assu me that console is a Scanner object initialized to the standard input device.) (i) beta[0] = console.nextInt(); beta[1] = console.nextInt(); beta[2] = console.nextInt(); (ii) for (j = 0; j < 3; j++) beta[j] = console.nextInt(); c. Both (i) and (ii)

Question 47 Suppose you have the following declaration:

int[] beta = new int[50]; Which of the following is a valid element of beta. (i) beta[0] (ii) beta[50] a. Only (i)

Question 48 In Java, [] is an operator called the index access operator. b. False

Question 49 The array index can be any integer less than the array size. b. False

Question 50 The instance variable length contains the value of the last index in the array. b. False

Question 51 What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 0; j < 5; j++) System.out.print(list[j] + " "); System.out.println(); b. 0 5 10 15 20

Question 52 char[][] array1 = new char[15][10];

How many dimensions are in the array above? c. 2

Question 53 What is the output of the following Java code? int[] list = {0, 5, 10, 15, 20}; int j; for (j = 1; j <= 5; j++) System.out.print(list[j] + " "); System.out.println(); d. Code contains index out-of-bound 1. T Arrays have a fixed number of components. T 2. F Arrays are made up only of integers. T 3. F A single array can hold components of many different data types. T 4. F The statement int[] list = new int[25]; creates list to be an array of 26 components because array index starts at 0. T F F F F

5. T When an array object is instantiated, its components are initialized to their de fault values. T 6. F In Java, the array index starts at 1. T 7. F The array index can be any integer less than the array size. F F

T 8. F In Java, [] is an operator called the index access operator. T 9. F Given the declaration int[] list = new int[20]; the statement list[12] = list[5] + list[7]; updates the content of the twelfth component of the array list. T

10. T Arrays that are instantiated during program execution are called dynamic arrays. T F

11. T The instance variable length is a public member and can be directly accessed usi ng the dot operator. T F

12. F The instance variable length contains the value of the last index in the array. T 13. T Arrays can be initialized when they are created. T 14. T Loops can be used to step through the elements of a one-dimensional array. T 15. F Given the declaration int[] list = new int[50]; the statement System.out.println(list); outputs all 50 components of the array list, one component per line. T 16. F F F F F

If an array index is less than zero, an InvalidIndexException exception is throw n. T F

17. F An ArrayOutOfBoundsException is thrown if an index is greater than or equal to t he size of the array minus 1. T F

18. T In a method call statement, when passing an array as an actual parameter, you us e only its name. T F

19. T If an array component is of a primitive type, the component can be passed as a p arameter to a method. T F

20. T The base address of an array is the memory location of the first array component . T F

21. T When you pass an array as a parameter, the base address of the actual array is p assed to the formal parameter. T 22. F Two arrays are parallel if they hold the same type of data. T F F

23. T If the value in each index of an array is related to the value in the correspond ing index of a different array, the two arrays are parallel. T F

24. T A method can have both a variable length formal parameter and other formal param eters. T 25. F A method can have at two variable length formal parameters. T F F

26. T If a method has both a variable length formal parameter and other types of forma l parameters, then the variable length formal parameter must be the last formal

parameter of the formal parameter list. T F

27. T Suppose list is a one dimensional array, wherein each component is of the type i nt. Further, suppose that sum is an int variable. The following for loop correct ly find the sume of the elements of list. sum = 0; for (double num : list) sum = sum + num; T 28. T Two-dimensional arrays generally contain data in list form. T F F

29. T The following statements creates alpha to be a two-dimeansional array of 25 rows and 10 columns. int[][] alpha = new int[25][10]; T 30. F Suppose that you have the following declarations. int[] alpha = new int[100]; int[][] beta = new int[25][4]; In this declaration, the array alpha has more components than the array beta. T 31. T In row processing, a two-dimensional array is processed one row at a time. T F F F

32. T In column processing, a two-dimensional array is processed one column at a time. T 33. F Only one-dimensional arrays can be passed as parameters. T 34. T Java stores two-dimensional arrays in a row order form in computer memory. T 35. F F F F

The statement dataType[][][] arrayName; would declare a two-dimensional array. Lesson 10: Practice Test Chapter 10: Applications of Arrays (Searching and Sorting) and Str ings Question 1 A selection sort always starts with the middle element of the list. b. False

Question 2 To design a general-purpose search method, searchList, to search a list, which o f the following must be parameters of the method searchList. (i) The array containing the list. (ii) The length of the list. (iii) The search item. (iv) A boolean variable indicating whether the search is successful. b. (i), (ii), and (iii)

Question 3 In a sequential search, the array must be sorted. b. False

Question 4 To determine whether a given item is in an ordered ist of length 1024, binary se arch makes at most 22 key comparisons. a. True

Question 5 The class Vector is contained in the package java.util. a. True

Question 6 A binary search can be performed on both sorted and unsorted lists. b. False

Question 7 Suppose that you have the following list: int[] list = {2, 5, 8, 11, 14, 17, 20}; Further assume that sequential search on an ordered list is used to determine wh ether 11 is in list. When the loop terminates the value of the index variable lo c is 3. a. True

Question 8 On average, a sequential search on an ordered list only takes one key comparison because you already have an idea where the item will be found. b. False

Question 9 Consider the following list. list = {24, 20, 10, 75, 70, 18, 60, 35} Suppose that list is sorted using the selection sort algorithm as discussed in t he book. What is the resulting list after two passes of the sorting phase, that is, after two iteration of the outer for loop. c. list = {10, 18, 24, 75, 70, 20, 60, 35}

Question 10 Consider the following list. int[] intList = {35, 12, 27, 18, 45, 16, 38}; What is the minimum number of comparisons that have to be made to find 18 using a sequential search on intList? d. 4

Question 11 The method clone in the class Vector returns a copy of the vector. a. True

Question 12 Consider the following list. list = {20, 10, 17, 2, 18, 35, 30, 90, 48, 47}; Suppose that sequential search as discussed in the book is used to determine whe ther 2 is in list. Exactly how many key comparisons are executed by the sequenti al search algorithm. b. 4

Question 13 On average, the number of comparisons made by a sequential search is equal to on e-third the size of the list. b. False

Question 14 Which method would you most likely use to add an element to an end of a vector? b. addElement

Question 15 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; In a sequential search on intList, how many key comparisons would have to be mad e to find the number 5? d. 8

Question 16 Which technique does a binary search use to find an element in a list? a. divide and conquer

Question 17 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; If intList were sorted using selection sort, which two elements would be swapped first? a. 5 and 16

Question 18 Suppose that you have the following list: int[] list = {5, 10, 15, 20, 25, 30, 35, 40, 45}; Further assume that binary search is used to determine whether 20 is in list. Wh en the loop terminates the value of the index variable first is 3. a. True

Question 19 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; Why can t a binary search be used on intList as it appears? b. Because the list is not sorted

Question 20 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; If intList is implemented as a Vector object, what statement would you use to fi nd the number of elements?

a. list1.size()

Question 21 The selection sort algorithm repeatedly moves the smallest element from the unso rted list to the beginning of the unsorted list. a. True

Question 22 Suppose that you have the following list: int[] list = {2, 4, 6, 8, 10, 12, 14, 16}; Further assume that binary search is used to determine whether 15 is in list. Wh en the loop terminates the value of the index variable last is 6. a. True

Question 23 In general, if L is a sorted list of size n, to determine whether an element is in L, the binary search makes at most 2 * log2n + 2 key (item) comparisons. a. True

Question 24 For a list size of 500, on average, the sequential search makes about 250 compar isons. a. True

Question 25 To design a general-purpose sort method, sortList, to sort a list, which of the following must be parameters of the method sortList. (i) The array containing the list. (ii) The length of the list. (iii) A boolean variable indicating whether the sort was successful.

c. (i) and (ii)

Question 26 Consider the following list. list = {5, 11, 25, 28, 45, 78, 100, 120, 125}; Suppose that binary search as discussed in the book is used to determine whether 110 is in the list. What are the values of first and last when the while loop, in the body of the binarySearch method, terminates. c. first = 7, last = 6

Question 27 Suppose that L is a list of length 100. In a successful search, to determine whe ther an item is in L, on average the number of key comparisons executed by the s equential search algorithm, as discussed in this book, is ____. b. 50

Question 28 Consider the following list. intList = {4, 18, 29, 35, 44, 59, 65, 98}; Which element would the search element be compared to first, if a binary search were used on intList? b. 35

Question 29 In which package is the class Vector located? c. java.util

Question 30 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50};

If intList above were implemented as a Vector named v1, how would it be instanti ated? a. v1 = new Vector<int>(10);

Question 31 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; If intList above were sorted, what would be the middle element? c. 24

Question 32 Consider the following list. intList = {4, 18, 29, 35, 44, 59, 65, 98}; If intList were to be searched for the number 44 using a binary search, how many key comparisons would have to be made? c. 5

Question 33 Which of the following is NOT a characteristic of a vector? c. Vectors can contain items of different types.

Question 34 Consider the following list. list = {5, 11, 25, 28, 45, 78, 100, 120, 125}; Suppose that binary search as discussed in the book is used to determine whether 28 is in the list. What are the values of first and last when the while loop, i n the body of the binarySearch method, terminates. a. first = 3, last = 3

Question 35 Which method of the class vector would you use to remove an element at a specifi c location? c. removeElementAt

Question 36 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; On average in a sequential search on intList, how many comparisons would have to be made to find an element in intList? b. 5

Question 37 Only a fixed number of elements can be stored in a vector. b. False

Question 38 One requirement of a linear search is that the item must be in the array. b. False

Question 39 Consider the following list. intList = {4, 18, 29, 35, 44, 59, 65, 98}; If intList were to be searched using a sequential search on an unordered list, h ow many key comparisons would be made to find the number 44? c. 5

Question 40 A binary search starts by comparing the search item to the first item in the lis t.

b. False

Question 41 Suppose that you have the following list: int[] list = {0, 10, 20, 30, 40, 50, 60, 70, 80}; Further assume that binary search is used to determine whether 45 is in list. Wh en the loop terminates the value of the index variable first is 5 and the value of the inde variable last is 4. a. True

Question 42 Vectors can be used to represent lists. 0.0% b. False

Question 43 Suppose that L is a sorted list of length 1000. To determine whether an item is in L, the maximum number of comparisons executed by the binary search algorithm, as discussed in this book, is ____. d. None of these

Question 44 Consider the following list. list = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; Suppose that sequential search on an ordered list as discussed in the book is us ed to determine whether 40 is in list. Exactly how many key comparisons are exec uted by this search algorithm. c. 5

Question 45 In a linear search, you search an array starting from the middle component. b. False

Question 46 Suppose that you have the following list: int[] list = {5, 10, 15, 20, 25, 30, 35, 40, 45}; Further assume that sequential search on an ordered list is used to determine wh ether 28 is in list. When the loop terminates the value of the index variable lo c is 4. b. False

Question 47 Which of the following copies the elements of a vector into an array? a. clone

Question 48 Consider the following list. list = {20, 10, 17, 2, 18, 35, 30, 90, 48, 47}; Suppose that sequential search as discussed in the book is used to determine whe ther 95 is in list. Exactly how many key comparisons are executed by the sequent ial search algorithm. c. 10

Question 49 Consider the following list. list = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; Suppose that sequential search on an ordered list as discussed in the book is us ed to determine whether 55 is in list. Exactly how many key comparisons are exec uted by this search algorithm. d. None of these

Question 50

What is usually returned if the search item is found during a search of a list? a. the location of the element

Question 51 Linear search is another name for sequential search. a. True

Question 52 A list is a set of related values that do not necessarily have the same type. b. False

Question 53 Which of the following returns the number of elements in a Vector? b. Vector.size()

Question 54 Suppose that you have the following list: int[] list = {1, 3, 5, 7, 9, 11, 13, 15, 17}; Further assume that binary search is used to determine whether 8 is in list. Whe n the loop terminates the value of the index variable first is 1. b. False

Question 55 What does the following statement do? Vector<Double> thisVector = new Vector<Double>(); a. It creates an empty vector to create a vector of Double objects.

Question 56

Consider the following list. list = {24, 20, 10, 75, 70, 18, 60, 35} Suppose that list is sorted using the bubble sort algorithm as discussed in the book. What is the resulting list after two passes of the sorting phase, that is, after two iteration of the outer for loop. c. list = {10, 20, 24, 18, 60, 35, 70, 75}

Question 57 What is the maximum number of key comparisons made when searching a list L of le ngth n for an item using a binary search? b. 2 * log2n + 2

Question 58 In the binary search algorithm, two key comparisons are made through every itera tion of the loop. b. False

Question 59 Consider the following list. int[] intList = {16, 30, 24, 7, 25, 62, 45, 5, 65, 50}; In a sequential search on intList, how many key comparisons would have to be mad e to find the number 24? c. 3

Question 60 Consider the following list. int[] intList = {35, 12, 27, 18, 45, 16, 38}; In a sequential search on intList, what is the minimum number of comparisons tha t have to be made to determine if 10 is in intList? c. 7

Question 61 Consider the following list. list = {24, 20, 10, 75, 70, 18, 60, 35} Suppose that list is sorted using the insertion sort algorithm as discussed in t he book. What is the resulting list after two passes of the sorting phase, that is, after three iteration of the for loop. b. list = {10, 20, 24, 75, 70, 18, 60, 35}

Question 62 Consider the following list. list = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; Suppose that sequential search on an ordered list as discussed in the book is us ed to determine whether 120 is in list. Exactly how many key comparisons are exe cuted by this search algorithm. a. 10

Question 63 To search through a list you need to know the length of the list. a. True

Question 64 Consider the following list. list = {5, 11, 25, 28, 45, 78, 100, 120, 125}; Suppose that binary search as discussed in the book is used to determine whether 110 is in the list. Exactly how many key comparisons are executed by binary sea rch. d. None of these

Question 65 Which method would you most likely use to find the element in the last location of the vector?

a. lastElement

Question 66 Consider the following list. intList = {4, 18, 29, 35, 44, 59, 65, 98}; If intList were to be searched using a sequential search on an ordered list, how many key comparisons would be made to find the number 44? d. 6

Question 67 A Vector object can shrink during program execution. a. True

Question 68 Consider the following list. list = {5, 11, 25, 28, 45, 78, 100, 120, 125}; Suppose that binary search as discussed in the book is used to determine whether 28 is in the list. Exactly how many key comparisons are executed by binary sear ch. b. 7

Question 69 A sequential search is faster than a binary search on sorted lists. b. False

Question 70 In a selection sort, a list is sorted by selecting an element and moving it to i ts proper position. a. True

Question 71 Every component of a Vector object is a reference. a. True

Question 72 Key comparisons are also called item comparisons. a. True

Question 73 Which limitation of arrays does a vector overcome? a. Arrays cannot increase in size; vectors can. 1. F A list is a set of related values that do not necessarily have the same type. 2. T To search through a list you need to know the length of the list. 3. T Linear search is another name for sequential search. 4. F In a linear search, you search an array starting from the middle component. 5. F In a sequential search, the array must be sorted. 6.F One requirement of a linear search is that the item must be in the array. 7. T Key comparisons are also called item comparisons.

8. F On average, the number of comparisons made by a sequential search is equal to on e-third the size of the list. 9. T For a list size of 500, on average, the sequential search makes about 250 compar isons. 10. T In a selection sort, a list is sorted by selecting an element and moving it to i ts proper position. 11. F A selection sort always starts with the middle element of the list. 12. T The selection sort algorithm repeatedly moves the smallest element from the unso rted list to the beginning of the unsorted list. 13. F Suppose that you have the following list: int[] list = {5, 10, 15, 20, 25, 30, 35, 40, 45}; Further assume that sequential search on an ordered list is used to determine wh ether 28 is in list. When the loop terminates the value of the index variable lo c is 4. 14. T Suppose that you have the following list: int[] list = {2, 5, 8, 11, 14, 17, 20}; Further assume that sequential search on an ordered list is used to determine wh ether 11 is in list. When the loop terminates the value of the index variable lo c is 3. 15. F On average, a sequential search on an ordered list only takes one key comparison because you already have an idea where the item will be found. 16.F

A binary search can be performed on both sorted and unsorted lists. 17. F In the binary search algorithm, two key comparisons are made through every itera tion of the loop. 18. F A sequential search is faster than a binary search on sorted lists. 19. F A binary search starts by comparing the search item to the first item in the lis t. 20. T Suppose that you have the following list: int[] list = {2, 4, 6, 8, 10, 12, 14, 16}; Further assume that binary search is used to determine whether 15 is in list. Wh en the loop terminates the value of the index variable last is 6. 21.F Suppose that you have the following list: int[] list = {1, 3, 5, 7, 9, 11, 13, 15, 17}; Further assume that binary search is used to determine whether 8 is in list. Whe n the loop terminates the value of the index variable first is 1. 22. T In general, if L is a sorted list of size n, to determine whether an element is in L, the binary search makes at most 2 * log2n + 2 key (item) comparisons. 23. T Suppose that you have the following list: int[] list = {5, 10, 15, 20, 25, 30, 35, 40, 45}; Further assume that binary search is used to determine whether 20 is in list. Wh en the loop terminates the value of the index variable first is 3. 24. T Suppose that you have the following list:

int[] list = {0, 10, 20, 30, 40, 50, 60, 70, 80}; Further assume that binary search is used to determine whether 45 is in list. Wh en the loop terminates the value of the index variable first is 5 and the value of the inde variable last is 4. 25. T To determine whether a given item is in an ordered ist of length 1024, binary se arch makes at most 22 key comparisons. 26. F Only a fixed number of elements can be stored in a vector. 27. T A Vector object can shrink during program execution. 28. T Vectors can be used to represent lists. 29. T The method clone in the class Vector returns a copy of the vector. 30. T Every component of a Vector object is a reference. 31. T The class Vector is contained in the package java.util.

Lesson 11: Practice Test Chapter 11: Inheritance and Polymorphism

Question 1 To determine whether a reference variable that points to an object is of a parti cular class type, Java provides the operator instanceof. 100.0% a. True

Question 2 If there are three classes: Shape, Circle, and Square, what is the most likely r elationship between them? 100.0% . b. Shape is a superclass, and Circle and Square are subclasses of Shape

Question 3 Inheritance implies an 100.0% a. True

is-a

relationship.

Question 4 Suppose that the class Mystery is derived from the class Secret. Consider the fo llowing statements: Secret secRef; Mystery mysRef = new Mystery(); secRef = mysRef; The value of the expression secRef instanceof Secret is true. 100.0% b. False

Question 5 In single inheritance, the subclass is derived from a single superclass. 100.0% a. True

Question 6 Suppose that the class Mystery is derived from the class Secret. Consider the fo llowing statements: Secret secRef = new Secret(); Mystery mysRef = new Mystery(); Which of the following statements is legal in Java? (i) secRef = mysRef; (ii) mysRef = secRef; 100.0% a. Only (i)

Question 7

Based on the diagrams above, which of the following is the superclass? 100.0% a. Rectangle

Question 8 Any new class you create from an existing class is called a(n) ____. 100.0% c. derived class

Question 9 Which of the following statements about the reference super is true? 100.0% c. It must be the first statement of the constructor.

Question 10 An abstract class ____. 100.0% c. cannot be instantiated

Question 11 Inheritance is an example of what type of relationship? 100.0% a. is-a

Question 12 Consider the following class definitions. public class BClass { private int x;

public void set(int a) { x = a; } public void print() { System.out.print(x); } } public class DClass extends BClass { private int y; public void set(int a, int b) { //Postcondition: x = a; y = b; } public void print(){ } }

Which of the following correctly overrides the method print of DClass? (i) public void print() { System.out.print(x + " " + y); } (ii) public void print() { super.print(); System.out.print(" " + y); } 100.0% b. Only (ii)

Question 13 The private members of a superclass can be accessed by a subclass. 100.0% b. False

Question 14 An interface is a class that contains only abstract methods and/or named constan ts.

100.0%

a. True

Question 15 A subclass can directly access ____. 100.0% a. public members of a superclass

Question 16 In Java, you can automatically make a reference variable of a subclass type poin t to an object of its superclass. 100.0% b. False

Question 17 An abstract method is a method that has only the heading with no body. 100.0% a. True

Question 18 Suppose that the class Mystery is derived from the class Secret. Consider the fo llowing statements: Secret mySecret = new Secret(); Secret secRef; Mystery myMystery = new Mystery(); Mystery mysRef; secRef = myMystery; Which of the following statements is legal in Java? (i) mysRef = (Mystery) mySecret; (ii) mysRef = (Mystery) secRef; 100.0% b. Only (ii)

Question 19 The subclass can override public methods of a superclass.

100.0%

a. True

Question 20 In dynamic binding the method that gets executed is determined at the compile ti me not at execution time. On the other hand, in run-time binding the method that gets executed is determined at execution time not at compile time. 100.0% b. False

Question 21 You can instantiate an object of a subclass of an abstract class, but only if th e subclass gives the definitions of all the abstract methods of the superclass. 100.0% a. True

Question 22 A polymorphic reference variable can refer to either an object of their own clas s or an object of the subclasses inherited from its class. 100.0% a. True

Question 23 Consider the following class definitions. public class BClass { private int x; public void set(int a) { x = a; } public void print(){ } } public class DClass extends BClass { private int y; public void set(int a, int b) { //Postcondition: x = a; y = b; } public void print(){ } }

Which of the following is the correct definition of the method set of the class Dclass? (i) public void set(int a, int b) { super.set(a); y = b; } (ii) public void set(int a, int b) { x = a; y = b; } 100.0% a. Only (i)

Question 24 A subclass can directly access protected members of a superclass. 100.0% a. True

Question 25 An abstract method ____. 100.0% c. has no body

Question 26 In Java, stream classes are implemented using the inheritance mechanism. 100.0% a. True

Question 27 If a class is declared final, then no other class can be derived from this class . 100.0% a. True

Question 28 Composition is a(n) ____ relationship. 100.0% b. has-a

Question 29 In multiple inheritance, the subclass is derived from more than one superclass. 100.0% a. True

Question 30 You must always use the reserved word super to use a method from the superclass in the subclass. 100.0% b. False

Question 31 Suppose a class Car and its subclass Honda both have a method called speed as pa rt of the class definition. rentalH refers to an object of the type Honda and th e following statements are found in the code: rentalH.cost(); super.speed();

What does the second statement in the description above do? 100.0% b. The speed method in Car will be called.

Question 32 Java uses late binding for methods that are private but not for methods that are marked final. 100.0% b. False

Question 33

How many members are in the class Rectangle? 100.0% b. 10

Question 34

Based on the diagram above, the method setDimension in the class Box ____ the me thod setDimension in the class Rectangle. 100.0% a. overloads

Question 35 If class Dog has a subclass Retriever, which of the following is true? 100.0% b. Because of single inheritance, Retriever can extend no other class e xcept Dog.

Question 36 Using the mechanism of inheritance, every public member of the class Object can be overridden and/or invoked by every object of any class type. 100.0% a. True

Question 37 The class Object is directly or indirectly the superclass of every class in Java . 100.0% a. True

Question 38

Based on the diagram above, the method area in the class Box ____ the method are a in the class Rectangle. 100.0% b. overrides

Question 39 The superclass inherits all its properties from the subclass. 100.0% b. False

Question 40 A subclass cannot directly access public members of a superclass. 100.0% b. False

Question 41 If a class implements an interface, it must ____. 100.0% a. provide definitions for each of the methods of the interface

Question 42 Java supports both single and multiple inheritance. 100.0% b. False

Question 43

Which operator is used to determine if an object is of a particular class type? 100.0% c. The instanceof operator

Question 44 Redefining a method of a superclass is also known as overloading a method. 100.0% b. False

Question 45 Suppose that the class Mystery is derived from the class Secret. The following s tatements are legal in Java. Secret secRef; Mystery mysRef = new Mystery(); secRef = mysRef; 100.0% a. True

Question 46 In Java, polymorphism is implemented using late binding. 100.0% a. True

Question 47 An abstract class can contain ____. 100.0% c. abstract and non-abstract methods

Question 48 Composition is a 100.0% a. True

has-a

relation.

Question 49 An abstract class can only contain abstract methods.

100.0%

b. False

Question 50 A subclass inherits all its data members from the superclass; it has none of its own. 100.0% b. False

Question 51 Consider the following class definitions. public class BClass { private int x; private double y; public void print() { } } public class DClass extends BClass { private int a; private int b; public void print() { } } Suppose that you have the following statement. DClass dObject = new DClass(); How many instance variables DObject has? 100.0% c. 4

Question 52 How many interfaces can a class implement? 100.0% d. There is no limit to the number of interfaces that can be implemente d by a single class.

Question 53

Interfaces are defined using the reserved word interface and the reserved word c lass. 100.0% b. False

Question 54 The classes Reader and Writer are derived from the class ____. 100.0% d. Object

Question 55 In Java, a reference variable of a superclass type cannot point to an object of its subclass. 100.0% b. False

Question 56 What type of inheritance does Java support? 100.0% a. single inheritance

Question 57 What is the correct syntax for defining a new class Parakeet based on the superc lass Bird? 100.0% d. class Parakeet extends Bird{ }

Question 58 Suppose a class Car and its subclass Honda both have a method called speed as pa rt of the class definition. rentalH refers to an object of the type Honda and th e following statements are found in the code: rentalH.cost(); super.speed();

What will the first statement in the situation described above do? 100.0% a. The cost method in Honda will be called.

Question 59 The method toString() is a public member of the class ____. 100.0% a. Object

Question 60

Based on the diagram above, which of the following members will Box NOT have dir ect access to? 100.0% c. length

Question 61 To override a public method of a superclass in a subclass, the corresponding met hod in the subclass must have the same name but a different number of parameters . 100.0% b. False is-a relationship. T F 2. The superclass inherits all its properties from the subclass. T F 3. The private members of a superclass can be accessed by a subclass. T F 4. A subclass cannot directly access public members of a superclass. T T 5. The subclass can override public methods of a superclass. T F F F F F

T 1. Inheritance implies an

T 6. In single inheritance, the subclass is derived from a single superclass. T F

T 7. In multiple inheritance, the subclass is derived from more than one superclass. T F 8. Java supports both single and multiple inheritance. T F F

F 9. A subclass inherits all its data members from the superclass; it has none of its own. T F

F 10. To override a public method of a superclass in a subclass, the corresponding met hod in the subclass must have the same name but a different number of parameters . T F 11. Redefining a method of a superclass is also known as overloading a method. T F F

F 12. You must always use the reserved word super to use a method from the superclass in the subclass. T T 13. A subclass can directly access protected members of a superclass. T F F

T 14. The class Object is directly or indirectly the superclass of every class in Java . T F

T 15. Using the mechanism of inheritance, every public member of the class Object can be overridden and/or invoked by every object of any class type. T T 16. In Java, stream classes are implemented using the inheritance mechanism. T F F

F 17. In Java, a reference variable of a superclass type cannot point to an object of its subclass. T F

F 18. In dynamic binding the method that gets executed is determined at the compile ti me not at execution time. On the other hand, in run-time binding the method that gets executed is determined at execution time not at compile time. T T 19. In Java, polymorphism is implemented using late binding. T F F

T 20. A polymorphic reference variable can refer to either an object of their own clas s or an object of the subclasses inherited from its class. T F

T 21. Suppose that the class Mystery is derived from the class Secret. The following s tatements are legal in Java. Secret secRef; Mystery mysRef = new Mystery(); secRef = mysRef; T F

F 22. Java uses late binding for methods that are private but not for methods that are marked final. T F

T 23. If a class is declared final, then no other class can be derived from this class . T F

F 24. In Java, you can automatically make a reference variable of a subclass type poin t to an object of its superclass. T F

T 25. To determine whether a reference variable that points to an object is of a parti cular class type, Java provides the operator instanceof. T F 26. F

Suppose that the class Mystery is derived from the class Secret. Consider the fo llowing statements: Secret secRef; Mystery mysRef = new Mystery(); secRef = mysRef; The value of the expression secRef instanceof Secret is true. T T 27. An abstract method is a method that has only the heading with no body. T F 28. An abstract class can only contain abstract methods. T F F F

T 29. You can instantiate an object of a subclass of an abstract class, but only if th e subclass gives the definitions of all the abstract methods of the superclass. T F

T 30. An interface is a class that contains only abstract methods and/or named constan ts. T F

F 31. Interfaces are defined using the reserved word interface and the reserved word c lass. T T 32. Composition is a has-a relation. F

Lesson 12: Exceptions with J Applet ft files http://cyber.gwc.cccd.edu/faculty/hcohen/Java5Ch12MCAnswers.txt http://titanpad.com/indiosbravos Which two can be used to create a new Thread? FUCK U NIGGAS HEHE

Practice Test Chapter 12: Handling Exceptions and Events Question 1 The class Exception and its subclasses are designed to catch exceptions that sho uld be caught and processed during program execution.

a. True

Question 2 If you have created an exception class, you can define other exception classes e xtending the definition of the exception class you created. a. True

Question 3 Every program with a try block must end with a finally block. b. False

Question 4 What happens in a method if there is an exception thrown in a try block but ther e is no catch block following the try block? d. The program throws an exception and proceeds to execute the finally block.

Question 5 Making a reference to an object that has not yet been instantiated would throw a n exception from the NullPointerException class. a. True

Question 6 If in the heading of a catch block you can declare an exception using the class Exception, then that catch block can catch all types of exceptions because the c lass Exception is the superclass of all exception classes. a. True

Question 7 int number; boolean done = false; do { try { System.out.print("Enter an integer: "); number = console.nextInt(); System.out.println(); done = true; System.out.println("number = " + number); }

catch (InputMismatchException imeRef) { str = console.next(); System.out.println("Exception " + imeRef.toString() + " " + str); } } while (!done);

What is most likely the type of exception in the code above? b. InputMismatchException

Question 8 The class Throwable is derived from the class Exception. b. False

Question 9 For the interface WindowListener that contains more than one method, Java provid es the class ____. b. WindowAdapter

Question 10 The class RuntimeException is the superclass of which of the following classes? a. NullPointerException

Question 11 An unchecked exception is any exception that causes a program to terminate. b. False

Question 12 For interfaces such as WindowListener that contain more than one method, Java pr ovides the class WindowAdapter. a. True

Question 13 How many finally blocks can there be in a try/catch structure? c. There can be 0 or 1 following the last catch block.

Question 14 Which of the following statements is NOT true about creating your own exceptions ? b. The exception class that you define extends either the class Throwable or one of its subclasses.

Question 15 The order in which catch blocks are placed in a program has no impact on which c atch block is executed. b. False

Question 16 How many constructors does the class Exception have? c. 2

Question 17 During program execution, if division by zero occurs with integer values and is not addressed by the program, then the program terminates with an error message indicating an attempt to divide by zero. a. True

Question 18 Which class of exceptions is NOT checked? a. True

Question 19 To handle window events you first create a class that implements the interface W indowListener and then you create and register objects of that class. a. True

Question 20 If there is a finally block after the last catch block, the finally block always executes. a. True

Question 21 If a negative value is used for an array index, ____. d. an IndexOutOfBoundsException is thrown

Question 22 import java.util.*; public class ExceptionExample1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int dividend, divisor, quotient; try { System.out.print("Enter dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Enter divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("quotient = " + quotient); } catch (ArithmeticException aeRef) { System.out.println("Exception" + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Exception " + imeRef.toString()); } catch( IOException ioeRef) { System.out.println("Exception " + ioeRef.toString()); } } }

Which of the following will cause the first exception to occur in the code above

? a. if the divisor is zero

Question 23 What can a method do with a checked exception? c. Throw the exception to the method that called this method, or handle the e xception in a catch block.

Question 24 Which of the following is an exception thrown by the methods of the class String ? a. NullPointerException

Question 25 Which of the following statements is true? c. The class Throwable, which is derived from the class Object, is the superc lass of the class Exception.

Question 26 The class Exception contains two constructors. a. True

Question 27 import java.util.*; public class ExceptionExample1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int dividend, divisor, quotient; try { System.out.print("Enter dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Enter divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("quotient = " + quotient);

} catch (ArithmeticException aeRef) { System.out.println("Exception" + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Exception " + imeRef.toString()); } catch( IOException ioeRef) { System.out.println("Exception " + ioeRef.toString()); } } }

Which of the following inputs would be caught by the second catch block in the p rogram above? c. h3

Question 28 A message string is returned by which method of an Exception object? b. getMessage()

Question 29 The class RuntimeException is part of the package java.io. b. False

Question 30 The class Object is derived from the class Throwable. b. False

Question 31 The methods getMessage and printStackTrace are private methods of the class Thro wable. b. False

Question 32 A checked exception is any exception checked for by the programmer. b. False

Question 33 When is a finally{} block executed? d. Always after the execution of a try block, regardless of whether or not an exception is thrown

Question 34 When an exception occurs, an object of a specific exception class is created by the system. a. True

Question 35 Which of the following is NOT a method of the class Throwable? b. throwMessage

Question 36 The StringIndexOutOfBoundsException could be thrown by the method parseInt of th e class Integer. b. False

Question 37 When an exception occurs in a method, you can use the method printStackTrace to determine the order in which the methods were called and where the exception was handled. a. True

Question 38 Which of the following is NOT a typical action of the catch block? d. Throwing the exception

Question 39 int number; boolean done = false; do { try { System.out.print("Enter an integer: "); number = console.nextInt(); System.out.println(); done = true; System.out.println("number = " + number); } catch (InputMismatchException imeRef) { str = console.next(); System.out.println("Exception " + imeRef.toString() + " " + str); } } while (!done);

How many times will the code in the try block above execute? b. Until the user inputs a valid integer

Question 40 import java.util.*; public class ExceptionExample1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int dividend, divisor, quotient; try { System.out.print("Enter dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Enter divisor: "); divisor = console.nextInt(); System.out.println();

quotient = dividend / divisor; System.out.println("quotient = " + quotient); } catch (ArithmeticException aeRef) { System.out.println("Exception" + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Exception " + imeRef.toString()); } catch( IOException ioeRef) { System.out.println("Exception " + ioeRef.toString()); } } }

Which method throws the second exception in the code above? a. nextInt

Question 41 Statements that might generate an exception are placed in a catch block. b. False

Question 42 Which of the following methods prints a list of the methods that were called bef ore the exception was thrown? c. printStackTrace()

Question 43 NoSuchFileException is a method of the class Exception. b. False

Question 44 int number; boolean done = false; do {

try { System.out.print("Enter an integer: "); number = console.nextInt(); System.out.println(); done = true; System.out.println("number = " + number); } catch (InputMismatchException imeRef) { str = console.next(); System.out.println("Exception " + imeRef.toString() + " " + str); } } while (!done);

Which exception-handling technique is the code above using? b. Fix the error and continue

Question 45 Which class of exceptions is NOT checked? c. RuntimeException

Question 46 The try block contains statements that should be executed regardless of whether or not an exception occurs. b. False

Question 47 If you have a reference to an exception object, you can use the reference to thr ow the exception. a. True

Question 48 An exception that can be analyzed by the compiler is a(n) ____. b. checked exception True or False Questions: JApplet.

. The class Container is the superclass of all the classes designed to provide a G UI. -True You can create an applet by extending the class JFrame. -False Like Java application programs, Java applets do not have the method main. -False (Eto ung sagot sa website pero alam ko true to kasi may main ang mga Japp let) gThe class Graphics is an abstract class. -True A Java applet is the same as a Java GUI application program. -False The class JComponent is part of the package javax.swing. -True Which of the following is NOT a typical action of the catch block? -False Applets do not have titles. -True Unlike application programs, when you compile a Java applet no .class file is pr oduced. -False You can terminate an applet by closing the HTML document in which the applet is embedded. -True You must import the package javax.swing in order to use the methods in the class Font. -False You can use the methods Background and Foreground to set the background and fore ground color of a component. -False The R in RGB stands for Right. -False You can create instances of Color by mixing red, green, and blue hues in various proportions. -True The class Graphics provides methods for drawing items such as lines, ovals, and rectangles on the screen. -True

An applet invokes the methods start, init, stop, paint, and destroy in sequence. -False Applets use the init method in place of constructors to initialize various GUI c omponents and data members. -True It is impossible to convert a GUI application into an applet. -False JTextAreas can be used to display multiple lines of text. -True JCheckBox is a subclass of the abstract class ToggleButton. -True Clicking on a JCheckBox generates an item event. -True Item events are handled by the interface ItemListener which contains only the ab stract method itemStateChanged. -True JRadioButtons are useful when you want to give the user the ability to select mo re than one of the presented options. -False The layout manager FlowLayout places components in the container from left to ri ght until no more items can be placed. -True What will be the output of the program? public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } } A.Finally What will be the output of the program? try { int x = 0; int y = 5 / x; } catch (Exception e)

{ System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished"); C.Compilation fails. T 1. During program execution, if division by zero occurs with integer values an d is not addressed by the program, then the program terminates with an error mes sage indicating an attempt to divide by zero. T 2. F Statements that might generate an exception are placed in a catch block. T F F

3. F The try block contains statements that should be executed regardless of whether or not an exception occurs. T 4. F Every program with a try block must end with a finally block. T F F

5. T If there is a finally block after the last catch block, the finally block always executes. T F

6. T If an exception occurs in a try block and that exception is caught by a catch bl ock, then the remaining catch blocks associated with that try block are ignored. T F

7. T If in the heading of a catch block you can declare an exception using the class Exception, then that catch block can catch all types of exceptions because the c lass Exception is the superclass of all exception classes. T F

8. F The order in which catch blocks are placed in a program has no impact on which c atch block is executed. T 9. F The class Object is derived from the class Throwable. F

T 10. F The class Throwable is derived from the class Exception. T

11. F The methods getMessage and printStackTrace are private methods of the class Thro wable. T F

12. T The class Exception and its subclasses are designed to catch exceptions that sho uld be caught and processed during program execution. T 13. F The class RuntimeException is part of the package java.io. T 14. F NoSuchFileException is a method of the class Exception. T 15. T The class Exception contains two constructors. T F F F F

16. T Making a reference to an object that has not yet been instantiated would throw a n exception from the NullPointerException class. T F

17. F The StringIndexOutOfBoundsException could be thrown by the method parseInt of th e class Integer. T 18. F A checked exception is any exception checked for by the programmer. T 19. F An unchecked exception is any exception that causes a program to terminate. T F F F

20. T If you have a reference to an exception object, you can use the reference to thr ow the exception.

21. T When an exception occurs, an object of a specific exception class is created by the system. T F

22. T When an exception occurs in a method, you can use the method printStackTrace to determine the order in which the methods were called and where the exception was handled. T F

23. T If you have created an exception class, you can define other exception classes e xtending the definition of the exception class you created. T F

24. T To handle window events you first create a class that implements the interface W indowListener and then you create and register objects of that class. T F

25. T For interfaces such as WindowListener that contain more than one method, Java pr ovides the class WindowAdapter.

Java Threads. Multitasking: refers to a computer's ability to perform multiple jobs concurrently more than one program are running concurrently, e.g., UNIX Multithreading: A thread is a single sequence of execution within a program refers to multiple threads of control within a single program each program can run multiple threads of control within it, e.g., Web Browser There are two ways to create our own Thread object Subclassing the Thread class and instantiating a new object of that class Implementing the Runnable interface In both cases the run() method should be implemented void start() Creates a new thread and makes This method can be called only void run() The new thread begins its life void stop() (deprecated) The thread is being terminated void yield() Causes the currently executing threads to execute Allow only threads of the same void sleep(int m) or sleep(int it runnable once inside this method

thread object to temporarily pause and allow other priority to run m, int n)

The thread sleeps for m milliseconds, plus n nanoseconds When running the Runnable object, a Thread object is created from the Runnable ob ject The Thread object s run() method calls the Runnable object s run() method Allows threads to run inside any object, regardless of inheritance java.lang.Thread public static void yield(); Method of java.lang.Thread Thread gives up CPU for other threads ready to run

1. The word new is an operator. ANSWER: T 2. Given String name; the value of name is directly stored in its memory space. ANSWER: F 3. The + operator is used to instantiate a class. ANSWER: F 4. The new operator can be used to create a class object. ANSWER: T 5. Java provides automatic garbage collection. ANSWER: T 6. Primitive type variables directly store data into their memory space. ANSWER: T 7. The class Math is contained in the java.text package.

ANSWER: F 8. Contents of the java.lang package do not need to be imported into a program in o rder to be used. ANSWER: T 9. In order to use a predefined method, you simply need to know the name of the met hod. ANSWER: F The . (dot) operator is also called the member access operator. ANSWER: T In the class String, the substring method extracts a string from within another string. ANSWER: T indexOf(String str) is a method in the class String. ANSWER: T The method length in the class String returns the number of characters in the st ring not including whitespace characters. ANSWER: F String variables are primitive variable types. ANSWER: F The method printf is used only to format the output of decimal numbers. ANSWER: F The default output of decimal numbers of the type float is 9 decimal places.

ANSWER: F Suppose x = 15.674. The output of the statement System.out.printf("%.2f", x); is 15.67. ANSWER: T Suppose z = 9525.9864. The output of the statement System.out.printf("%.2f", z); is 9525.98. ANSWER: F A string consisting of only an integer or a decimal number is called a numeric s tring. ANSWER: T The value of the expression Integer.parseInt("-823") is -"823" ANSWER: F The value of the expression Float.parseFloat("-542.97") is -542.97. ANSWER: T The method, parseInt is used to convert a numeric integer string into a value of the type int. ANSWER: T The classes Integer, Float, and Double are called wrapper classes. ANSWER: T The class JOptionPane is part of the package java.io. ANSWER: F

The class JOptionPane allows a programmer to use graphical interface components to obtain input from a user. ANSWER: T The statement System.exit(0); is found at the end of every working Java program. ANSWER: F Given a decimal number, the method format of the class String returns the string containing the digits of the formatted number. ANSWER: T When writing output to a file, if the file is not closed at the end of the progr am, you may not be able to view your output properly. ANSWER: T If the output file does not exist you will get a FileNotFoundException. ANSWER: F If the specified output file does not exist, the computer prepares an empty file for output. ANSWER: T

FILES creating a file: private Formatter x; x= new Formatter ("chupuls.txt"); //Formatter ay ung ginagamit para gumawa ng fi le writing text in files: x.format(%s%s%s, "chupuls", "ka", "carlos"); x.close() //para di na malagyan ng iba pang text. bsta lagi to ginagamit. opening and reading a file dito, gagawa ka ng scanner tapos ipapasok mo ung file mo private Scanner x; x = new Scanner(new File("chupuls.txt"));

tapos ireread mo ung file public void readFile(x.hasNext)) { String a = x.next(); } tapos print mo. tapos sa main kailangan may close parin na method. LESSON 14: Recursion 1. T The process of solving a problem by reducing it to smaller versions of itself is called recursion. 2. F In the base case, the solution is obtained through a call to a smaller version o f the original method. 3. F Every recursive definition must have zero or more base cases. 4. T A general solution to a recursive algorithm must eventually reduce to a base cas e. 5. F The base case starts the recursion. 6. F The general case is the case for which the solution is obtained directly. 7. T The following is a valid recursive definition to determine the factorial of a no n-negative integer. 0! = 1 1! = 1 n! = n * (n 8. T Consider the following recursive definition. F(1) = 3 F(n) = F(n 1) + 1 if n > 1,

1)! if n > 0.

where n is a positive integer. The value of F(3) = 5. 9. F The following is an example of a recursive method. public static int recFunc(int x) { return (nextNum(nextNum(x))); } where nextNum is method such that nextNum(x) = x + 1. 10. T The following is an example of a void recursive method. public static void print(int x) { if (x > 0) { System.out.print(x + " "); print(x 1); } } 11. T The body of a recursive method contains a statement that causes the same method to execute before completing the current call. 12. F A method that calls itself is an iterative method. 13. T You can think of a recursive method as having unlimited copies of itself. 14. T Every recursive call has its own code. 15. F After completing a particular recursive call the program terminates. 16. F A method is called directly recursive if it calls another recursive method.

17. T A method that calls another method and eventually results in the original method call is called indirectly recursive. 18. T Tracing through indirect recursion is generally more tedious than tracing throug h direct recursion. 19. T If every recursive call results in another recursive call, then the recursive me thod (algorithm) is said to have infinite recursion. 20. F In reality, if you execute an infinite recursive method on a computer it will ex ecute forever. 21. F A recursive method in which the first statement executed is a recursive call is called a tail recursive method. 22. T The recursive implementation of the factorial method is an example of a tail rec ursive method. 23. T The base case is never reached or does not exist in infinite recursion. 24. T To design a recursive method you must determine the limiting conditions. 25. T The limiting condition for a list might be the number of elements in the list. 26. T There are two base cases in the recursive implementation of generating a Fibonac ci sequence. 27. F Recursive algorithms are implemented using while loops.

28. F A recursive solution is always a better alternative to an iterative solution. 29. F The overhead associated with iterative methods is greater in terms of both memor y space and computer time, when compared to the overhead associated with executi ng recursive methods.

S-ar putea să vă placă și