0% found this document useful (0 votes)
298 views283 pages

Guia Certificacao Java Meu

This document contains 14 multiple choice questions about Java language fundamentals including escape sequences, variable declaration and initialization, array creation, primitive data types and their ranges, and default values. It provides the questions, possible answers, and explanations for each question covering topics like compile-time errors, main method signatures, and primitive conversions and representations.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
298 views283 pages

Guia Certificacao Java Meu

This document contains 14 multiple choice questions about Java language fundamentals including escape sequences, variable declaration and initialization, array creation, primitive data types and their ranges, and default values. It provides the questions, possible answers, and explanations for each question covering topics like compile-time errors, main method signatures, and primitive conversions and representations.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 283

Language Fundamentals Question 1

class MCZ11 { public static void main (String[] args) { char a = '\c'; // 1 char b = '\r'; // 2 char c = '\"'; // 3 char d = '\b'; // 4 char e = '\''; // 5 }}

A compile-time error is generated at which line?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resposta:

Os scapes so: '\b' (backspace), '\f' (formfeed), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\\' (backslash), '\"' (double quote), '\'' (single quote). 1a 1 Yes, you must memorize the escape sequences! Just remember "big farms need red tractors".

Question 2
class GFM11{ public static void main (String[] args) { int x,y,z; System.out.println(x+y+z); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints nothing. Prints an undefined value. Prints: null Prints: 0 Run-time error Compile-time error None of the above

Resposta:

2f

Compiletime error

Variables declared inside of a block or method are called local variables; they are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.

Question 3
class MCZ27 { public static void main (String[] args) { char a = '\f'; // 1 char b = '\n'; // 2 char c = '\r'; // 3 char d = '\l'; // 4 char e = '\\'; // 5 }}

A compile-time error is generated at which line?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resposta:

The escape sequences are as follows: '\b' (backspace), '\f' (formfeed), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\\' (backslash), '\"' (double 3d 4 quote), '\'' (single quote). Yes, you must memorize the escape sequences! Just remember "big farms need red tractors".

Question 4
class GRC4 {public static void main(String[] args) {}} // 1 class GRC5 {public static void main(String []args) {}} // 2 class GRC6 {public static void main(String args[]) {}} // 3

What is the result of attempting to compile and run the above programs?
a. Compile-time error at line 1. b. Compile-time error at line 2. c. Compile-time error at line 3.

d. e. f. g.

An attempt to run GRC4 from the command line fails. An attempt to run GRC5 from the command line fails. An attempt to run GRC6 from the command line fails. None of the above

Resposta:

Section 12.1.4 of the Java Language Specification requires that the main method must accept a single argument that is an array of None of components of type String. In each of the three class declarations, the 4 g the single argument is indeed an array of components of type String. above Please note that the square brackets within an array declaration may appear as part of the type or part of the declarator (i.e. array name).

Question 5
class MCZ28 { public static void main (String[] args) { char a = '\b'; // 1 char b = '\d'; // 2 char c = '\f'; // 3 char d = '\t'; // 4 char e = '\"'; // 5 }}

A compile-time error is generated at which line?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resposta:

The escape sequences are as follows: '\b' (backspace), '\f' (formfeed), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\\' (backslash), '\"' (double 5b 2 quote), '\'' (single quote). Yes, you must memorize the escape sequences! Just remember "big farms need red tractors".

Question 6
class JJF1 { public static void main (String args[]) { System.out.print(Byte.MIN_VALUE+","); System.out.print(Byte.MAX_VALUE);

}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 0,255 Prints: 0,256 Prints: -127,128 Prints: -128,127 Compile-time error Run-time error None of the above

Resposta:

6d

Prints: 128,127

A byte is an 8 bit signed value; so the minimum byte value is (27) and the maximum value is (27 - 1).

Question 7
class GFC100 { public static void main(String[] args) { final short s1 = 1; // 1 final char c1 = 1; // 2 byte b1 = s1; // 3 byte b2 = c1; // 4 byte b3 = 1; // 5 byte b4 = 1L; // 6 byte b5 = 1.0; // 7 byte b6 = 1.0d; // 8 }}

Compile-time errors are generated at which lines?


a. b. c. d. e. f. g. h. 1 2 3 4 5 6 7 8

Resposta:

The compiler will implicitly do a narrowing conversion for an assignment f statement if the right hand operand is a compile time constant of 7 g 6 7 8 type byte, short, char, or int and the value falls within the range of h the variable on the left and if the variable is of type byte, short,

or char.

Question 8
class MWC101 { public static void main(String[] args) { int[] a1 = new int[]; // 1 int a2[] = new int[5]; // 2 int[] a3 = new int[]{1,2}; // 3 int []a4 = {1,2}; // 4 int[] a5 = new int[5]{1,2,3,4,5}; // 5 }}

Compile-time errors are generated at which lines?


a. b. c. d. e. 1 2 3 4 5

Resposta:

An array creation expression must have either a dimension expression or an initializer. If both are present, then a compile-time error is generated. Similarly, if neither is present, then a compile-time error is generated. If only the dimension expression is present, then an array with the specified dimension is created with all elements set to the default values. If only the initializer is present, then an array will be created that has the required a 8 1 5 dimensions to accommodate the values specified in the initializer. Java e avoids the possibility of an incompatible dimension expression and initializer by not allowing both to appear in the same array creation expression. A compile-time error is generated by the array creation expression for a1, because it needs either a dimension expression or an initializer. A compiletime error is generated at 5, because either the dimension expression or the initializer must be removed.

Question 9
class GRC1 {public static void main(String[] args) {}} // 1 class GRC2 {protected static void main(String[] args) {}} // 2 class GRC3 {private static void main(String[] args) {}} // 3

What is the result of attempting to compile each of the three class declarations and invoke each main method from the command line?
a. Compile-time error at line 1.

b. c. d. e. f.

Compile-time error at line 2. Compile-time error at line 3. An attempt to run GRC1 from the command line fails. An attempt to run GRC2 from the command line fails. An attempt to run GRC3 from the command line fails.

Resposta:

An attempt to runGRC2 from the e command line fails. An 9 f attempt to runGRC3 from the command line fails.

Section 12.1.4 of the JLS requires the main method to be declared public. The main methods of GRC2 and GRC3 are not declared public and can not be invoked from the command line using a JVM that is compliant with section 12.1.4. Not every JVM enforces the rule. Even so, for the purposes of the SCJP exam, the main method should be declared as required by the JLS.

Question 10
class JJF2 { public static void main (String args[]) { System.out.print(Short.MIN_VALUE+","); System.out.print(Short.MAX_VALUE); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: -32767,32768 Prints: -32768,32767 Prints: 0,65535 Prints: 0,65536 Compile-time error Run-time error None of the above

Resposta:

Prints: 10 b 32768,32767

A short is a 16 bit signed value; so the minimum short value is -(215) and the maximum value is (215 1).

Question 11
class GFC101 { public static void main(String[] args) { byte b1 = -128; // 1

byte b2 = 128; short s1 = -32769; short s2 = 32767; char c1 = 0; char c2 = 65536; }}

// // // // //

2 3 4 5 6

Compile-time errors are generated at which lines?


a. b. c. d. e. f. 1 2 3 4 5 6

Resposta:

b 11 c f

2 3 6

The maximum value of type byte is 127. The minimum value of type short is -32768. The maximum value of type char is 65535.

Question 12
class MWC102 { public static void main (String[] args) { byte[] a = new byte[1]; long[] b = new long[1]; float[] c = new float[1]; Object[] d = new Object[1]; System.out.print(a[0]+","+b[0]+","+c[0]+","+d[0]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 0,0,0,null Prints: 0,0,0.0,null Compile-time error Run-time error None of the above

Resposta:

12 b

Prints: 0,0,0.0,null

Each array contains the default value for its type. The default value of a primitive byte or a primitive long is printed as 0. The default value of a float primitive is printed as 0.0. The default value of an Object is null and is printed as null.

Question 13

class JJF3 { public static void main(String args[]) { System.out.print(Integer.toBinaryString(Byte.MAX_VALUE)+","); System.out.print(Integer.toOctalString(Byte.MAX_VALUE)+","); System.out.print(Integer.toString(Byte.MAX_VALUE)+","); System.out.print(Integer.toHexString(Byte.MAX_VALUE)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 1111111,177,127,7f Prints: 11111111,377,256,ff Compile-time error Run-time error None of the above

Resposta:

A byte is an 8 bit signed value. The left most bit is the sign bit. The sign bit is set to zero for positive numbers and is set to one for negative numbers. The most positive byte value is represented as a sign bit that is set to zero and all of the other bits set to one. The Integer.toBinaryString method does not print leading zeros; so only seven bits are printed. An eight bit binary value is represented as three octal digits. The first of the three digits represents the left most two bits Prints: of the binary value. In this case, the left most two bits are 13 a 1111111,177,127,7f zero and one. The second octal digit represents the next three bits of the binary value. The last of the octal digits represents the right most three bits of binary value. Note that the Integer.toOctalString method does not print a leading zero as is required for an octal literal value. An eight bit binary value is represented as two hexadecimal digits. The left hex digit represents the left most four bits of the binary value. The right hex digit represents the right most four bits of the binary value.

Question 14
class GFC102 { public static void main(String[] args) { byte b1 = -129; // 1 byte b2 = 127; // 2 short s1 = -32768; // 3 short s2 = 32768; // 4 char c1 = -1; // 5 char c2 = 65535; // 6 }}

Compile-time errors are generated at which lines?

a. b. c. d. e. f.

1 2 3 4 5 6

Resposta:

a 14 d e

1 4 5

The minimum value of type byte is -128. The maximum value of type short is 32767. The minimum value of type char is 0.

Question 15
Which of these words belong to the set of Java keywords?
a. b. c. d. e. f. g. transient serializable runnable run volatile externalizable cloneable

Resposta:

Serializable, Runnable, Externalizable, a and Cloneable are all interfaces. Thread.run is a 15 transient volatile e method. The keywords transient and volatile are field modifiers.

Question 16
class GFM12 { static int x; public static void main(String[] args) { int y; System.out.println("x="+x); System.out.println("y="+y); }} // // // // // 1 2 3 4 5

What is the result of attempting to compile and run the program?


a. Compile-time error at line 1.

b. c. d. e. f. g.

Compile-time error at line 2. Compile-time error at line 3. Compile-time error at line 4. Compile-time error at line 5. Run-time error None of the above

Resposta:

16 e

Compile-time error at line 5.

The local variable y has not been initialized so the attempt to access the variable results in a compile-time error.

Question 17
class GFM13 { static byte a; static short b; static char c; static int d; static long e; static String s; public static void main(String[] args) { System.out.println(a+b+c+d+e+s); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 00000null Prints: 00000 Prints: 0null Prints: 0 Prints: null Compile-time error Run-time error None of the above

Resposta:

17 c

Prints: 0null

The numeric sum of variables a, b, c, d and e is zero. The zero is converted to a String and concatenated with s.

Question 18
Which of these words belong to the set of Java keywords?
a. virtual b. goto c. ifdef

d. e. f. g. h. i.

typedef friend struct implements union const

Resposta:

The words virtual, ifdef, typedef, friend, struct an 1 goto implements c d union are all words related to the C programming g 8 onst language. Although the words const and goto are also related to the C programming language, they are also Java i keywords. b

Question 19
class int int int int int int int int } Identifiers { i1; // 1 _i2; // 2 i_3; // 3 #i4; // 4 $i5; // 5 %i6; // 6 i$7; // 7 8i; // 8

Compile-time errors are generated at which lines?


a. b. c. d. e. f. g. h. 1 2 3 4 5 6 7 8

Resposta:

The first letter of an identifier can be any Unicode JLS 3.1 character that d is a Java letter. The first letter can not be a number. For historical 19 f 4 6 8 reasons, the dollar sign $ and underscore _ are considered Java letters h along with many currency symbols in use in the world today.

Operators Question 1
class EBH019 { public static void main (String args[]) { int i1 = 0xffffffff, i2 = i1 << 1; int i3 = i1 >> 1, i4 = i1 >>> 1; System.out.print(Integer.toHexString(i2) + ","); System.out.print(Integer.toHexString(i3) + ","); System.out.print(Integer.toHexString(i4)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: ffffffff,ffffffff,ffffffff Prints: ffffffff,ffffffff,7fffffff Prints: ffffffff,7fffffff,ffffffff Prints: ffffffff,7ffffffe,7ffffffe Prints: fffffffe,ffffffff,ffffffff Prints: fffffffe,ffffffff,7fffffff Prints: fffffffe,7fffffff,ffffffff Prints: fffffffe,7fffffff,7fffffff Run-time error Compile-time error None of the above

Resposta:

1f

Prints: fffffffe,ffffffff,7fffffff

If the left-hand operand of a shift operator, <<, >> and >>>, is of type int, then the shift distance is always within the range of 0 to 31, inclusive; and is specified by the least significant 5 bits of the right hand operand. Similarly, if the left-hand operand of a shift operator is of type long, then the shift distance is always within the range of 0 to 63, inclusive; and is specified by the least significant 6 bits of the right hand operand. The left shift operator, <<, shifts each bit of the left operand to the left a distance specified by the shift distance. A number of bits that is equal to the shift distance are shifted out of the leftmost bit position and are lost. A number of bits that is equal to the shift distance are shifted in at the right. The signed right shift operator, >>, shifts each bit of the left operand to the right a distance specified by the shift distance. A number of bits that is equal to the shift distance are shifted out of the right-most bit position and are lost. A number of bits that is equal to the shift distance are shifted in at the left. The value of each bit that is shifted in at the

left is equal to the value of the sign bit. The signed right shift operator maintains the sign of the left operand. The unsigned right shift operator, >>>, is similar to the signed right shift operator except for the fact that each bit shifted in at the left is zero.

Question 2
class EBH201 { public static void main (String[] args) { int a = 1 || 2 ^ 3 && 5; int b = ((1 || 2) ^ 3) && 5; int c = 1 || (2 ^ (3 && 5)); System.out.print(a + "," + b + "," + c); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: 0,0,0 Prints: 0,0,3 Prints: 0,3,0 Prints: 0,3,3 Prints: 3,0,0 Prints: 3,0,3 Prints: 3,3,0 Prints: 3,3,3 Run-time error Compile-time error None of the above

Resposta:

2j

Compile-time Both operands of the conditional and operator and the error conditional or operator must be of type boolean.

Question 3
class EBH202 { static boolean a, b, c; public static void main (String[] args) { boolean x = (a = true) || (b = true) && (c = true); System.out.print(a + "," + b + "," + c); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g. h. i. j. k.

Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true Run-time error Compile-time error None of the above

Resposta:

3e

Prints: true,false,false

The conditional and expression is not evaluated, because the left hand operand of the conditional or expression is true. The original expression is as follows: x = (a = true) || (b = true) && (c = true). The left hand operand of the conditional or expression is the result of the assignment expression, (a = true). Since the left hand operand of the conditional or expression is true, the right hand operand will not be evaluated. In this case, the right hand operand is the conditional and expression. Consequently, neither operand of the conditional and expression is evaluated and the variables, b and c, maintain their default values of false.

Question 4
class EBH203 { static boolean a, b, c; public static void main (String[] args) { boolean x = a || (b = true) && (c = true); System.out.print(a + "," + b + "," + c); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true

i. Run-time error j. Compile-time error k. None of the above


Resposta:

The right hand operand of the conditional or operator is evaluated only if the left hand operand is false. The right hand operand of the conditional and operator is only evaluated if the left hand operand is true. In this case, the left hand operand of the Prints: 4d conditional or operator is false, so the right hand operand must false,true,true also be evaluated. The left hand operand of the conditionaland operator is the result of the conditional or expression, true, so the right hand operand is evaluated.

Question 5
class EBH011 { public static void main (String[] args) { float a = Float.POSITIVE_INFINITY; double b = Double.POSITIVE_INFINITY; double c = Double.NaN; System.out.print((a == b)+","+(c == c)+","+(c != c)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true Run-time error Compile-time error None of the above

Resposta:

Prints: 5f true,false,true

The positive infinity of type float is promoted to the positive infinity of type double. NaN is not equal to anything including itself.

Question 6
class EBH012 { public static void main (String[] args) { byte x = 3, y = 5; System.out.print((-x == ~x + 1)+","+(-y == ~y + 1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Run-time error Compile-time error None of the above

Resposta:

6d

Prints: true,true

The sign of an integral numeric type is changed by inverting all of the bits and by adding one.

Question 7
class EBH013 { public static void main (String[] args) { byte x = 3, y = 5; System.out.print((~x == -x - 1)+","+(~y == -y - 1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Run-time error Compile-time error None of the above

Resposta:

Prints: 7d true,true

The bitwise complement operator produces the same result as changing the sign and subtracting one. Please note that the operand must be an integral type. The bitwise complement operator can not be applied to a floating-point value.

Question 8
class EBH014 { public static void main (String[] args) { byte x = 3, y = 5; System.out.print((y % x) + ","); System.out.print(y == ((y/x)*x + (y%x))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,true Prints: 2,true Prints: 1,false Prints: 2,false Run-time error Compile-time error None of the above

Resposta:

8b

Prints: 2,true

Suppose the left operand were divided by the right operand. The remainder operator returns the remainder of the division operation. For integral types, the identity, (y == ((y/x)*x+(y%x))), is always true.

Question 9
class Color {} class Red extends Color {} class Blue extends Color {} class A { public static void main (String[] args) { Color color1 = new Red(); Red color2 = new Red(); boolean b1 = color1 instanceof Color; boolean b2 = color1 instanceof Blue; boolean b3 = color2 instanceof Blue; System.out.print(b1+","+b2+","+b3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. false,false,false false,false,true false,true,false false,true,true

e. f. g. h. i. j. k.

true,false,false true,false,true true,true,false true,true,true Run-time error Compile-time error None of the above

Resposta:

The type of the reference color2 is Red. Since Red is not a subclass or a superclass of Blue, the expression color2 instanceof Blue is rejected at compile-time. Please note: The expression, x instanceof T, produces a compile-time error whenever the cast expression (T)x produces a compile-time error. If the program had been able to compile and run, the expression color1 instanceof Color would evaluate to true at run-time. The reference color1 refers to an instance of type Red. Since Red is a Compile9j time error subclass ofColor, the expression color1 instanceof Color would evaluate to true at run-time. The expression, color1 instanceof Blue would evaluate to false at run-time. The reference, color1, is of type Color. Since Color is a superclass of Blue, the expression, color1 instanceof Blue, is accepted at compile-time. The type of the object instance referenced by color1 is Red. Since Red is not Blue or a subclass of Blue, the expression, color1 instanceof Blue, would be false at runtime.

Question 10
class EBH020 { public static void main (String[] args) { int a = 1 | 2 ^ 3 & 5; int b = ((1 | 2) ^ 3) & 5; int c = 1 | (2 ^ (3 & 5)); System.out.print(a + "," + b + "," + c); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 0,0,0 Prints: 0,0,3 Prints: 0,3,0 Prints: 0,3,3 Prints: 3,0,0 Prints: 3,0,3

g. h. i. j. k.

Prints: 3,3,0 Prints: 3,3,3 Run-time error Compile-time error None of the above

Resposta:

Java evaluates operands from left to right while respecting operator precedence. The order of operator precedence starting with the lowest is Prints: 10 f as follows: |, ^, &. Although complete memorization of the operator 3,0,3 precedence chart is not necessary, it is a good idea to memorize the three levels that appear in this question.

Question 11
class EBH025 { public static void main (String args[]) { int i1 = 0xffffffff, i2 = i1 << 33; int i3 = i1 << (33 & 0x1f); System.out.print(Integer.toHexString(i2) + ","); System.out.print(Integer.toHexString(i3)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0,0 Prints: 0,fffffffe Prints: 0,ffffffff Prints: ffffffff,ffffffff Prints: ffffffff,fffffffe Prints: fffffffe,ffffffff Prints: fffffffe,fffffffe Run-time error Compile-time error None of the above

Resposta:

For each of the three shift operators, <<, >> and >>>, the shift distance is specified by the right hand operand. If the left operand is of type int, then the shift distance is always within Prints: the range 0 to 31, inclusive; and the following expression is 11 g fffffffe,fffffffe always true: (int1 << shift) == (int1 << (shift & 0x1f)). The hexadecimal representation of decimal 31 is 0x1f and the binary representation is 0001 1111. The hexadecimal representation of decimal 33 is 0x21 and the binary

representation is 0010 0001. The expression i1 << (33 & 0x1f) is equivalent to (0xffffffff << (0x21 & 0x1f)). Evaluation of the right hand operand of the shift operator produces (0xffffffff << 1). The final result is0xfffffffe. Similarly, if the left operand is of type long, then the shift distance is always within the range 0 to 63, inclusive; and the following expression is always true: (long1 << shift) == (long1 << (shift & 0x3f)).

Question 12
class EBH001 { static int m(int i) {System.out.print(i + ", "); return i;} public static void main(String s[]) { m(m(1) - m(2) + m(3) * m(4)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 1, 2, 3, 4, 8, Prints: 1, 2, 3, 4, 11, Prints: 3, 4, 1, 2, 11, Run-time error Compile-time error None of the above

Resposta:

The expression can be simplified as follows: j = 1 - 2 + 3 * 4 = 11. The original expression is as follows: m(m(1) - m(2) + Prints: 1, m(3) * m(4)). Simplification step one. Evaluate each operand from 12 b 2, 3, 4, left to right: m(1 - 2 + 3 * 4). Step two. Add parentheses to 11, indicate operator precedence: m(1 - 2 + (3 * 4)). Step three. Evaluate the inner-most parentheses: m(1 - 2 + 12). Step four: Work through the expression from left to right. j = 11.

Question 13
class EBH002 { static int m(int i) {System.out.print(i + ", "); return i;} public static void main(String s[]) { m(m(1) + m(2) % m(3) * m(4)); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g. h. i.

Prints: 1, 2, 3, 4, 0, Prints: 1, 2, 3, 4, 3, Prints: 1, 2, 3, 4, 9, Prints: 1, 2, 3, 4, 12, Prints: 2, 3, 4, 1, 9, Prints: 2, 3, 4, 1, 3, Run-time error Compile-time error None of the above

Resposta:

Prints: 13 c 1, 2, 3, 4, 9,

The expression can be simplified as follows: 1 + 2 % 3 * 4 = 9. The original expression is as follows: m(m(1) + m(2) % m(3) * m(4)). Simplification step one. Evaluate each operand from left to right: m(1 + 2 % 3 * 4). Step two. Add parentheses to indicate operator precedence and associativity: m(1 + ((2 % 3) * 4). Step three. Evaluate the inner-most parentheses: m(1 + (2 * 4)). Step four. Evaluate the inner-most parentheses: m(1 + 8). The result is 9.

Question 14
class EBH005 { public static void main (String[] s) { byte b = 127; b <<= 2;System.out.println(b); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: -4 Prints: -3 Prints: -2 Prints: 0 Prints: 1 Prints: 127 Prints: 508 Run-time error Compile-time error None of the above

Resposta:

14 a

Prints: If the left-hand operand of the shift operator is of type byte, short, -4 or char then the left operand is promoted to a 32 bit int and all four

bytes are shifted. When a variable of typeint with a value of 127 is shifted two bits to the left, the result is 508. The compound assignment operator includes an implicit cast to the type of the left-hand operand. The expression, E1 op= E2, is equivalent to E1=(T)((E1) op (E2)), where T is the type of the left hand operand. Therefore, when 508 is cast to an eight bit byte, the three most significant bytes (24 bits) are discarded leaving only the least significant byte (8 bits). The result is the binary value, 11111100, which is the two's complement representation of negative four.

Question 15
class EBH007{ public static void main (String[] s) { byte b = 5; System.out.println(b<<33); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: -1 Prints: 0 Prints: 1 Prints: 5 Prints: 10 Run-time error Compile-time error None of the above

Resposta:

If the left-hand operand of the shift operator is of type byte, short, or char then the left operand is promoted to a 32 bit int and all four bytes are shifted. If the promoted type of the left-hand operand is of Prints: type int, then the shift distance is always within the range of 0 to 31, 15 e inclusive; and is specified by the least significant 5 bits of the right-hand 10 operand. In this case, the shift distance is 33, and the five least significant bits are 00001; so the shift distance is one bit. Note: If the type of the left hand operand is long, then the least significant six bits of the right hand operand are used.

Question 16
class EBH015 { public static void main (String[] args) { System.out.print((new Object() instanceof Object)+","); System.out.print((new Object() instanceof String)+",");

System.out.print((new String() instanceof Object)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true Run-time error Compile-time error None of the above

Resposta:

16 f

Prints: true,false,true

The left operand of the instanceof operator must be null or a reference to an instance of an Object or a subclass of Object. The right operand of the instanceof operator must be a class type, interface type or array type. If the left operand is a reference to an instance of the type specified by the right operand or if the left operand is a reference to an instance of a subclass of the type specified by the right operand, then instanceof returns true.

Question 17
class EBH101 { static int m(int i) {System.out.print(i + ", "); return i;} public static void main(String s[]) { int i = 1; m(m(++i) + m(i++) + m(-i) + m(i++)); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. Prints: 1, 2, 3, 4, 10, Prints: 1, 2, -3, 4, 4, Prints: 2, 2, -3, -3, -2, Prints: 2, 2, -3, 3, 4, Prints: 2, 3, -3, -2, 0, Prints: 2, 3, -3, 4, 6,

g. h. i. j.

Prints: 2, 3, 4, 5, 14, Run-time error Compile-time error None of the above

Resposta:

The expression can be simplified as follows: j = 2 + 2 + -3 + 3 Prints: 2, = 4. The original expression is as follows: j = ++i + i++ + -i 17 d 2, -3, 3, + i++. Simplification step one. Evaluate the unary expressions from 4, left to right: j = 2 + 2 + -3 + 3. Step two. Complete the evaluation of the simplified expression: j = 4.

Question 18
class EBH102 { static int m(int i) {System.out.print(i + ","); return i;} public static void main(String s[]) { int i = 1, j = m(i++) + m(i++) * m(i++) + m(i++); System.out.print(j % 5); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. i. Prints: 1,2,3,4,0 Prints: 1,2,3,4,1 Prints: 1,2,3,4,2 Prints: 1,2,3,4,3 Prints: 1,2,3,4,4 Prints: 1,2,3,4,5 Run-time error Compile-time error None of the above

Resposta:

18 b

Prints: 1,2,3,4,1

The expression can be simplified as follows: j = 1 + (2 * 3) + 4 = 11. The original expression is as follows: j = m(i++) + m(i++) * m(i++) + m(i++). The method, m, prints and then returns the value of the parameter, so the original expression is equivalent to the following: j = i++ + i++ * i++ + i++. Step one. Work through the expression from left to right to evaluate the unary expressions: j = 1 + 2 * 3 + 4. Step two. Add parentheses to indicate operator precedence: j = 1 + (2 * 3) + 4. Step three. Work through the simplified expression: j = 1 + 6

+ 4 = 11. Step four. Evaluate the expression that is the argument of the print method: j % 5 = 11 % 5 = 1.

Question 19
class EBH103 { public static void main (String[] args) { byte a = 1, b = 2, c = (byte)a++, d = (byte)++b, e = (byte)a + b; System.out.print(c + d + e); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. i. j. k. Prints: 1 2 3 Prints: 6 Prints: 2 3 5 Prints: 10 Prints: 1 3 4 Prints: 8 Prints: 1 3 5 Prints: 9 Run-time error. Compile-time error. None of the above

Resposta:

The precedence of the cast operator is higher than the precedence of the addition operator, so the cast applies only to variable a and not to Compile- the result of the addition. Binary numeric promotion causes the byte variables a and b to be promoted to type int before the 19 j time error. addition operation, and the result of the addition is also of type int. The attempt to assign the int result to thebyte variable e generates a possible loss of precision error.

Question 20
class EBH204 { static boolean m1(String s, boolean b) { System.out.print(s + (b ? "T" : "F")); return b; } public static void main(String[] args) { m1("A",m1("B",false) || m1("C",true) || m1("D",false)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: ATBFCT Prints: ATBFCTDF Prints: BFCTAT Prints: BTCTDFAT Run-time error Compile-time error None of the above

Resposta:

20 c

Prints: BFCTAT

The right operand of the conditional or operator is evaluated only if the left hand operand is false. In this case, the left operand of the first conditional or operator is false so the right hand operand is evaluated. No further evaluation of the expression is necessary so the right hand operand of the second conditional or operator is not evaluated.

Question 21
class EBH104 { static int m(int i) {System.out.print(i + ", "); return i;} public static void main(String s[]) { int i = 1; m(m(++i) - m(i++) + m(-i) * m(~i)); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. i. j. Prints: 2, 2, -3, -4, 8, Prints: 2, 2, -3, -4, 12, Prints: 2, 3, -3, -4, 7, Prints: 1, 1, 1, 1, 0, Prints: 2, 2, -2, -2, 4, Prints: 2, 3, -2, -2, 3, Prints: -1, -2, 2, 2, 0, Run-time error Compile-time error None of the above

Resposta:

Prints: 2, The original expression is as follows: m(m(++i) - m(i++) + 21 b 2, -3, -4, m(-i) * m(~i)). The method, m, prints and then returns the value 12, of the parameter, so the original expression is equivalent to the

following: ++i - i++ + -i * ~i. We can use a simplification process that evaluates the expression as follows. Step one. Work through the expression from left to right to evaluate the unary expressions: 2 - 2 + -3 * -4. Step two. Add the parentheses to indicate operator precedence: 2 - 2 + (-3 * -4). Step three. Evaluate the inner-most parentheses: 2 - 2 + 12. Step four. Evalute the simplified expression to produce the result, 12. The bitwise complement operator, ~, inverts each bit of the operand. To avoid working in binary the same result can be obtained by changing the sign of the operand and then subtracting 1. The following identity is always true ~x == -x - 1.

Question 22
class EBH105 { static int m(int i) {System.out.print(i + ","); return 0;} public static void main (String[] args) { int i = 0; i = i++ + m(i); System.out.print(i); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. Prints: 0,0 Prints: 1,0 Prints: 0,1 Prints: 1,1 Run-time error Compile-time error None of the above

Resposta:

The expression, i = i++ + m(i), can be reduced to, i = 0 + 0. The left operand of the addition expression is found to be zero, and the value of variable i is then incremented to 1. The right hand operand of Prints: the addition operation is evaluated next. The value, 1, is passed to 22 b 1,0 method m. After printing the argument value, method m returns the value zero. The two operands of the addition operation are zero as is the result of the addition. The zero value serves as the right hand operand of the assignment statement, so the value, zero, is assigned to variable i.

Question 23
class EBH106 {

public static void main(String args[]) { int a = 1; a += ++a + a++; System.out.print(a); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. Prints: 3 Prints: 4 Prints: 5 Prints: 6 Prints: 7 Run-time error Compile-time error None of the above

Resposta:

The two statements, int a=1 followed by a += ++a + a++, can be rewritten as the single statement, a=(int)((1)+(++a + a++)). Prints: Further evaluation produces a=(int)((1)+(2 + 2)). Generally 23 c 5 speaking, a compound assignment expression of the form E1 op= E2 can be rewritten as E1=(T)((E1)op(E2)) where T is the type of E1.

Question 24
class EBH107 { static int m(int i) {System.out.print(i + ","); return i;} public static void main(String s[]) { int i=0, j = m(++i) + m(++i) * m(++i) % m(++i) + m(++i); System.out.print(j%5); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. Prints: 1,2,3,4,5,0 Prints: 1,2,3,4,5,1 Prints: 1,2,3,4,5,2 Prints: 1,2,3,4,5,3 Prints: 1,2,3,4,5,4 Prints: 1,2,3,4,5,5 Run-time error Compile-time error

i. None of the above


Resposta:

24 d

Prints: 1,2,3,4,5,3

The expression can be simplified as follows: j = 1 + ((2 * 3) % 4) + 5 = 8. The original expression is as follows: j = ++i + ++i * ++i % ++i + ++i. Step one. Evaluate the unary expressions from left to right: j = 1 + 2 * 3 % 4 + 5. Step two. Add parentheses to indicate operator precedence: j = 1 + ((2 * 3) % 4) + 5. Step three. Evaluate the inner most parentheses: j = 1 + (6 % 4) + 5. Repeat step three: j = 1 + 2 + 5. Repeat step three: j = 8. The argument of the print expression is: j%5. The result is: 8 % 5 = 3.

Question 25
class EBH108 { public static void main(String s[]) { int i=0, j = ++i + ((++i * ++i) % ++i) + ++i; System.out.print(j%5); }}

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. h. Prints: 1 Prints: 2 Prints: 3 Prints: 4 Prints: 5 Run-time error Compile-time error None of the above

Resposta:

The expression can be simplified as follows: j = 1 + ((2 * 3) % 4) + 5 = 8. The original expression is as follows: j = ++i + ((++i * ++i) % ++i) + ++i;. Step one. Evaluate the unary Prints: expressions from left to right: j = 1 + ((2 * 3) % 4) + 5. Step 25 c 3 two. Evaluate the inner-most parentheses: j = 1 + (6 % 4) + 5. Step three: Evaluate the inner-most parentheses. j = 1 + 2 + 5. Step four: Work through the expression from left to right. j = 8. The argument of the print expression is: j%5. The result is: 8 % 5 = 3.

Question 26
class EBH023 { static String m1(boolean b){return b?"T":"F";} public static void main(String [] args) { boolean b1 = false?false:true?false:true?false:true; boolean b2 = false?false:(true?false:(true?false:true)); boolean b3 = ((false?false:true)?false:true)?false:true; System.out.println(m1(b1) + m1(b2) + m1(b3)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: FFF Prints: FFT Prints: FTF Prints: FTT Prints: TFF Prints: TFT Prints: TTF Prints: TTT Run-time error Compile-time error None of the above

Resposta:

26 b

Prints: FFT

The expression used to assign variable b1 is equivalent to the expression used to assign variable b2. The results demonstrate that the conditional operator (?:) groups from right-to-left.

Question 27
class EBH024 { public static void main(String[] args) { int i1 = 15; String b1 = (i1>30)?"Red":(i1>20)?"Green":(i1>10)?"Blue":"Violet"; String b2 = (i1>30)?"Red":((i1>20)?"Green":((i1>10)?"Blue":"Violet")); System.out.println(b1 + "," + b2); }}

What is the result of attempting to compile and run the program?


a. Prints: Red,Red b. Prints: Green,Green c. Prints: Blue,Blue

d. e. f. g. h. i. j. k.

Prints: Violet,Violet Prints: Blue,Violet Prints: Violet,Blue Prints: Blue,Green Prints: Green,Blue Run-time error Compile-time error None of the above

Resposta:

Prints: 27 c Blue,Blue

The expression used to assign variable b1 is equivalent to the expression used to assign variable b2. The results demonstrate that the conditional operator (?:) groups from right-to-left.

Question 28
class EBH003 { static int m(int i) {System.out.print(i + ", "); return i;} public static void main(String s[]) { m(m(~1) + m(1|2) + m(1&2) + m(1^3) + m(1<<1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. l. m. Prints: -2, 3, 0, 3, 0, 6, Prints: -2, 3, 0, 2, 1, 4, Prints: -2, 3, 0, 2, 2, 5, Prints: -2, 3, 0, 3, 2, 6, Prints: -1, 3, 0, 3, 2, 7, Prints: -2, 0, 3, 3, 0, 6, Prints: -1, 0, 3, 2, 1, 4, Prints: -2, 0, 3, 2, 2, 5, Prints: -2, 0, 3, 3, 2, 6, Prints: -1, 0, 3, 3, 2, 7, Run-time error Compile-time error None of the above

Resposta:

The expression can be simplified as follows: -2+3+0+2+2=5. The Prints: original expression is as follows: m(m(~1) + m(1|2) + m(1&2) 28 c 2, 3, 0, + m(1^3) + m(1<<1)). Expr 1: ~1 = -1 - 1 = -2. Expr 2, 2, 5, 2: 1|2 = 0001 | 0010 = 0011 = 3. Expr 3: 1&2 = 0001 &

0010 = 0000. Expr 4: 1^3 = 0001 ^ 0011 = 0010 = 2. Expr 5: 1<<1 = 0001 << 1 = 0010 = 2. Note: The bitwise expressions were demonstrated using only four bits of the 32 bit int type values.

Question 29
class EBH021 { public static void main(String[] args) { System.out.print((-1 & 0x1f) + "," + (8 << -1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 0,0 Prints: -1,4 Prints: 0x1f,8 Prints: 31,16 Run-time error Compile-time error None of the above

Resposta:

Prints 31,0. The expression (-1 & 0x1f) is equal to (0xffffffff & 0x1f), and both are equal to the hex value 0x1f or decimal 31. The expression (8 << -1) is equivalent to (8 << 0xffffffff). If the left hand operand of a shift expression is of type int, then the None of right hand operand is implicitly masked with the value 0x1f. In other 29 g the words, the expression (8 << -1) is equivalent to (8 << (-1 & above 0x1f)). By replacing -1 with the hexadecimal representation we have (8 << (0xffffffff & 0x1f)). By evaluating the right hand operand we have (8 << 31). When 8 is shifted 31 bits to the left, the result is zero since the only non-zero bit is lost as it is shifted beyond the most significant bit of the int data type.

Multidimensional Arrays Question 1


class MWC201 { public static void main(String[] args) { int[][] a1 = {{1,2,3},{4,5,6},{7,8,9,10}}; System.out.print(a1[0][2]+","+a1[1][0]+","+a1[2][1]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 3,4,8 Prints: 7,2,6 Compile-time error Run-time error None of the above

Resultado:

An array variable a1 is declared, and the declaration contains the initializer {{1,2,3},{4,5,6},{7,8,9,10}}. The initializer creates an array containing three components, and each is a reference to a subarray Prints: of type int[]. Each subarray contains components of type int, so the 1a 3,4,8 elements of the array referenced by a1 are of type int. The array access expression, a1[0][2] = a1[1st subarray][third component] = 3.

Question 2
class MWC202 { public static void main(String[] args) { int[] a1[] = {{1,2},{3,4,5},{6,7,8,9}}; int []a2[] = {{1,2},{3,4,5},{6,7,8,9}}; int a3[][] = {{1,2},{3,4,5},{6,7,8,9}}; System.out.print(a1[0][1]+","+a2[1][2]+","+a3[2][3]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 14 Prints: 16 Prints: 1,5,9 Prints: 2,4,8 Prints: 2,5,9 Compile-time error Run-time error None of the above

Resultado:

The declarations of the array variables, a1, a2 and a3, are different in terms of the position of the square brackets, but each is of type int[][]. Prints: The array access expression, a1[0][1] =a[1st subarray][2nd 2e 2,5,9 component] = 2. Each of the three array variable declarations has an array initializer. The same initializer, {{1,2},{3,4,5},{6,7,8,9}}, is used in each of the

three cases. The initializer specifies three components of type int[], so each component is a reference to an array object containing components of type int. The size of each of the subarrays is different: The size of the first is 2, the second is 3, and the third is 4.

Question 3
class MWC207 { public static void main(String[] args) { int[][] a1 = {{1;2};{3;4;5};{6;7;8;9}}; System.out.print(a1[0][1]+","+a1[1][2]+","+a1[2][3]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 14 Prints: 16 Prints: 1,5,9 Prints: 2,4,8 Prints: 2,5,9 Compile-time error Run-time error None of the above

Resultado:

The array initializer, {{1;2};{3;4;5};{6;7;8;9}} generates a Compilecompile-time error, because the commas have been replaced by 3 f time semicolons. The array initializer should have been specified as error follows: {{1,2},{3,4,5},{6,7,8,9}}.

Question 4
class MWC208 { public static void main(String[] args) { int[][] a1 = ((1,2),(3,4,5),(6,7,8,9)); System.out.print(a1[0][1]+","+a1[1][2]+","+a1[2][3]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: 14 Prints: 16 Prints: 1,5,9 Prints: 2,4,8

e. f. g. h.

Prints: 2,5,9 Compile-time error Run-time error None of the above

Resultado:

The array initializer, ((1,2),(3,4,5),(6,7,8,9)), generates a Compile- compile-time error, because the curly braces have been replaced by 4f time error parentheses. The array initializer should have been specified as follows: {{1,2},{3,4,5},{6,7,8,9}}.

Question 5
class MWC209 { public static void main(String[] args) { int[][] a1 = [[1,2],[3,4,5],[6,7,8,9]]; int[][] a2 = [[1,2],[3,4,5],[6,7,8,9]]; int[][] a3 = [[1,2],[3,4,5],[6,7,8,9]]; System.out.print(a1[0][1]+","+a2[1][2]+","+a3[2][3]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 14 Prints: 16 Prints: 1,5,9 Prints: 2,4,8 Prints: 2,5,9 Compile-time error Run-time error None of the above

Resultado:

The array initializer, [[1,2],[3,4,5],[6,7,8,9]], generates a Compile- compile-time error, because the curly braces have been replaced by 5f time error square brackets. The array initializer should have been specified as follows: {{1,2},{3,4,5},{6,7,8,9}}.

Question 6
class MWC210 { public static void main(String[] args) { int[] a2 = {1,2}, a3 = {3,4,5}, a4 = {6,7,8,9}; // 1 int[][] a1 = {a2,a3,a4}; // 2 System.out.print(a1[0][1]+","+a1[1][2]+","+a1[2][3]);

}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 14 Prints: 16 Prints: 1,5,9 Prints: 2,4,8 Prints: 2,5,9 Compile-time error Run-time error None of the above

Resultado:

The line marked 1 declares three array variables, a2, a3 and a4, and each references an array with components of type int. The line marked 2 Prints: declares an array variable, a1, where each component is initialized with a 6e 2,5,9 reference to one of the previously created arrays. The array access expression, a1[0][1], is evaluated as follows: a1[0][1] = a1[first subarray][second component] = 2.

Question 7
class MWC211 { public static void main(String[] args) { int a1[3]; // 1 int []a2[]; // 2 int[ ]a3; // 3 int[] a4[]; // 4 }}

A compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resultado:

A compile-time error occurs at the line marked 1, because the array variable declaration can not be used to specify the number of components contained in 7a 1 the array. Instead, the dimension expression should be contained in an array creation expression such as the following, new int[3].

Question 8
class MWC212 { public static void main(String[] args) { int[] a1[],a2[]; // 1 int []a3,[]a4; // 2 int []a5,a6[]; // 3 int[] a7,a8[]; // 4 }}

A compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resultado:

An array variable is declared by placing brackets after the identifier or after the type name. A compile-time error occurs at the line marked 2, because the 8b 2 brackets appearing before the identifier for array variable a4 are not associated with the type or the identifier.

Question 9
class MWC203 { public static void main(String[] args) { int[] a1[] = {new int[]{1,2},new int[]{3,4,5}}; int []a2[] = new int[][]{{1,2},{3,4,5}}; int a3[][] = {{1,2},new int[]{3,4,5}}; System.out.print(a1[0][1]+","+a2[1][0]+","+a3[1][2]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: 14 Prints: 16 Prints: 1,2,4 Prints: 2,3,4 Prints: 2,3,5 Prints: 2,4,5 Compile-time error Run-time error None of the above

Resultado:

Each of the three array variable declarations, a1, a2 and a3, is different in terms of the position of the square brackets, but each declares a variable of type int[][]. Each of the three declarations contains an array initializer. In each case, the initializer could be simplified as Prints: follows: {{1,2},{3,4,5}}. The initializer creates an array containing 9e 2,3,5 two components, and each is a reference to an array containing components of type int. The size of each of the subarrays is different: The size of the first is 2 and the second is 3. The array access expression, a1[0][1] =a[1st subarray][2nd component] = 2.

Question 10
class MWC204 { public static void main(String[] args) { int[][] a1 = {{1,2},{3,4,5},{6,7,8,9},{}}; System.out.print(a1.length); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: 0 Prints: 3 Prints: 4 Prints: 9 Prints: 10 Prints: 11 Compile-time error Run-time error None of the above

Resultado:

The array initializer, {{1,2},{3,4,5},{6,7,8,9},{}}, creates an array containing four components, and each is a reference to a subarray of Prints: 10 c type int[]. The size of the array referenced by variable a1, is 4, 4 because a1 contains four components. The size of the first subarray is 2, the second is 3, the third is 4 and the fourth is zero.

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

}}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 2,3,4,0, Prints: 1,2,5,0, Compile-time error Run-time error None of the above

Resultado:

The array initializer, {{1,2},{3,4,5},{6,7,8,9},{}}, creates an array containing four components, and each is a reference to an array Prints: of type int[]. The size of the first subarray is 2, the second is 3, the 11 a 2,3,4,0, third is 4, and the fourth is zero. While the components of the array referenced by a1 are of type int[], the elements of the array referenced by a1 are of type int.

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

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 123456789 Prints: 147258369 Prints: 321654987 Prints: 369258147 Run-time error Compile-time error None of the above

Resultado:

The array variable a1 is declared with the initializer, {{1,2,3},{4,5,6},{7,8,9}}. The array access expression, a1[0][1] = a1[first subarray][second Prints: 12 b 147258369 element] = 2. If the argument of the print statement had been a1[i][j] then the output would have been 123456789. The tricky feature of this question is the reversal of i and j to produce

the deceptive array access expression, a1[j][i]. The output is 147258369.

Question 13
class A11 {public String toString() {return "A11";}} class A12 { public static void main(String[] arg) { A11[] a1 = new A11[1]; // 1 A11[][] a2 = new A11[2][]; // 2 A11[][][] a3 = new A11[3][][]; // 3 a1[0] = new A11(); // 4 a2[0] = a2[1] = a1; // 5 a3[0] = a3[1] = a3[2] = a2; // 6 System.out.print(a3[2][1][0]); // 7 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: null Prints: A11 Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. Compile-time error at 5. Compile-time error at 6. Compile-time error at 7. Run-time error None of the above

Resultado:

The declaration A11[] a1 = new A11[1] declares a variable a1 that references an array that contains one component of type A11. The declaration A11[][] a2 = new A11[2][] declares a variable a2 that references an array that contains two components of type A11[]. In other words, the array referenced by a2 contains two reference variables, and each is able to reference a subarray. The initial value of the subarray references 13 b Prints: A11 is null. The size of the subarrays has not been specified. The declaration A11[][][] a3 = new A11[3][][] declares a variable a3 that references an array that contains three components of type A11[][]. In other words, the array referenced by a3 contains three reference variables, and each is able to reference a subarray. The initial value of each subarray reference is null. The dimensions of the subarrays have not been specified.

At line 5, a reference to the array referenced by a1 is assigned to each of the two components of the array referenced by a2, a2[0] = a2[1] = a1. At line 6, a reference to the array referenced by a2 is assigned to each of the three components of the array referenced by a3, a3[0] = a3[1] = a3[2] = a2. In other words, after line 6, each component of the array referenced by a3 is a reference to the array referenced by a2, and each element of the array referenced by a2 is a reference to the array referenced by a1, and the array referenced by a1 contains a reference to an instance of class A11. Every element of the multi-dimensional array referenced by a3 contains a reference to a single instance of class A11. The print method invokes the toString method on the instance, and produces the output, A11.

Question 14
class A13 {} class A14 { public static void main(String[] arg) { A13[] a1 = new A13[1]; // A13[][] a2 = new A13[2][1]; // A13[][][] a3 = new A13[3][3][3]; // System.out.print(a3[2][2][2]); // a1[0] = new A13(); // a2[0] = a2[1] = a1; // a3[0] = a3[1] = a3[2] = a2; // System.out.print(a3[2][2][2]); // }}

1 2 3 4 5 6 7 8

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: null Prints: nullnull Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. Compile-time error at 5. Compile-time error at 6. Compile-time error at 7. Compile-time error at 8. Run-time error

Resultado:

14 a Prints:

The declaration A13[] a1 = new A13[1] declares a

k null Runtime error

variable a1 that references an array that contains one component of type A13. The declaration A13[][] a2 = new A13[2][1] declares a variable a2 that references an array that contains two components of type A13[]. In other words, the array referenced by a2 contains two references to two subarrays of typeA13[]. The size of each subarray is 1. The declaration A13[][][] a3 = new A13[3][3][3] declares a variable a3 that references an array that contains three components of typeA13[][]. In other words, the array referenced by a3 contains three references to three subarrays of type A13[][]. The dimensions of the subarrays are 3 X 3. The dimensions of the array referenced by a3 are 3 X 3 X 3. The number of elements in the array referenced by a3 is 3 * 3 * 3 = 27 elements. Each of the three subarrays contains three components, where each is a reference to a subarray of type A13[]. Each of the 27 elements of the array referenced by a3 is a reference of type A13 that has been initialized to the default value of null. At line 7, a reference to the array referenced by a2 is assigned to each of the three components of the array referenced by a3, a3[0] = a3[1] = a3[2] = a2. Since the array referenced by a2has dimensions 2 X 1, the array referenced by a3 now has dimensions 3 X 2 X 1. The number of elements is 6. An attempt to access any element beyond those 6 results in an exception at run-time.

Conversions Question 1
class A { public static void main(String[] args) { char a = 'a', b = 'b'; // 'a' = 97, 'b' = 98 System.out.print(a + b + "" + a + b); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 390 Prints: 195195 Prints: 195ab Prints: ab195 Prints: abab Run-time error Compile-time error None of the above

Resultado:

Both operands of the first addition operator are promoted from type char to int, and are evaluated as integral numeric values. The right hand operand of the second addition operator is of typeString, so the Prints: 1c result of the first addition operator is converted to type String, and is 195ab concatenated with the right hand operand. As evaluation of the expression continues from left to right, the remaining operands are also converted to type String.

Question 2
class Black { public static void main(String[] args) { short s1 = 1; //1 char c1 = 1; //2 byte b1 = s1; //3 byte b2 = c1; //4 final short s2 = 1; //5 final char c2 = 1; //6 byte b3 = s2; //7 byte b4 = c2; //8 }}

Compile-time errors are generated at which lines?


a. b. c. d. e. f. g. h. 1 2 3 4 5 6 7 8

Resultado:

This question demonstrates a variety of assignment conversions. The compiler will implicitly do a narrowing conversion for an assignment statement if the right hand operand is a compile time constant of type byte, short, char, or int and the value falls within the range of the c 2 3 4 variable on the left and if the variable on the left is of type byte, short, d or char. In this case, variables s1 and c1are not compile time constants so the compiler will not do an implicit narrowing conversion. However, variables s2 and c2 are compile time constants that fall within the range of the left hand operand. For more information, please see JLS section 5.2.

Question 3

class Magenta { static byte a = (byte)127, b = (byte)128, c = (byte)255, d = (byte)256; public static void main(String args[]) { System.out.print(a + " " + b + " " + c + " " + d); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 127 128 255 256 Prints: 127 128 255 0 Prints: 127 -1 -127 0 Prints: 127 -128 -1 0 Run-time error Compile-time error None of the above

Resultado:

Bytes are stored as 8 bit two's complement signed integers. When an int primitive is cast to a byte, the three most significant bytes are discarded Prints: and only the least significant byte remains. The most significant bit of 3 d 127 -128 the remaining byte becomes the new sign bit. byte a = (byte)127; // -1 0 01111111. byte b = (byte)128; // 10000000. byte c = (byte)255; // 11111111. byte d = (byte)256; // 00000000.

Question 4
interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Red { public static void main(String args[]) { Sub s1 = new Sub(); I2 i2 = s1; // 1 I1 i1 = s1; // 2 Base base = s1; // 3 Sub s2 = (Sub)base; // 4 }}

A compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resultado:

Line 4 does not generate a compile-time error. The reference None of named base actually refers to an instance of type Sub, so the 4e the above reference may be cast to type Sub.

Question 5
class Green { public static void int[] i = null; Cloneable c = i; i = (int [])c; }} main (String args[]) { // 1 // 2 // 3

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Compile-time error at line 1. Run-time error at line 1. Compile-time error at line 2. Run-time error at line 2. Compile-time error at line 3. Run-time error at line 3. None of the above

Resultado:

The null literal is converted to an int array type with the value null. None of All array types implement the Cloneable interface, so any array 5 g the reference can be assigned to a reference of typeCloneable. above The int array object referenced by the Cloneable reference, c, can be assigned to a reference of the int array type, int[].

Question 6
class Primitives { static void printFloat(float f) {System.out.println(f);} static void printDouble(double d) {System.out.println(d);} public static void main(String[] args) { byte b = 1; // 1 short s = b; // 2 char c = s; // 3 int i = c; // 4 long l = i; // 5 float f = l; // 6 printFloat(i); // 7 printFloat(l); // 8 printDouble(l); // 9 }}

A compile-time error is generated at which line?


a. b. c. d. e. f. g. h. i. j. 1 2 3 4 5 6 7 8 9 None of the above

Resultado:

6c 3

Short is signed and char is not signed so an explicit cast is necessary when a short is assigned to a char and vice versa.

Question 7
interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Orange { public static void main(String args[]) { Base base = new Base(); I1 i1 = base; // 1 Sub sub = (Sub)base; // 2 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Compile-time error at line 1 Run-time error at line 1 Compile-time error at line 2 Run-time error at line 2 None of the above

Resultado:

Run-time The compiler accepts the explicit cast at line 2, but an error is generated at run-time. Type Base is the super class of type Sub, so an instance 7 d error at line 2 of type Base can not be converted to the type of the subclass, Sub.

Question 8

class Purple { public static void main (String []args) { int[] i = {1,2,3}; // 1 Object obj = i; // 2 i = obj; // 3 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Compile-time error at line 1. Run-time error at line 1. Compile-time error at line 2. Run-time error at line 2. Compile-time error at line 3. Run-time error at line 3. None of the above

Resultado:

Compile-time 8e error at line 3.

Although the referenced object is indeed an array of type int, an explicit cast is necessary to cast the obj reference to an int array.

Question 9
class Maroon { public static void int a = 1; // short b = 1; // long c = 1; // a = c + a; // c = b + a; // }} main (String[] args) { 1 2 3 4 5

A compile-time error is generated at which line?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resultado:

The assignment expression, a = c + a, requires an explicit cast to type int. 9 d 4 If one of the two operands of a numeric expression is of type long and if the other operand is of type int, short,char or byte; then it will be promoted

to type long, and the result of the expression will be of type long. (Note: The rule does not apply to the shift operator.) The type long result can not be assigned to a variable of type int without an explicit cast.

Question 10
interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Yellow { public static void main(String args[]) { Base base = new Sub(); // 1 I1 i1 = base; // 2 Sub sub = (Sub)base; // 3 I2 i2 = (Sub)base; // 4 }}

A compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resultado:

Although the reference named base is of type Base, the instance that None of it refers to is of type Sub, and the reference can be cast to type Sub. 10 e the Since instances of type Sub implement both interfaces,I1 and I2, above the Sub type instances can be assigned to references of type I1 and I2 without an explicit cast.

Question 11
import java.io.Serializable; class Blue { public static void main (String args[]) { int[] i = {1,2,3}; // 1 Serializable s = i; // 2 i = (int [])s; // 3 }}

What is the result of attempting to compile and run the program?


a. Compile-time error at line 1. b. Run-time error at line 1.

c. d. e. f. g.

Compile-time error at line 2. Run-time error at line 2. Compile-time error at line 3. Run-time error at line 3. None of the above

Resultado:

11 g

None of the All array types implement the Serializable interface and may above be assigned to a reference of type Serializable.

Question 12
class Teal { public static void main (String[] args) { byte b = 1; // 1 long l = 1000; // 2 b += l; // 3 }}

A compile-time error is generated at which line?


a. b. c. d. 1 2 3 None of the above

Resultado:

None of 12 d the above

The compound assignment operators include an implicit cast to the type of the left hand operand. The expression at line 3, b += l, does not require an explicit cast to convert the right hand operand from type long to type byte.

Question 13
interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Gray { public static void main(String []args) { Base[] base = {new Base()}; // 1 Sub sub[] = {new Sub()}; // 2 Object obj = sub; // 3 base = obj; // 4 }}

A compile-time error is generated at which line?

a. b. c. d. e.

1 2 3 4 None of the above

Resultado:

The Object referenced by obj is of type Sub[], and the reference, base, 13 d 4 is of type Base[]. The assignment expression, base = obj requires an explicit cast to type Base[] as follows:base = (Base[])obj.

Question 14
class Black { public static void main(String args[]) { int[] i = {1,2,3,4,5}; long[] l = new long[5]; for (int j = 0; j < l.length(); j++) { l[j] = i[j]; }}} // // // // 1 2 3 4

A compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resultado:

The length member of the array type is an attribute. A compile-time error is 14 c 3 generated as a result of the attempt to access length as though it were a method.

Question 15
class Sienna { static double a; static float b; static int c; static char d; public static void main(String[] args) { a = b = c = d = 'a'; System.out.println(a+b+c+d == 4 * 'a'); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e.

Prints: true Prints: false Compile-time error Run-time error None of the above

Resultado:

The literal, 'a', is promoted to type int; and is then multiplied by the value of the left operand, 4. If one of the two operands of a 15 a Prints:true numeric expression is of type int, then the other operand will be promoted to type int if it is of type short, char or byte.

Question 16
interface I1 {} interface I2 {} class Base implements I1 {} class Sub extends Base implements I2 {} class Silver { public static void main(String []args) { Base[] base = {new Base()}; Sub sub[] = new Sub[1]; // 1 Object obj = base; // 2 sub = (Sub[])obj; // 3 I1 []i1 = (I1[])obj; // 4 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Compile-time error at line 1 Run-time error at line 1 Compile-time error at line 2 Run-time error at line 2 Compile-time error at line 3 Run-time error at line 3 Compile-time error at line 4 Run-time error at line 4 None of the above

Resultado:

Base is the superclass of type Sub, so a reference to an actual instance of type Base can not be cast to type Sub. Therefore, a reference to an Runarray instance of type Base[] can not be cast to type Sub[]. The type time 16 f error at of the reference, obj, is Object. Type Sub[] is a subclass line 3 of Object. The compiler accepts the cast, because the actual instance referenced at run-time might be of typeSub[]. In this case, the actual

type of the instance referenced by obj at run-time is found to be type Base[], so the result is a run-time error.

Question 17
class White { public static void main(String args[]) { int[] i = {1,2,3,4,5}; // 1 long[] l1 = new long[5]; // 2 long []l2 = l1; // 3 long l3[] = (long[])i; // 4 long l4[] = new long[5]; // 5 l4[1] = i[1]; // 6 }}

A compile-time error is generated at which line?


a. b. c. d. e. f. g. 1 2 3 4 5 6 None of the above

Resultado:

17 d 4

An array of primitive type can not be cast to an array of a different primitive type.

Question 18
class UltraViolet { public static void main (String[] args) char a = '\u002a', b = '\u0024'; // a Sign $ System.out.print(a + b); // System.out.print(" ABC" + a + b); // }} { = Asterisk *; b = Dollar 1 2

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: 78 ABC*$ Prints: *$ ABC*$ Prints: 78 ABC78 Compile-time error

e. Run-time error f. None of the above


Resultado:

Prints: 18 a 78 ABC*$

When char variables a and b are converted to String types they are printed as *$. When not converted to String types they are promoted to type int, and are printed as the numeric sum of 0x2a and 0x24. At line 1, the expression, a + b, can be evaluated as follows: 0x2a + 0x24 = 42 + 36 = 78. At line 2, the first operand of the expression, " ABC" + a + b, is of type String. Since one operand of the first addition operator is of type String the other operand must be converted to type String: (" ABC" + "*") + b = " ABC*" + b. The process is repeated for the second addition operation: " ABC*" + b = " ABC*" + "$" = " ABC*$"

Question 19
class Amber { public static void main(String[] args) { int[][] a = {{1,2},{0,1,2},{-1,0,2}}; Object[] obj = (Object[])a.clone(); for(int i = 0; i < obj.length; i++) { int[] ia = (int[])obj[i]; System.out.print(ia[i]); }}} // // // // // 1 2 3 4 5

A compile-time error is generated at which line?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resultado:

The program compiles and runs without error and prints 112. It is necessary to remember that arrays are Cloneable objects. Furthermore, a two dimensional array is also a single dimensional array of single dimensional arrays. At line 2, a two dimensional array None of of int primitives is converted to a single dimensional array with 19 f the components of type Object where each Object is a single above dimensional array. The loop iterates through each element of the Object array. Since each element is actually a reference to a single dimensional array of integer primitives a conversion from typeObject to an int array is legal.

Arguments Question 1
class GFC401 { static int m1(int x) {return ++x;} public static void main (String[] args) { int x = 1; int y = m1(x); System.out.println(x + "," + y); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,1 Prints: 1,2 Prints: 2,1 Prints: 2,2 Run-time error Compile-time error None of the above

Resposta:

1b

Primitive arguments are passed by value. The method m1 increments the Prints: parameter x, and the result is returned. The local 1,2 variable x of main remains unchanged.

Question 2
class GRC10 { public static void main (String[] s) { System.out.print(s[1] + s[2] + s[3]); }} java GRC10 A B C D E F

What is the result of attempting to compile and run the program using the specified command line?
a. b. c. d. e. f. Prints: ABC Prints: BCD Prints: CDE Prints: A B C Prints: B C D Prints: C D E

g. Compile-time error h. Run-time error i. None of the above


Resposta:

The index for the first element of an array is zero so the first argument 2 b Prints:BCD printed by this program is the second argument on the command line following the name of the class.

Question 3
class GFC402 { static int x=1; void m1(int i) {x++; i++;} public static void main (String[] args) { int y=3; m1(y); System.out.println(x + "," + y); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,3 Prints: 2,3 Prints: 1,4 Prints: 2,4 Run-time error Compile-time error None of the above

Resposta:

3f

Compiletime error

Method m1 is an instance method, and must be invoked with reference to an instance of type GFC402. Method m1 can not be invoked from a static context.

Question 4
class GFC403 { private static int x=1; static void m1(int i) {x++; i++;} public static void main (String[] args) { int y=3; m1(y); System.out.println(x + "," + y); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g.

Prints: 1,3 Prints: 2,3 Prints: 1,4 Prints: 2,4 Run-time error Compile-time error None of the above

Resposta:

Variables of primitive type are passed to methods by value: Only a copy of the value of the variable is passed to the method. While the method works with a local copy of the variable, the original variable remains unchanged Prints: by any actions performed on the method parameter. For that reason, 4b method m1 does not change the value of the variable y in 2,3 the main method. However, method m1does have direct access to the class variable x and the content of the class variable is modified by method m1.

Question 5
class GFC404 { private static int x=1; static void m1(int x, int y) {x++; y++;} public static void main (String[] args) { int y=3; m1(x, y); System.out.println(x + "," + y); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,3 Prints: 2,3 Prints: 1,4 Prints: 2,4 Run-time error Compile-time error None of the above

Resposta:

Variables of primitive type are passed to methods by value: Only a copy of the value of the variable is passed to the method. While the method works Prints: with a local copy of the variable, the original variable remains unchanged 5a by any actions performed on the method parameter. For that reason, 1,3 method m1 does not change the contents of the variable y in the main method or the class variable x.

Question 6
class GFC301 { private String name; public GFC301(String name) {this.name = name;} public void setName(String name) {this.name = name;} public String getName() {return name;} public static void m1(GFC301 r1, GFC301 r2) { r1.setName("Bird"); r2 = r1; } public static void main (String[] args) { GFC301 pet1 = new GFC301("Dog"); GFC301 pet2 = new GFC301("Cat"); m1(pet1,pet2); System.out.println(pet1.getName() + "," + pet2.getName()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: Dog,Cat Prints: Dog,Bird Prints: Bird,Cat Prints: Bird,Bird Run-time error Compile-time error None of the above

Resposta:

The method m1 is invoked by the method invocation expression m1(pet1,pet2). The value of the reference variable denoted by the argument pet1 is used to initialize the method parameter r1. Inside of method m1, the method invocation expression r1.setName("Bird") uses the copy of the value of the argument pet1 to assign a new name to the instance of GFC301 that is referenced by the local variable pet1 in the main method. Generally Prints: speaking, a reference parameter can be used to invoke methods on the 6c Bird,Cat referenced object and change the state of the object to the extent provided by the object's methods. The method invocation expression m1(pet1,pet2) has a second argument pet2, and the value of pet2 is used to initialize the method parameterr2. Inside of method m1, the assignment expression r2 = r1 changes the value of the method parameter r2; but the local variable of the main method denoted by the argument pet2 appearing in the method invocation expression m1(pet1,pet2) remains unchanged.

Question 7
class GFC303 { private String name; public GFC303(String name) {this.name = name;} public void setName(String name) {this.name = name;} public String getName() {return name;} public static void m1(GFC303 pet1, GFC303 pet2) { pet1 = new GFC303("Fish"); pet2 = null; } public static void main (String[] args) { GFC303 pet1 = new GFC303("Dog"); GFC303 pet2 = new GFC303("Cat"); m1(pet1,pet2); System.out.println(pet1.getName() + "," + pet2.getName()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: Dog,Cat Prints: Dog,Fish Prints: Fish,Cat Prints: Fish,Fish Compile-time error Run-time error None of the above

Resposta:

7a

Prints: Dog,Cat

The method m1 is invoked by the method invocation expression m1(pet1,pet2). A copy of the reference argument pet1 is assigned to the method parameter pet1. Inside the body of methodm1, the assignment expression pet1 = new GFC303("Fish") assigns a reference to a new instance of GFC303 to the method parameter pet1; but the argument pet1 that appears in the method invocation expression m1(pet1,pet2) and the local variable pet1 that is declared in the main method remain unchanged. The method invocation expression m1(pet1,pet2) has a second argument pet2, and a copy of pet2 is assigned to the method parameter pet2. Inside of method m1, the assignment expression pet2 = null changes the value of the method parameter pet2; but the argument pet2 appearing in the method invocation expression remains unchanged in the main method.

Question 8
class GFC304 { static void m1(int[] i1, int[] i2) {

int[] i3 = i1; i1 = i2; i2 = i3; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,1 Prints: 1,3 Prints: 3,1 Prints: 3,3 Run-time error Compile-time error None of the above

Resposta:

The method m1 is invoked by the method invocation expression m1(i1, i2). The argument i1 denotes a local variable of type int[] that is declared in the main method. The value of the argument is a reference to the array, and the argument value is used to initialize the method parameter i1 of method m1. Inside the body of m1, the expression i1 = Prints: i2 sets the value of parameteri1 to the value of parameter i2, but the 8b 1,3 change in the value of the parameter i1 does not change the original argument value or the local variable i1 of the main method that the argument denotes. Similarly, the assignment expression i2 = i3 in method m1 does not change the value of the local variable i1 declared in the main method.

Question 9
class GFC305 { static void m1(int[] i1, int[] i2) { int i = i1[0]; i1[0] = i2[0]; i2[0] = i; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: 1,1 Prints: 1,3 Prints: 3,1 Prints: 3,3

e. Run-time error f. Compile-time error g. None of the above


Resposta:

Method m1 is not able to change the value of the local variables that are Prints: declared in the main method and serve as the arguments in the method 9c 3,1 invocation expression. However, method m1 is able to modify the contents of the arrays that are referenced by the method parameters.

Question 10
class GFC306 { static int[] i1 = {1}, i2 = {3}; static void m1(int[] i1) { int[] i3 = i1; i1 = i2; i2 = i3; } public static void main (String[] args) { m1(i1); System.out.print(i1[0] + "," + i2[0]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,1 Prints: 1,3 Prints: 3,1 Prints: 3,3 Run-time error Compile-time error None of the above

Resposta:

The method m1 is invoked by the method invocation expression m1(i1). The argument i1 denotes the static member variable i1. Inside the declaration of method m1, the method parameter i1shadows the static member variable i1. The assignment expression i1 = i2 assigns the value of the member variable i2 to the Prints: method parameter i1, but the member variable i1 remains unchanged. 10 a Inside of method m1, the member variable i2 is not shadowed; so the 1,1 assignment expression i2 = i3 assigns the reference value contained by the method local variable i3 to the member variable i2. This question demonstrates that argument values are passed to method parameters by value, and the method parameter is only a copy of the argument value. A change made to the method parameter does not change the value of any variable that is shadowed by the parameter and does not change the value

of the argument appearing in the method invocation expression.

Question 11
class GFC307 { static void m1(int[] i1, int[] i2) { i1 = i2 = null; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,0 Prints: 1,1 Prints: 1,3 Prints: 3,1 Prints: null,null Run-time error Compile-time error None of the above

Resposta:

11 c

Although the reference parameters i1 and i2 are reassigned inside Prints: of m1, the change has no impact outside of m1. Array references are 1,3 passed by value: the invoked method gets a copy of the array reference.

Question 12
class GFC308 { int[] i1 = {1}, i2 = {3}; void m1() { m2(i1, i2); System.out.print(i1[0] + "," + i2[0]); } void m2(int[] i1, int[] i2) { int[] i3 = i1; this.i1 = i2; this.i2 = i3; } public static void main (String[] args) { new GFC308().m1(); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g. h.

Prints: 0,0 Prints: 1,1 Prints: 1,3 Prints: 3,1 Prints: null,null Run-time error Compile-time error None of the above

Resposta:

12 d

Prints: 3,1

Inside of method m2, the local variables i1 and i2 remain unchanged while the shadowed instance variables are changed.

Declarations and Access Control Question 1


package com.dan.chisholm; public class A { public void m1() {System.out.print("A.m1, ");} protected void m2() {System.out.print("A.m2, ");} private void m3() {System.out.print("A.m3, ");} void m4() {System.out.print("A.m4, ");} } class B { public static void main(String[] args) { A a = new A(); a.m1(); // 1 a.m2(); // 2 a.m3(); // 3 a.m4(); // 4 }}

Assume that the code appears in a single file named A.java. What is the result of attempting to compile and run the program?
a. b. c. d. e. f. Prints: A.m1, A.m2, A.m3, A.m4, Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. None of the above

Resposta:

1d

Compile-time Both class A and B are declared in the same package, so class B has error at 3. access to the public, protected, and package access methods

of class A.

Question 2
class A {A(int i) {}} class B extends A {} // 1 // 2

Which of the following statements are true?


a. b. c. d. The compiler attempts to create a default constructor for class A. The compiler attempts to create a default constructor for class B. Compile-time error at 1. Compile-time error at 2.

Resposta:

If no constructor is declared explicitly, then the compiler will implicitly create a default constructor that accepts no parameters, has no throws clause, and invokes its superclass constructor. Since class A has an explicitly The compiler declared constructor, the compiler will not create an attempts to create a b 2 default constructor for implicit default constructor. Class B does not have an d class B. Compile-time explicit constructor declaration, so the compiler attempts to error at 2. create a default constructor. Since class A does not have a no-parameter constructor, the attempt by class B to invoke the no parameter constructor of Awould fail. As a result, a compiler error is generated at marker 2.

Question 3
Which of the following modifiers can be applied to a constructor?
a. b. c. d. e. f. private abstract final volatile native None of the above.

Resposta:

Constructors are not inherited and can not be overridden, so there is no 3 a private need for the final modifier in a constructor declaration. Furthermore, an abstract constructor would be useless, since it could never be

implemented. The volatile modifier can be applied to a field, but not to a constructor. Native constructors are not permitted, because it would be difficult for Java to verify that the native constructor properly invokes the superclass constructor.

Question 4
Which of the following modifiers can be applied to the declaration of a field?
a. b. c. d. e. abstract final private protected public

Resposta:

A field is a class member. A static field is sometimes called a class variable. A nonstatic field is sometimes called an instance b variable. A variable declaration that is immediately contained by a block such as a c method body is called a local variable. The final private protected pu access 4 d blic modifiers, private, protected and pu blic, can be applied to a field. e A final field can not have its value assigned more than once. The abstract modifier may be applied to methods but not to fields.

Question 5
Which of the following modifiers can not be applied to a method?
a. b. c. d. e. f. abstract private protected public volatile None of the above.

Resposta:

An abstract method declaration provides no method body. If one abstract method is appears within a class declaration, then the entire class must be declared abstractand the class can not be 5 e volatile instantiated. The access modifiers, private, protected and public, can be applied to a method. The field modifiers, transient andvolatile, are not applicable to method declarations.

Question 6
class JSC201 { static byte m1() { final char c1 = '\u0001'; return c1; } static byte m2(final char c2) {return c2;} public static void main(String[] args) { char c3 = '\u0003'; System.out.print(""+m1()+m2(c3)); }}

// 1 // 2 // 3

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 13 Prints: 4 Compile-time error at 1 Compile-time error at 2 Run-time error None of the above

Resposta:

Compile6 d time error at 2

There is a compile-time error at 2. The char type variable c2 is not a compile-time constant, so it can not be assigned to type byte without an explicit cast. The method parameterc2 is declared final, so the value of c2 can not be changed within method m2. The value of method parameter c2 is set at run time to the value of the argument that is provided whenm2 is invoked at line 3. For that reason, the method parameter c2 is not a compile-time constant. In method m2, the statement, "return c2;", is a return statement with an expression, c2. A compile-time error occurs if the type of the expression is not assignable to the declared result type of the method. The declared result type of method m2 is byte. The return statement attempts to return the value of the char type variable c2. If a char value is a compile-time constant, and if the value falls within the range of type byte, then the char value is

assignable to type byte. In method m2, variable c2 is not a compiletime constant, because the value of c2 is not known at compile time. Instead, the value of c2 is assigned at run time to the value of the argument. Since the char type variable c2 is not a compile-time constant, the value of variable c2 is not assignable to the return type of method m2 without an explicit cast. While the declaration of method m2 produces a compile-time error, the declaration of method m1 does not. The local variable c1 is declared final and the value is set at compile time; so c1 is a compile-time constant. The value \u0001 falls within the range of type byte; so the value of the compile-time constant c1 is assignable to the return type of method m1 without an explicit cast.

Question 7
Which of the following modifiers can be applied to a class that is not a nested class?
a. b. c. d. e. f. public protected private abstract static final

Resposta:

The access modifiers, protected and private, can be applied to a class that is a member of an enclosing class, but can not be applied to a local class or a class that is not nested inside another class. The static modifier can be applied to a class that is a member of an enclosing class, but can not a be applied to a local class or a class that is not 7 d public abstract final nested inside another class. The public modifier f can be applied to a top level class to allow the class to be accessed from outside of the package. The abstract modifier prevents the class from being instantiated. An abstract class may include zero, one or more abstract methods. The final modifier prevents a class from being extended.

Question 8
Which of the following techniques can be used to prevent the instantiation of a class by any code outside of the class?
a. b. c. d. e. Do not declare any constructors. Do not use a return statement in the constructor. Declare all constructors using the keyword void to indicate that nothing is returned. Declare all constructors using the private access modifier. None of the above.

Resposta:

Declare all constructors using 8d the privateaccess modifier.

If no constructors are declared explicitly; then the compiler will create one implicitly, and it will have the same access modifier as the class. The explicit declaration of any constructor will prevent the creation of a default constructor. If all constructors are declared private, then code outside of the class will not have access to the constructors and will not have the ability to create an instance of the class. Constructors do not return a value and constructor declarations do not include a return type, so the keyword void is not applicable to a constructor declaration.

Question 9
Which of the following modifiers can be applied to a constructor?
a. b. c. d. e. protected public static synchronized transient

Resposta:

Constructors can not be inherited, so an abstract constructor would be useless, since it could never be implemented. A static constructor a would also be useless--or nearly so--since it would be 9 protected public b unable to access the non-static members of the new instance. An object is not available to multiple threads during the construction process, so thesynchronized modifier would not provide

additional protection. The transient modifier can be applied to a field, but not a constructor.

Question 10
Which of the following modifiers can be applied to the declaration of a field?
a. b. c. d. e. static synchronized transient volatile native

Resposta:

A transient field is not part of the persistent state of an object. Transient fields are not serialized. Fields that are shared between threads may be a marked volatile to force each thread to 10 c static transient volatile reconcile its own working copy of the field d with the master copy stored in the main memory. The synchronized modifier may be applied to methods but not to fields.

Question 11
Which of the following modifiers can not be applied to a method?
a. b. c. d. e. f. final static synchronized transient native None of the above.

Resposta:

A final method can not be overridden. A static method is associated with a class, but not a particular instance of the class. A 11 d transient thread can not enter a synchronizedmethod without first acquiring a lock. The field

modifiers, transient and volatile, are not applicable to method declarations. A native method is implemented in platform-dependent code.

Question 12
class JSC202 { static byte m1() {final short s1 = 2; return s1;} static byte m2(final short s2) {return s2;} public static void main(String[] args) { short s3 = 4; System.out.print(""+m1()+m2(s3)); }} // 1 // 2 // 3

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 24 Prints: 6 Compile-time error at 1. Compile-time error at 2. Run-time error None of the above

Resposta:

Compile12 d time error at 2.

There is a compile-time error at 2. The short type variable s2 is not a compile-time constant, so it can not be assigned to type byte without an explicit cast. The method parameter s2 is declared final, so the value of s2 can not be changed within method m2. The value of method parameter s2 is set at run time to the value of the argument that is provided when m2 is invoked at line 3. For that reason, the method parameter s2 is not a compile-time constant. In method m2, the statement, "return s2;", is a returnstatement with an expression, s2. A compile-time error occurs if the type of the expression is not assignable to the declared result type of the method. The declared result type of method m2 is byte. The return statement attempts to return the value of the short type variable s2. If a short value is a compiletime constant, and if the value falls within the range of type byte, then the short value is assignable to type byte without an explicit cast. In method m2, variable s2 is not a compile-time constant, because the value ofs2 is not known at compile time. Instead, the value of s2 is assigned at run time to the value of the argument. Since the short type variable s2 is not a compile-time constant, the value of variable s2 is not assignable to the return type of method m2 without an explicit cast. While the declaration of method m2 produces a compile-time error, the declaration of

method m1 does not. The local variable s1 is declared final and the value is set at compile time; so s1 is a compile-time constant. The value 2 falls within the range of type byte; so the value of the compile-time constant s1 is assignable to the return type of method m1 without an explicit cast.

Question 13
// Class A is declared in a file named A.java. package com.dan.chisholm; public class A { public void m1() {System.out.print("A.m1, ");} protected void m2() {System.out.print("A.m2, ");} private void m3() {System.out.print("A.m3, ");} void m4() {System.out.print("A.m4, ");} } // Class D is declared in a file named D.java. package com.dan.chisholm.other; import com.dan.chisholm.A; public class D { public static void main(String[] args) { A a = new A(); a.m1(); // 1 a.m2(); // 2 a.m3(); // 3 a.m4(); // 4 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: A.m1, A.m2, A.m3, A.m4, Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4.

Resposta:

Classes A and D are not declared in the same package, so Compile-time error class D does not have access to package access c at 2. Compile-time 13 d method, m4. Since class D does not extend class A, error at 3. Compilee class D does not have access to time error at 4. the protected method, m2, of class A.

Question 14
Which of the follow statements is true.

a. b. c. d. e. f.

An anonymous class can be declared abstract. A local class can be declared abstract. An abstract class can be instantiated. An abstract class is implicitly final. An abstract class must declare at least one abstract method. An abstract class can not extend a concrete class.

Resposta:

14 b

A local class can be declared abstract.

An anonymous class can not be extended; therefore, an anonymous class can not be declared abstract. A local class can be abstract. An abstract class can not be instantiated. If a class declaration contains an abstract method, then the class must also be declared abstract. A class can be declared abstract even if it does not contain an abstract method. An abstract class can never be declared final.

Question 15
Which of the following statements are true?
a. The compiler will create a default constructor if no other constructor is declared. b. The default constructor takes no arguments. c. If a class A has a direct superclass, then the default constructor of class A invokes the no-argument constructor of the superclass. d. The default constructor declares Exception in the throws clause. e. The default constructor is always given the private access modifier. f. The default constructor is always given the public modifier. g. The default constructor is always given default package access.
Resposta:

If no constructor is declared explicitly, then the compiler will implicitly insert a default The compiler will create a default constructor. The default constructor takes no constructor if no other constructor arguments. The primordial class Object has is declared. The default a no superclass; so the default constructor of constructor takes no arguments. If 15 b type Object does not invoke a superclass a class A has a direct superclass, c constructor. If a class A has a direct then the default constructor of superclass, then the default constructor of class A invokes the no-argument class A will invoke the no-argument constructor of the superclass. superclass constructor. It is unlikely that the real exam would try to trick you with a

question that requires you to know that the constructor of type Object does not invoke a superclass constructor. For the purposes of the real exam, it might be safer to overlook that particular unique feature of type Object. If a subclass constructor attempts to invoke the no-argument superclass constructor when none exists, then a compile-time error is generated. The access modifier implicitly assigned to the default constructor is the same as that assigned to the class. The default constructor does not have a throws clause. Consequently, a compiletime error is generated if the no-argument constructor of the superclass has a throws clause.

Question 16
Which of the following is used to prevent the serialization of a nonstatic field?
a. b. c. d. e. f. final protected synchronized transient volatile native

Resposta:

A transient field is not part of the persistent state of an object, 16 d transient so it is not serialized. A static field is also not part of the persistent state of an object, and also is not serialized.

Question 17
Which of the following modifiers can not be used with the abstract modifier in a method declaration?
a. final b. private c. protected

d. e. f. g.

public static synchronized native

Resposta:

A final or private met hod can not be overridden, and can not be abstract. An abstract method declaration provides no implementation of the a method, and all implementation details are b left to the overriding method in the subclass. final private static synchronized nat 1 e The synchronized modi 7 ive fier specifies an f implementation detail that g can be omitted from the declaration of an overriding method of a subclass, so it makes no sense to allow the use of the synchronized modifi er in an abstract method declaration.

Question 18
class JSC203 { static int m1(byte b) {return b;} // 1 static int m2(char c) {return c;} // 2 static int m3(long l) {return l;} // 3 public static void main(String[] args) { byte b = 1; char c = '\u0002'; long l = 4L; System.out.print(""+m1(b)+m2(c)+m3(l)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 124 Prints: 7 Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Run-time error

Resposta:

Compile18 e time error at 3.

There is a compile-time error at line 3. The long type variable, l, can not be assigned to type int without an explicit cast. The statement, "return l;", is a return statement with an expression, l. A compile-time error occurs if the type of the expression is not assignable to the declared result type of the method. The declared result type of the method, m3, is int. The type of the variable, l, is long, so an explicit cast is needed to perform the narrowing primitive conversion, "return (int)l;". The declarations of methods m1and m2 do not generate compile-time errors, because the types of the expressions contained in the return statements are assignable to type int. Widening conversions from typesbyte, char, or short to type int do not require an explicit cast.

Question 19
// Class A is declared in a file named A.java. package com.dan.chisholm; public class A { public void m1() {System.out.print("A.m1, ");} protected void m2() {System.out.print("A.m2, ");} private void m3() {System.out.print("A.m3, ");} void m4() {System.out.print("A.m4, ");} } // Class C is declared in a file named C.java. package com.dan.chisholm.other; import com.dan.chisholm.A; public class C extends A { public static void main(String[] args) { C c = new C(); c.m1(); // 1 c.m2(); // 2 c.m3(); // 3 c.m4(); // 4 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: A.m1, A.m2, A.m3, A.m4, Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4.

Resposta:

19

d Compile-time e error at

Class A and C are not declared in the same package; therefore, class C does not have access to package access method, m4.

3. Compile-time error at 4.

Since class C extends class A, class C does have access to the protected method, m2, of class A.

Question 20
public class A {int i1; void m1() {}}

Which of the following statements are true?


a. b. c. d. e. f. g. h. class A extends Object. Field i1 is implicitly public, because class A is public. Method m1 is implicitly public, because class A is public. The compiler will insert a default constructor implicitly. The default constructor has no throws clause. The default constructor of class A has package access. The default constructor accepts one parameter for each field in class A. The default constructor invokes the no-parameter constructor of the superclass.

Resposta:

a d 20 e h

Field i1 and m1 both have package access. When no constructor is declared class A extendsObject. The compiler explicitly the compiler will insert one implicitly. The implicitly declared will insert a default constructor implicitly. The default constructor has default constructor will have the same access privileges as the class. In this nothrows clause. The default case, the class is public, so the constructor invokes the no-parameter constructor of the superclass. default constructor is also public. The default constructor accepts no parameters and throws no exceptions.

Flow Control Question 1


class JMM102 { public static void main(String args[]) { for (int i = 0; i<5 ;i++) { switch(i) { case 0: System.out.print("v ");break; case 1: System.out.print("w "); case 2: System.out.print("x ");break; case 3: System.out.print("y "); case 4: System.out.print("z ");break; default: System.out.print("d "); }}}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: v w x y z Prints: v w x y z d Prints: v w x x y z z Prints: v w w x y y z d Prints: d d d d d d Run-time error Compile-time error None of the above

Resposta:

1c

Prints: v w x Cases one and three have no break statement, so the next case is xyzz also executed and x and z are printed twice.

Question 2
class JMM103 { public static void main(String args[]) { for (int i = 0; i < 5 ;i++) { switch(i) { 0: System.out.print("v ");break; 1: System.out.print("w "); 2: System.out.print("x ");break; 3: System.out.print("y "); 4: System.out.print("z ");break; }}}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: v w x y z Prints: v w x x y z z Prints: v w w x y y z Run-time error. Compile-time error. None of the above.

Resposta:

2 e Compile-time error.

The keyword, case, is missing from the case labels.

Question 3
class JMM107 { public static void main(String[] args) {

boolean b = true; if (b = false) {System.out.print("A"); } else if (b) {System.out.print("B"); } else {System.out.print("C");} }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: A Prints: B Prints: C Run-time error Compile-time error None of the above

Resposta:

The boolean type variable, b, is initialized to true. The boolean expression of the first if statement, b = false, is a simple assignment Prints: 3c expression that sets b to false. Always look carefully at the boolean C expression of an if statement to verify that the expected equality operator (==) has not been replaced by the simple assignment operator (=).

Question 4
class JMM108 { static boolean b; public static void main(String[] args) { if (b) {System.out.print("A"); } else if (b = false) {System.out.print("B"); } else if (b) {System.out.print("C"); } else if (!b) {System.out.print("D"); } else {System.out.print("E");} }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: A Prints: B Prints: C Prints: D Prints: E Run-time error Compile-time error None of the above

Resposta:

The expression, b = false, appears to be testing the value of b, but it is Prints: really setting the value of b. Always look carefully at the boolean 4d D expression of an if statement to verify that the expected equality operator (==) has not been replaced by the simple assignment operator (=).

Question 5
class JMM109 { public static void main(String[] args) { boolean b; if (b = false) {System.out.print("A"); } else if (b) {System.out.print("B"); } else if (!b) {System.out.print("C"); } else {System.out.print("D");} }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: A Prints: B Prints: C Prints: D Run-time error Compile-time error None of the above

Resposta:

The first if statement initializes the value of b. The expression, b = false, appears to be testing the value of b, but it is really setting the Prints: 5c value of b. Always look carefully at the boolean expression of C an if statement to verify that the expected equality operator (==) has not been replaced by the simple assignment operator (=).

Question 6
class JMM122 { public static void main (String[] args) { for (int i = 0; i < 4; i++) { switch (i) { case 0: System.out.print("A"); case 1: System.out.print("B"); case 2: System.out.print("C"); }}}}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g.

Prints: ABC Prints: ABCC Prints: CBA Prints: ABCBCC Run-time error Compile-time error None of the above

Resposta:

6d

Prints: ABCBCC

The switch statement does not contain any break statements. The first case falls through to the second. The second case falls through to the third. There is no default switch label, so nothing is printed when variable i is 3.

Question 7
class JMM123 { public static void main (String args[]) { int i = 0, j = 0, k = 0; label1: for (int h = 0; h < 6; h++) { label2: do { i++; k = h + i + j; switch (k) { default: break label1; case 1: continue label2; case 2: break; case 3: break label2; case 4: continue label2; case 5: continue label1; } } while (++j<5); } System.out.println(h + "," + i + "," + j); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 0,1,0 Prints: 0,2,1 Prints: 1,3,1 Prints: 2,4,1 Run-time error Compile-time error None of the above

Resposta:

7f

Compiletime error

The loop variable, h, is local to the for statement. The print statement causes a compile-time error, because it refers to the out-ofscope local variable, h. Always check for variables that are out-ofscope!

Question 8
class JMM103 { public static void main(String args[]) { byte b = -1; switch(b) { case 0: System.out.print("zero "); break; case 100: System.out.print("100 "); break; case 1000: System.out.print("1000 "); break; default: System.out.print("Default "); }}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: zero Prints: 100 Prints: 1000 Prints: Default Run-time error Compile-time error None of the above

Resposta:

The case constant expression, 1000, produces a compile-time error, because it exceeds the range of the switch expression type, byte. The type of a switch expression can bebyte, short, int or char. Compile- A constant expression is associated with each case label. 8f time error Each case constant expression must be assignable to the type of the switch expression. In this case, the switch expression, b, is of type byte; so the maximum positive value of each case constant expression is limited to the maximum byte value, 127.

Question 9
class JMM104 { public static void main (String args[]) { char c = 'b'; switch(c) { case 'a': System.out.print("1"); case 'b': System.out.print("2"); case 'c': System.out.print("3");

default: }}}

System.out.print("4");

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 3 Prints: 34 Prints: 234 Prints: 1234 Run-time error Compile-time error None of the above

Resposta:

9c

Prints: 234

No break statements appear inside the switch statement, so more than one case is processed.

Question 10
class JMM105 { public static void main(String args[]) { int x = 6; int success = 0; do { switch(x) { case 0: System.out.print("0"); x += 5; break; case 1: System.out.print("1"); x += 3; break; case 2: System.out.print("2"); x += 1; break; case 3: System.out.print("3"); success++; break; case 4: System.out.print("4"); x -= 1; break; case 5: System.out.print("5"); x -= 4; break; case 6: System.out.print("6"); x -= 5; break; } } while ((x != 3) || (success < 2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 60514233 Prints: 6152433 Prints: 61433 Prints: 6143 Run-time error Compile-time error

Resposta:

10 c

Prints: On the first pass through the loop, the value of x is 6, so 5 is subtracted 61433 from x. On the second pass, the value of x is 1, so 3 is added to x. On

the third pass, the value of x is 4, so 1 is subtracted from x. On the fourth pass, the value of x is 3, so the variable, success, is incremented from zero to one. On the final pass, the value of x is 3 and the variable, success, is incremented to the value, 2. The boolean expression of the do loop is now false, so control passes out of the loop.

Question 11
class JMM106 { public static void main(String args[]) { int x = -5; int success = 0; do { switch(x) { case 0: System.out.print("0"); x += 5; break; case 1: System.out.print("1"); x += 3; break; case 2: System.out.print("2"); x += 1; break; case 3: System.out.print("3"); success++; break; case 4: System.out.print("4"); x -= 1; break; case 5: System.out.print("5"); x -= 4; break; case 6: System.out.print("6"); x -= 5; break; default: x += x < 0 ? 2 : -2; } } while ((x != 3) || (success < 2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 60514233 Prints: 1433 Prints: 61433 Prints: 051433 Run-time error Compile-time error

Resposta:

On the first pass through the loop, the switch expression, x, has the value, -5. None of the case constants are matched, so the statement following the default label is executed causing the value of x to be set to Prints: -3. On the second pass, the default case of the switch statement is 11 b 1433 executed again, and two is again added to the value of x. The new value is -1. On the third pass, the value of x is again incremented, and the new value is +1. After that, the value of x is printed on each pass through the loop. For the last two passes, the value of x is 3.

Question 12

class JMM124 { public static void main(String args[]) { int k; for (int i=0, j=0; i<2; i++,j++) {System.out.print(i);} // 1 for (int i=0, k=0; i<2; i++,k++) {System.out.print(i);} // 2 for (int i=0, int j=0; i<2; i++,j++) {System.out.print(i);} // 3 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 012345 Prints: 010101 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Run-time error

Resposta:

Compile-time d error at line 12 e 2 Compile-time error at line 3

A compile-time error occurs at line 2 as a result of the attempt to shadow the method local variable, k, within the for-loop. A variable declared within the for-loop can not shadow a local variable of the enclosing method. At line 3, the declaration of variable j causes a compile-time error. The initialization part of a for statement may use a single local variable declaration statement to declare more than one local variable. Each of the new variables is declared in a comma separated list of variable declarators. In this program, the local variables should have been declared as follows: "int i=0, j=0;". Instead, the type of variable j has been incorrectly added to the declarator: "int i=0, int j=0;". The result is a compile-time error.

Question 13
class JMM125 { static int i; public static void main(String args[]) { for (i=1; i<3; i++) {System.out.print(i);} for (int i=1; i<3; i++) {System.out.print(i);} int i; for (i=0; i<2; i++) {System.out.print(i);} System.out.print(JMM125.i); }}

// // // //

1 2 3 4

What is the result of attempting to compile and run the program?


a. Prints: 1212010 b. Prints: 1212013

c. d. e. f. g.

Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 4 Run-time error None of the above

Resposta:

13 b

Prints: 1212013

A method local variable, i, is declared at line 3. At line 4, the initialization part of the for statement initializes the method local variable to the value zero. The for statement does not declare a new variable, i, so the method local variable is not shadowed within the loop. Suppose a local variable, v, is declared within a statement or block. Variable, v, can shadow a class variable or an instance variable of the same name, but a compile-time error is generated if v shadows a method local variable. Please note that a compile-time error is not generated if a local variable is shadowed within the declaration of a class that is nested within the scope of the local variable.

Question 14
class JMM126 { static int i; public static void main(String args[]) { for (i=1; i<3; i++) {System.out.print(i);} for (int i=1; i<3; i++) {System.out.print(i);} int i; for (int i=0; i<2; i++) {System.out.print(i);} System.out.print(JMM126.i); }}

// // // //

1 2 3 4

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1212010 Prints: 1212013 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 4 Run-time error None of the above

Resposta:

A method local variable, i, is declared at line 3. At line 4, the initialization part of the for statement attempts to shadow the Compile14 e time error at method local variable with a new variable that is intended to be local line 4 to the for statement. The result is a compile-time error. At line 2, a new variable, i, is declared within the for statement. That variable

shadows the class variable, but it does not shadow the method local variable declared at line 3. The scope of a method local variable begins with its own initializer--if present--and extends to the end of the method body. At line 2, the method local variable is not in scope, so shadowing does not occur. Suppose a local variable, v, is declared within a statement or block. Variable, v, can shadow a class variable or an instance variable of the same name, but a compile-time error is generated if v shadows a method local variable. Please note that a compile-time error is not generated if a local variable is shadowed within the declaration of a class that is nested within the scope of the local variable.

Question 15
class JMM101 { public static void main(String[] args) { int i = 0; while (i++ < args.length) { System.out.print(args[i]); }}} java JMM101 A B C D E F

What is the result of attempting to compile and run the program using the specified command line?
a. b. c. d. e. Prints: JMM101ABCDEF Prints: ABCDEF Compile-time error Run-time error None of the above

Resposta:

The index, i, is incremented before the array access expression is Run- evaluated, so the first element accessed is at index one instead of zero. The 15 d time arguments, BCDEF, are printed before error anArrayIndexOutOfBoundsException is thrown when the attempt is made to access an element beyond the end of the array.

Question 16
class JMM110 { public static void main (String[] args) { int j = 0; do for (int i = 0; i++ < 2;) System.out.print(i);

while (j++ < 2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: 0001 Prints: 012 Prints: 012012 Prints: 012345 Prints: 001122 Prints: 1112 Prints: 111222 Prints: 121212 Run-time error Compile-time error None of the above

Resposta:

Prints: 16 h 121212

This trick question has a for loop nested inside of a do loop. For each iteration, the values of i and j are as follows: (1,0)(2,0)(1,1)(2,1)(1,2)(2,2).

Question 17
class JMM111 { public static void main (String[] args) { int j = 0; for (int i = 0; i < 2; i++) do System.out.print(i); while (j++ < 2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0001 Prints: 012 Prints: 012012 Prints: 012345 Prints: 001122 Prints: 1112 Prints: 111222 Prints: 121212 Run-time error Compile-time error

k. None of the above


Resposta:

17 a

Prints: 0001

This trick question has a do-loop nested inside of a for-loop. For each iteration, the values of i and j are as follows: (0,0)(0,1)(0,2)(1,3).

Question 18
class JMM112 { public static void main (String[] args) { int j = 0; for (int i = 0; i++ < 2;) do System.out.print(i); while (j++ < 2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: 0001 Prints: 012 Prints: 012012 Prints: 012345 Prints: 001122 Prints: 1112 Prints: 111222 Prints: 121212 Run-time error Compile-time error None of the above

Resposta:

Prints: 18 f 1112

This trick question has a do-loop nested inside of a for-loop. For each iteration, the values of i and j are as follows: (1,0)(1,1)(1,2)(2,3).

Question 19
class JMM113 { public static void main (String[] args) { int i = 0, j = 0, k = 0; do while (i++ < 3) System.out.print(k++); while (j++ < 3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: 0001 Prints: 012 Prints: 012012 Prints: 012345 Prints: 001122 Prints: 1112 Prints: 111222 Prints: 121212 Run-time error Compile-time error None of the above

Resposta:

19 b

This trick question has a while-loop nested inside of a do-loop. For each Prints: iteration, the values of i, j and k are as 012 follows: (1,0,0)(2,0,1)(3,0,2).

Question 20
class JMM114 { public static void main (String[] args) { int i = 0, j = 0; while (i++ < 3) do System.out.print(j); while (j++ < 3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0001 Prints: 001122 Prints: 012012 Prints: 012345 Prints: 1112 Prints: 111222 Prints: 121212 Run-time error Compile-time error None of the above

Resposta:

20 d Prints:

This trick question has a do-loop nested inside of a while-loop. For

012345

each iteration, the values of i and j are as follows: (1,0)(1,1)(1,2)(1,3)(2,4)(3,5).

Question 21
class JMM115 { static int m1(String s, int i) { System.out.print(s + i); return i; } public static void main (String[] args) { int i = 0, j = 0, k = 0; do while (m1("i", ++i) < 2) System.out.print("k" + ++k); while (m1("j", ++j) < 2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: i1k1i2k2j1i3j2 Prints: i1k1i2k2j1i1k1i2k2j2 Prints: i1k1i2j1i3j2 Run-time error Compile-time error None of the above

Resposta:

21 c

Prints: i1k1i2j1i3j2

A while loop is nested inside of a do loop. The while loop iterates once during the first iteration of the do loop. The body of the while loop does not execute during the final iteration of the do loop.

Question 22
class JMM116 { static int m1(String s, int i) { System.out.print(s + i); return i; } public static void main (String[] args) { int j = 0; for (int i = m1("A",0); m1("B",i) < 2; m1("C",++i)) { m1("J",++j); } }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f.

Prints: A0B0C1J1B1C2J2B2 Prints: A0B0J1C1B1J2C2B2 Prints: A0B0J1C1A1B1J2C2A2B2 Run-time error Compile-time error None of the above

Resposta:

22 b

Prints: A0B0J1C1B1J2C2B2

The initialization statement, labeled A, is processed first. The boolean expression, labeled B, is processed before each iteration of the loop. The body of the loop is processed next followed by the update expression, labeled C.

Question 23
class JMM117 { public static void main (String[] args) { int i = 0, j = 9; do { i++; if (j-- < i++) {break;} } while (i < 5); System.out.print(i + "," + j); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 5,4 Prints: 6,3 Prints: 6,6 Prints: 7,2 Run-time error Compile-time error None of the above

Resposta:

Suppose the print statement, System.out.print("(" + i + "," + j + ")");, is inserted at the top of the loop. The output of the Prints: program would be as follows:(0,9)(2,8)(4,7)6,6. The variable, i, 23 c 6,6 is incremented twice with each pass through the loop. The variable, j, is decremented once with each pass. The loop terminates when ireaches six.

Question 24
class JMM118 { public static void main (String[] args) { int i = 0, j = 9; while (i++ <= j--) {i++; if (j < 5) break;} System.out.print(i + "," + j); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 4,7 Prints: 6,6 Prints: 7,2 Prints: 8,5 Prints: 9,4 Run-time error Compile-time error None of the above

Resposta:

Suppose the print statement, System.out.print("(" + i + "," + j + ")");, is inserted at the top of the loop. The output of the program would be as follows:(1,8)(3,7)(5,6)(7,5)9,4. The variable, i, is incremented twice with each pass through the loop. The Prints: 24 e variable, j, is decremented once with each pass. 9,4 The booleanexpression of the while loop, i++ <= j--, is false when i reaches 8 and j reaches 5. The value of i is subsequently incremented and j is decremented yielding 9 and 4 respectively. Those values are printed.

Question 25
class JMM119 { public static void main (String[] args) { int i = 0, j = 9; do { if (j < 4) {break;} else if (j-- < 7) {continue;} i++; } while (i++ < 7); System.out.print(i + "," + j); }}

What is the result of attempting to compile and run the program?


a. Prints: 4,7 b. Prints: 6,6

c. d. e. f. g. h. i.

Prints: 6,5 Prints: 6,4 Prints: 7,5 Prints: 8,4 Run-time error Compile-time error None of the above

Resposta:

Suppose the print statement, System.out.print("(" + i + "," + j + ")");, is inserted at the top of the loop. The output of the program would be as follows:(0,9)(2,8)(4,7)(6,6)(7,5)8,4. The initial value of j is 9. With each pass through the loop, the Prints: expression, j-- < 7, decrements j. The initial value of variable i is 0. 25 f 8,4 With each pass through the loop, the expression, i++ < 7, increments variable i. Inside the body of the loop, i is also incremented as long as j is greater than or equal to 7. When jis less than seven, variable i is no longer incremented inside the body of the loop, but it is still incremented by the expression, i++ < 7.

Question 26
class JMM120 { public static void main (String args[]) { int i = 0, j = 0, k = 0; label1: for (;;) { i++; label2: do { k = i + j; switch (k) { case 0: continue label2; case 1: continue label1; case 2: break; case 3: break label2; case 4: break label1; default: break label1; } } while (++j<5); } System.out.println(i + "," + j); }}

What is the result of attempting to compile and run the program?


a. Prints: 2,1 b. Prints: 2,2 c. Prints: 3,1

d. e. f. g. h.

Prints: 3,2 Prints: 3,3 Run-time error Compile-time error None of the above

Resposta:

Suppose the print statement, System.out.print("("+i+","+j+","+k+")");, is inserted before the switch statement. The output of the program would be as follows: (1,0,1)(2,0,2)(2,1,3)(3,1,4)3,1. On the first iteration, case 1 is processed. The "continue label1;" statement causes control to go directly to the top of the for-loop following the label, label1. The boolean expression of the do-loop is not processed. Prints: On the second iteration, case 2 is processed. The break statement 26 c 3,1 causes the switch statement to complete, and control passes to the boolean expression of the do-loop. On the third iteration, case 3 is processed. The break with label statement, "break label2;", completes abruptly; and the do-loop completes abruptly without processing the loop expression, ++j<5, so j is not incremented. On the fourth iteration, case4 is processed. The break with label statement, "break label1;", completes abruptly, and the for-loop completes abruptly.

Question 27
class JMM121 { public static void main (String args[]) { int h = 0, i = 0, j = 0, k = 0; label1: for (;;) { h++; label2: do { i++; k = h + i + j; switch (k) { default: break label1; case 1: continue label1; case 2: break; case 3: break label2; case 4: continue label2; case 5: continue label1; } } while (++j < 5); } System.out.println(h + "," + i + "," + j); }}

What is the result of attempting to compile and run the program?


a. Prints: 1,2,3

b. c. d. e. f. g. h.

Prints: 1,3,2 Prints: 2,2,2 Prints: 2,4,1 Prints: 2,4,2 Run-time error Compile-time error None of the above

Resposta:

Suppose the print statement, System.out.print("("+h+","+i+","+j+","+k+") ");, is inserted before the switch statement. The output of the program would be as follows: (1,1,0,2)(1,2,1,4)(1,3,2,6)1,3,2. Three iterations of the loop are executed. On the first iteration, the switch expression, k, matches the caseconstant, 2. The Prints subsequent break statement is executed and the switch statement 2 b : 7 completes normally. On the second iteration, the switch expression 1,3,2 matches the caseconstant, 4; and the subsequent continue statement causes control to pass to the loop-continuation point of the do statement where the expression, ++j < 5, is evaluated and found to be true. On the final iteration, the switch expression does not match any case constant; so the break statement following the default label is processed.

Exception Handling Question 1


class A { public static void main (String[] args) { Error error = new Error(); Exception exception = new Exception(); System.out.print((exception instanceof Throwable) + ","); System.out.print(error instanceof Throwable); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

1 d Prints: true,true Both Error and Exception are subclasses of Throwable.

Question 2
class A {A() throws Exception {}} // 1 class B extends A {B() throws Exception {}} // 2 class C extends A {C() {}} // 3

Which of the following statements are true?


a. b. c. d. class A extends Object. Compile-time error at 1. Compile-time error at 2. Compile-time error at 3.

Resposta:

class A extends a Object. Compiled time error at 3.

The constructors for class B and class C both invoke the constructor for A. The constructor for class A declares Exception in the throws clause. Since the constructors for B and C invoke the constructor for A, it is necessary to declare Exception in the throws clauses of B and C. A compile-time error is generated at marker 3, because the constructor does not declareException in the throws clause.

Question 3
class A { public static void main (String[] args) { Object error = new Error(); Object runtimeException = new RuntimeException(); System.out.print((error instanceof Exception) + ","); System.out.print(runtimeException instanceof Exception); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error

f. Run-time error g. None of the above


Resposta:

Prints: 3b false,true

Error is a direct subclass of Throwable. RuntimeException is a direct subclass of Exception.

Question 4
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 1; try { try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;} } catch (Level1Exception e) { d++;} catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,0,0,1,0,0 Prints: 0,0,1,1,0,1 Prints: 0,1,1,1,0,1 Prints: 1,0,1,1,0,1 Prints: 1,1,1,1,0,1 Compile-time error Run-time error None of the above

Resposta:

4b

Prints: 0,0,1,1,0,1

The nested catch clause is able to catch a Level2Exception or any subclass of it. The switch statement throws a Level1Exception that can not be caught by the

nested catchclause; so the nested finally block is executed as control passes to the first of the two outer catch clauses. The outer finally block is executed as control passes out of the trystatement.

Question 5
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 2; try { try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;} } catch (Level1Exception e) { d++;} catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,0,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,1 Prints: 1,1,1,0,0,1 Compile-time error Run-time error None of the above

Resposta:

5c

Prints: 0,1,1,0,0,1

The nested catch block is able to catch a Level2Exception or any subclass of it causing b to be incremented. Both of the finally blocks are then executed.

Question 6

class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 3; try { try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;} } catch (Level1Exception e) { d++;} catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 1,1,1,0,0,1 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,0,0,0,1 Prints: 0,0,1,0,0,1 Compile-time error Run-time error None of the above

Resposta:

6b

Prints: 0,1,1,0,0,1

The nested catch block is able to catch a Level2Exception or any subclass of it causing b to be incremented. Both of the finally blocks are then executed.

Question 7
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 4; try { try {

switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); case 4: throw new Exception(); } a++; } catch (Level2Exception e) {b++;} finally{c++;} } catch (Level1Exception e) { d++;} catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: 0,0,0,0,0,1 Prints: 0,0,0,0,1,0 Prints: 0,0,1,0,0,1 Prints: 0,0,1,0,1,1 Prints: 0,1,1,1,1,1 Prints: 1,1,1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

7d

Prints: 0,0,1,0,1,1

The nested catch clause is able to catch a Level2Exception or any subclass of it. The switch statement throws an Exception that can not be caught by the nested catch clause; so the nested finally block is executed as control passes to the second of the two outer catch clauses. The outer finally block is executed as control passes out of the try statement.

Question 8
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 5; try { try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception();

case 3: throw new Level3Exception(); case 4: throw new Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;} } catch (Level1Exception e) { d++;} catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 1,0,0,0,0,0 Prints: 1,0,1,0,0,1 Prints: 0,0,1,0,0,1 Prints: 1,1,1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

Prints: 8b 1,0,1,0,0,1

The switch statement does not throw an exception; so the switch completes normally. The subsequent statement increments the variable, a; and the try block completes normally. Both of the finally blocks are then executed.

Question 9
class ColorException extends Exception {} class WhiteException extends ColorException {} class White { void m1() throws ColorException {throw new WhiteException();} void m2() throws WhiteException {} public static void main (String[] args) { White white = new White(); int a,b,d,f; a = b = d = f = 0; try {white.m1(); a++;} catch (ColorException e) {b++;} try {white.m2(); d++;} catch (WhiteException e) {f++;} System.out.print(a+","+b+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: 0,1,0,0 Prints: 1,1,0,0 Prints: 0,1,1,0 Prints: 1,1,1,0

e. f. g. h.

Prints: 1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

9c

Prints: 0,1,1,0

The first try block contains two statements. The first invokes method m1, and the subsequent statement contains a post increment expression with the variable, a, as the operand. Method m1throws a WhiteException exception, so variable a is not incremented as control passes to the catch block where b is incremented. The throws clause of m1 declares aColorException, so the body may throw a ColorException or any subclass of ColorException. The second try block also contains two statements. The first invokes methodm2, and the subsequent statement contains a post increment expression with the variable, d, as the operand. Method m2 does not throw an exception, so d is incremented, and the try block completes normally. Although the throws clause of m2 declares a WhiteException, there is no requirement to throw any exception.

Question 10
class ColorException extends Exception {} class WhiteException extends ColorException {} class White { void m1() throws ColorException {throw new ColorException();} void m2() throws WhiteException {throw new ColorException();} public static void main (String[] args) { White white = new White(); int a,b,d,f; a = b = d = f = 0; try {white.m1(); a++;} catch (ColorException e) {b++;} try {white.m2(); d++;} catch (WhiteException e) {f++;} System.out.print(a+","+b+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

The throws clause of White.m2 declares a WhiteException, Compile- so the body of m2 may throw a WhiteException or any subclass 10 f time error of WhiteException. Instead, the body of m2throws a superclass of WhiteException. The result is a compile-time error.

Question 11
class ColorException extends Exception {} class WhiteException extends ColorException {} class White { void m1() throws ColorException {throw new ColorException();} void m2() throws WhiteException {throw new WhiteException();} public static void main (String[] args) { White white = new White(); int a,b,d,f; a = b = d = f = 0; try {white.m1(); a++;} catch (WhiteException e) {b++;} try {white.m2(); d++;} catch (WhiteException e) {f++;} System.out.print(a+","+b+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

11 f

Compiletime error

The throws clause of White.m1 declares a ColorException, but the catch clause in the main method catches only a subclass of ColorException. The result is a compile-time error.

Question 12
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Brown { public static void main(String args[]) { int a, b, c, d, f; a = b = c = d = f = 0; int x = 1;

try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level3Exception e) {b++;} catch (Level2Exception e) {c++;} catch (Level1Exception e) {d++;} finally {f++;} System.out.print(a+","+b+","+c+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1 Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error None of the above

Resposta:

The first catch clause has a parameter e of type Level3Exception, so the first catch clause is able to catch any exception type that is assignable to type Level3Exception. SinceLevel2Exception is the superclass of Level3Exception, an instance of Level2Exception is not assignable to a catch clause parameter of type Level3Exception. Similarly, Level1Exception is also a superclass of Level3Exception, so an instance of Level1Exception is not assignable to a catch clause parameter of typeLevel3Exception. The only exception type that can be caught Prints: 12 a by the first catch clause is a Level3Exception. The 0,0,0,1,1 second catch clause has a parameter e of typeLevel2Exception, so the second catch clause is able to catch a Level2Exception. The Level1Exception is the superclass of Level2Exception. An instance ofLevel1Exception is not assignable to a catch clause parameter of type Level2Exception, so the second catch clause can not catch a Level1Exception. Since aLevel3Exception is a subclass of Level2Exception an exception of type Level3Exception is assignable to a catch clause parameter type Level2Exception. All exceptions of type Level3Exception will be caught by the

first catch clause, so the second catch clause in this program will not have an opportunity to catch a Level3Exception. The third catch clause has a parameter e of type Level1Exception, so the third catch clause is able to catch a Level1Exception. The exceptions of type Level2Exceptionand Level3Exception are assignable to the catch clause parameter of the third catch clause, but the exceptions of those subclass types will be caught by the first two catch clauses. Theswitch statement throws a Level1Exception. The try block completes abruptly as control passes to the third catch block where d is incremented. The finally block is also executed, so f is incremented.

Question 13
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Brown { public static void main(String args[]) { int a, b, c, d, f; a = b = c = d = f = 0; int x = 2; try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level3Exception e) {b++;} catch (Level2Exception e) {c++;} catch (Level1Exception e) {d++;} finally {f++;} System.out.print(a+","+b+","+c+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1 Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error None of the above

Resposta:

13 e

Prints: 0,0,1,0,1

The first catch block is able to catch a Level3Exception or any subclass of Level3Exception. The second catch block is able to catch a Level2Exception or any subclass of Level2Exception. The switch statement throws a Level2Exception. The try block completes abruptly as control passes to the second catch block where c is incremented. The finally block is also executed, so f is incremented.

Question 14
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Brown { public static void main(String args[]) { int a, b, c, d, f; a = b = c = d = f = 0; int x = 4; try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level3Exception e) {b++;} catch (Level2Exception e) {c++;} catch (Level1Exception e) {d++;} finally {f++;} System.out.print(a+","+b+","+c+","+d+","+f); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1 Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error None of the above

Resposta:

Prints: 14 g 1,0,0,0,1

The switch statement does not throw an exception; so the switch completes normally. The subsequent statement increments the variable, a; and the try block completes normally. Thefinally block is also executed, so f is incremented.

Question 15
class ColorException extends Exception {} class WhiteException extends ColorException {} abstract class Color { abstract void m1() throws ColorException; } class White extends Color { void m1() throws WhiteException {throw new WhiteException();} public static void main (String[] args) { White white = new White(); int a,b,c; a = b = c = 0; try {white.m1(); a++;} catch (WhiteException e) {b++;} finally {c++;} System.out.print(a+","+b+","+c); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: 0,0,0 Prints: 0,0,1 Prints: 0,1,0 Prints: 0,1,1 Prints: 1,0,0 Prints: 1,0,1 Prints: 1,1,0 Prints: 1,1,1 Compile-time error Run-time error None of the above

Resposta:

The try block contains two statements. The first invokes method m1, and the subsequent statement contains a post increment expression with the variable, a, as the operand. Method m1 throws aWhiteException exception, so variable a is not incremented as Prints: 15 d control passes to the catch block where b is incremented. 0,1,1 Although Color.m1 declares a ColorException in thethrows clause, a subclass of Color is free to declare only a subclass of ColorException in the throws clause of the overriding method.

Question 16

class RedException extends Exception {} class BlueException extends Exception {} class White { void m1() throws RedException {throw new RedException();} public static void main (String[] args) { White white = new White(); int a,b,c,d; a = b = c = d = 0; try {white.m1(); a++;} catch (RedException e) {b++;} catch (BlueException e) {c++;} finally {d++;} System.out.print(a+","+b+","+c+","+d); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error None of the above

Resposta:

Compile16 f time error

A compile-time error is generated, because the second catch clause attempts to catch an exception that is never thrown in the try block.

Question 17
class Level1Exception extends Exception {} class Level2Exception extends Level1Exception {} class Level3Exception extends Level2Exception {} class Purple { public static void main(String args[]) { int a,b,c,d,f,g,x; a = b = c = d = f = g = 0; x = 1; try { throw new Level1Exception(); try { switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;} } catch (Level1Exception e) { d++;}

catch (Exception e) {f++;} finally {g++;} System.out.print(a+","+b+","+c+","+d+","+f+","+g); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: 1,1,1,0,0,1 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,0,0,0,1 Prints: 0,0,1,0,0,1 Compile-time error Run-time error None of the above

Resposta:

A throw statement is the first statement in the outer try block. A throw statement appearing in a try block causes control to pass Compile- out of the block. Consequently, statements can not be reached if they 17 f time error appear in the block after the throw statement. The switch statement that appears after the throw statement is unreachable and results in a compile-time error.

Interfaces Question 1
interface A { void m1(); public void m2(); protected void m3(); private void m4(); } // // // // 1 2 3 4

Compile-time errors are generated at which lines?


a. b. c. d. 1 2 3 4

Resposta:

c Methods declared within an interface are implicitly public. If no access 3 4 d modifier is included in the method declaration; then, the declaration is

implicitly public. An attempt to declare the method using a weaker access privilege, private or protected, results in a compile-time error.

Question 2
Which of the following statements is not true?
a. An interface that is declared within the body of a class or interface is known as a nested interface. b. A constant can be a member of an interface. c. A class declaration can be a member of an interface. d. If an interface is named in the implements clause of a class, then the class must implement all of the methods declared within the interface. e. None of the above.
Resposta:

This question asks which answer option is not true. Some true statements are as follows. An interface can be declared within an enclosing class or interface. The members of an interface can be constants, If an interface is named in abstract method declarations, class declarations or the implements clause of a interface declarations. If an interface is named in the class, then the class must 2d implements clause of a class, then the class must implement all of the implement all of the methods declared within the methods declared within the interface or the class must be declared abstract. The interface. untrue answer option did not mention that an abstract class is not required to implement any of the methods declared in an interface that is named in the implements clause of the class declaration.

Question 3
Which of the following statements are true?
a. An interface declaration can be a member of an interface. b. A method declared within an interface must have a body represented by empty curly braces. c. An interface can implement another interface. d. An abstract class that implements an interface must implement all abstract methods declared within the interface. e. An abstract method declaration can be a member of an interface.
Resposta:

An interface can be declared within an enclosing class or interface. The members of an interface can be constants, An interface declaration abstract method declarations, class declarations, or can be a member of an interface declarations. The body of a method declared a interface. An abstract within an interface is a semicolon. An interface can 3 e method declaration can extend another interface, but can not implement an be a member of an interface. An abstractclass that has an interface, I1, interface. in its implements clause is not required to implement any of the methods declared within I1.

Question 4
Which of the following are modifiers that can be applied to an interface that is a member of a directly enclosing interface?
a. b. c. d. e. f. abstract implements final private protected public

Resposta:

All interfaces are implicitly abstract. The explicit application of the abstract modifier to an interface declaration is redundant and is strongly discouraged. The declaration of an interface within the body of an enclosing class or interface is called a member type declaration. Every member type declaration appearing within the body of a directly enclosing interface is a 4 abstract public implicitly static and public. Use of the access f modifiers, private or protected, is contradictory and results in a compile-time error. In contrast, the modifiers, private and protected, are applicable to a member type declaration appearing within the body of a directly enclosing class. The modifier, final, is never applicable to an interface. The keyword, implements, is not a modifier.

Question 5
Which of the following are modifiers that can be applied to an interface that is a member of a directly enclosing class?
a. abstract

b. c. d. e. f.

extends final private protected public

Resposta:

All interfaces are implicitly abstract. The explicit application of the modifier, abstract, to an interface is redundant and is strongly discouraged. The declaration of an interface within the body of an enclosing class or interface is called a member type declaration. a The private, protected and static modif d abstract private protected publ iers are applicable to a member type declaration 5 that appears in the body of a directly enclosing ic e class. In contrast, the f modifiers, private and protected, are not applicable to a member type declaration appearing within the body of a directly enclosing interface. The modifier, final, is never applicable to an interface. The keyword, extends, is not a modifier.

Question 6
Which of the following is a modifier that can be applied to an interface that is a member of a directly enclosing class or interface?
a. b. c. d. e. f. static synchronized transient volatile implements None of the above.

Resposta:

A member interface is always implicitly static. The modifier, static, can not be applied to an interface that is not a member interface. The modifier, synchronized, is applicable to a concrete implementation of a 6 a static method, but is not applicable to any interface. The modifiers, volatile and transient, are only applicable to variables that are members of a class. The keyword, implements, is not a modifier.

Question 7
Suppose that an interface, I1, is not a member of an enclosing class or interface. Which of the following modifiers can be applied to interface I1?
a. b. c. d. e. abstract final private protected public

Resposta:

The modifier, abstract, is applicable to an interface declaration, but its use is strongly discouraged; because every interface is implicitly abstract. An interface can not befinal. The modifiers, private and protected, are applicable only to an interface declaration that is a member of a a directly enclosing class declaration. If an interface is not a 7 abstract public e member of a directly enclosing class, or if the interface is a member of a directly enclosing interface; then, the modifiers, private and protected, are not applicable. If an interface is declare public, then the compiler will generate an error if the class is not stored in a file that has the same name as the interface plus the extension .java.

Question 8
Suppose that an interface, I1, is not a member of an enclosing class or interface. Which of the following modifiers can be applied to interface I1?
a. b. c. d. e. f. abstract public static synchronized transient volatile

Resposta:

The modifier, abstract, is applicable to an interface declaration, but its use is strongly discouraged; because every interface is implicitly abstract. If an interface is declarepublic, then the compiler will generate an error if the class is not stored in a file that has the same name as the interface a 8 abstract public plus the extension .java. The modifier, static, is applicable to a b member interface, but not to an interface that is not nested. The modifier, synchronized, is applicable only to concrete implementations of methods. The modifiers, transient and volatile, are applicable only to variables.

Question 9
Which of the following are modifiers that can be applied to a field declaration within an interface?
a. b. c. d. e. f. abstract const final private protected public

Resposta:

The modifier, abstract, is not applicable to a variable. All field declarations within an interface are implicitly public, static and final. Use of those modifiers is c 9 final public f redundant but legal. Although const is a Java keyword, it is not currently used by the Java programming language. An interface member can never be private orprotected.

Question 10
Which of the following is a modifier that can be applied to a field declaration within an interface?
a. b. c. d. e. static synchronized transient volatile None of the above.

Resposta:

All field declarations within an interface are implicitly public, static and final. Use of these modifiers is redundant but legal. A field that is declared final can not also be 10 a static declared volatile; so a field of an interface can not be declared volatile. The modifier, synchronized, is never applicable to a field.

Question 11
Which of the following modifiers can be applied to a class that is declared within an enclosing interface?
a. b. c. d. e. f. public protected private abstract static final

Resposta:

A class that is declared within an enclosing a interface is implicitly public and static; so the d 11 public abstract static final e access modifiers, protected and private, are f not applicable.

Question 12
interface A { int a = 1; public int b = 2; public static int c = 3; public static final int d = 4; } // // // // 1 2 3 4

Which field declaration results in a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

All field declarations within an interface are None of implicitly public, static and final. Use of these modifiers is 12 e the redundant but legal. No other modifiers can be applied to a field above declaration within an interface.

Question 13
interface A { protected int e = 5; private int f = 6; volatile int g = 7; transient int h = 8; public static final int d = 9; } // // // // // 1 2 3 4 5

Which of the field declarations does not result in a compile-time error?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resposta:

All field declarations within an interface are implicitly public, static and final. Use of these modifiers is redundant 13 e 5 but legal. No other modifiers can be applied to a field declaration within an interface.

Question 14
Which of the following are modifiers that can be applied to a method declaration within an interface?
a. b. c. d. e. abstract final private protected public

Resposta:

All methods declared within an interface are implicitly abstract and public. Although the abstract and public modifiers can legally be applied to a a 1 abstract publi method declaration in an interface, the usage is redundant and is 4 e c discouraged. An abstract method can not also be declared private, static, final, native orsynchroniz ed; so the same restriction applies to methods declared within an interface.

Question 15
Which of the following is a modifier that can be applied to a method declaration within an interface?
a. b. c. d. e. f. static synchronized transient volatile native None of the above

Resposta:

All methods declared within an interface are implicitly abstract and public. Although the abstract and public modifiers can legally be applied to a None method declaration in an interface, the usage is redundant and is 15 f of the discouraged. An abstract method can not also be above declared private, static, final, native orsynchronized; so the same restriction applies to methods declared within an interface. Transient and volatile are not method modifiers.

Question 16
interface A {void m1();} class B implements A {public void m1() {}} class C implements A {protected void m1() {}} class D implements A {private void m1() {}} class E implements A {void m1() {}} // // // // // 1 2 3 4 5

Compile-time errors are generated at which lines?


a. 1 b. 2

c. 3 d. 4 e. 5
Resposta:

Methods declared within an interface are implicitly public even if the c modifier, public, is omitted from the declaration. Within the body of a 16 d 3 4 5 class declaration, an attempt to implement the method using a weaker e access privilege, private, protected or package access, results in a compile-time error.

Question 17
interface A { void m1(); public void m2(); protected void m3(); private void m4(); abstract void m5(); } // // // // // 1 2 3 4 5

Compile-time errors are generated at which lines?


a. b. c. d. e. 1 2 3 4 5

Resposta:

All methods declared within an interface are implicitly abstract and public. Although c the abstract and public modifiers can legally be applied to a method 17 3 4 d declaration in an interface, the usage is redundant and is discouraged. Since all methods declared within an interface are implicitly public, a weaker access level can not be declared.

Question 18
interface A { final void m1(); synchronized void m2(); native void m3(); abstract void m4(); public void m5(); } // // // // // 1 2 3 4 5

Compile-time errors are generated at which lines?


a. b. c. d. e. 1 2 3 4 5

Resposta:

All methods declared within an interface are implicitly abstract and public. Although the abstract and public modifiers can legally be applied to a a 18 b 1 2 3 method declaration in an interface, the usage is redundant and is c discouraged. The final, synchronized and native modifiers can not appear in the declaration of anabstract method, and can not be applied to an abstract method declared within an interface.

Question 19
interface interface interface interface interface A B C D E {void main(String[] args);} {public void main(String[] args);} {public static void main(String[] args);} {protected void main(String[] args);} {private void main(String[] args);} // // // // // 1 2 3 4 5

Which interface declarations generate a Compile-time error?


a. b. c. d. e. 1 2 3 4 5

Resposta:

All methods declared within an interface are implicitly abstract and public. Although c the abstract and public modifiers can legally be applied to a 19 d 3 4 5 method declaration in an interface, the usage is redundant and is e discouraged. Since all methods declared within an interface are implicitly public, a weaker access level can not be declared.

Question 20
interface F {abstract void main(String[] args);} // 1

interface G {synchronized void main(String[] args);} interface H {final void main(String[] args);} interface I {native void main(String[] args);}

// 2 // 3 // 4

Which interface declaration does not generate a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

All methods declared within an interface are implicitly abstract. The final, synchronized and native modifiers can not appear in the 20 a 1 declaration of anabstract method, and can not be applied to an abstract method declared within an interface.

Question 21
interface A {String s1 = "A"; String m1();} interface B implements A {String s1 = "B"; String m1();} class C implements B { public String m1() {return s1;} public static void main(String[] args) { A a = new C(); System.out.print(a.m1()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: A Prints: B Compile-time error Run-time error None of the above

Resposta:

21 c

Compile-time In the declaration of interface B, the keyword, extends, has error been replaced by the keyword, implements.

Question 22
interface A {int i = 1; int m1();} interface B extends A {int i = 10; int m1();}

class C implements B { public int m1() {return ++i;} public static void main(String[] args) { System.out.print(new C().m1()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 2 Prints: 11 Compile-time error Run-time error None of the above

Resposta:

Compile22 c time error

Fields declared within an interface are implicitly public, final, and static. A compile-time error is generated in response to the attempt to increment the value of i.

Question 23
interface Z {void m1();} // 1 class A implements Z {void m1() {}} // 2 class B implements Z {public void m1() {}} // 3 abstract class C implements Z {public abstract void m1();} // 4

A Compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

All methods declared within an interface are implicitly abstract and public. Although the abstract and public modifiers can legally be applied to a method declaration in an interface, the usage is redundant and is discouraged. Methods declared within an interface are implicitly public even if the 23 b 2 modifier, public, is omitted from the declaration. Within the body of a class declaration, an attempt to implement the method using a weaker access privilege, private, protected or package access, results in a compiletime error. An abstract class that implements an interface is free to override any of the inherited method declarations with another abstract method declaration.

Question 24
interface Z {void m1();} // class D implements Z {public class E implements Z {public class G implements Z {public 1 final void m1() {}} // 2 synchronized void m1() {}} // 3 native void m1();} // 4

A Compile-time error is generated at which line?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

None 24 e of the above

All methods declared within an interface are implicitly abstract and public. Although the abstract and public modifiers can legally be applied to a method declaration within an interface, the usage is redundant and is discouraged. The modifiers, final, synchronized and native, can not appear in the declaration of anabstract method, but they can be added to an implementation of an abstract method.

Question 25
interface I10 {String name = "I10"; String interface I20 {String name = "I20"; String class C10 implements I10, I20 { public static void main(String[] args) { System.out.print(s10+","); System.out.print(s20+","); System.out.print(name); }} s10 = "I10.s10";} s20 = "I20.s20";} // 1 // 2 // 3 // 4

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: I10.s10,I20.s20,I10 Prints: I10.s10,I20.s20,I20 Prints: I10.s10,I20.s20, Prints: I10.s10,I20.s20,null Compile-time error at line 1 Compile-time error at line 2

g. h. i. j.

Compile-time error at line 3 Compile-time error at line 4 Run-time error None of the above

Resposta:

Class C10 inherits ambiguous declarations of the name field. As long as the field is not referenced as a member of class C10; then, Compile25 h time error at no compile-time error occurs. Line 4 generates the compile-time line 4 error, because it is the first to access the name field as a member of class C10.

Question 26
interface I10 {String name = "I10"; String interface I20 {String name = "I20"; String class C20 implements I10, I20 { // public static void main(String[] args) { System.out.print(I10.s10+","); // System.out.print(I20.s20+","); // System.out.print(I20.name); // }} s10 = "I10.s10";} s20 = "I20.s20";} 1 2 3 4

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: I10.s10,I20.s20,I10 Prints: I10.s10,I20.s20,I20 Prints: I10.s10,I20.s20, Prints: I10.s10,I20.s20,null Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4 Run-time error None of the above

Resposta:

26 b

Prints: I10.s10,I20.s20,I20

Class C20 inherits ambiguous declarations of the name field. As long as the field is not referenced as a member of class C20; then, no compile-time error occurs. Although line 4 may appear to generate the compile-time error it does not, because name is accessed directly as a member of interface I20. Therefore, the compiler does not encounter an ambiguity.

Inheritance Question 1
Which of the following statements are true?
a. A constructor can invoke another constructor of the same class using the alternate constructor invocation, "this(argumentListopt);". b. A constructor can invoke itself using the alternate constructor invocation, "this(argumentListopt);". c. The alternate constructor invocation, "this(argumentListopt);", can legally appear anywhere in the constructor body. d. A constructor can invoke the constructor of the direct superclass using the superclass constructor invocation, "super(argumentListopt);". e. The number of constructor invocations that may appear in any constructor body can equal but not exceed the number of alternate constructors declared in the same class. f. A constructor is not permitted to throw an exception.
Resposta:

If an alternate constructor invocation appears in the body of A constructor can invoke another constructor of the constructor, then it must be the same class using the alternate constructor the first statement. The same is a invocation,"this(argumentListopt);". A constructor can 1 true for a superclass constructor d invoke the constructor of the direct superclass invocation. A compile-time error using the superclass constructor is generated if a constructor invocation, "super(argumentListopt);". attempts to invoke itself either directly or indirectly.

Question 2
Suppose that the superclass constructor invocation, "super(argumentList );", appears explicitly in a subclass constructor. If a compile-time error is to be avoided then the arguments for the superclass constructor invocation, "super(argumentList );", can not refer to which of the following?
opt opt

a. b. c. d. e.

Static variables declared in this class or any superclass. Instance variables declared in this class or any superclass. Static methods declared in this class or any superclass. Instance methods declared in this class or any superclass. The keyword this.

f. The keyword super.


Resposta:

b d 2 e f

Instance variables declared in this class or any superclass. Instance methods declared in this class or any superclass. The keyword this. The keyword super.

If the superclass constructor invocation, "super(argumentListopt);", appears explicitly or implicitly, then it must be the first statement in the body of the constructor. Until the superclass constructor invocation runs to completion, no other statements are processed within the body of the constructor. The same is true of the constructors of any superclass. (Note: The primordial class, Object, does not have a superclass, so the constructors do not include a superclass constructor invocation statement.) Suppose class B is a subclass of A. The process of creating and initializing an instance of B includes the creation and initialization of an instance of the superclass A and an instance of the superclass Object. The superclass constructor invocation statement appearing in a constructor of B is invoked before the completion of the constructors of the superclasses A and Object. A superclass constructor invocation statement appearing in B can not refer to the non-static members of the superclasses, because the process of initializing those non-static superclass members is not complete when the superclass constructor invocation occurs in B. The same is true of the non-static members of B.

Question 3
class A {void m1(String s1) {}} class B extends A { void m1(String s1) {} // 1 void m1(boolean b) {} // 2 void m1(byte b) throws Exception {} // 3 String m1(short s) {return new String();} //4 private void m1(char c) {} // 5 protected void m1(int i) {} // 6 }

What is the result of attempting to compile the program?


a. b. c. d. Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4

e. Compile-time error at line 5 f. Compile-time error at line 6 g. None of the above


Resposta:

If a superclass method is not private and is accessible to code in a subclass, then any subclass method that has the same signature as the superclass method must also have the same return type. In other words, if a superclass method is overridden or hidden in a subclass, then the overriding or hiding subclass method must have the same return type as the superclass method. No such restriction applies to method overloading. If two methods share an overloaded method name but not the same parameter list, then the two methods need not have the same return type. Class A declares one method: The name is m1 and the single parameter is None of of type String. Class B extends A and declares six methods that 3 g the overload the name m1. The method, B.m1(String s1), overrides the above superclass method, A.m1(String s1). The overriding subclass method must have the same return type as the superclass method, but the methods that overload the name m1 are free to have different return types. An overriding subclass method is not permitted to throw any checked exception that is not listed or is not a subclass of any of those listed in the throws clause of the superclass method. No such restriction applies to method overloading. If two methods share an overloaded method name but not the same parameter list, then the two methods are free to have differing throws clauses.

Question 4
class A {void m1() {System.out.print("A.m1");}} class B extends A { void m1() {System.out.print("B.m1");} static void m1(String s) {System.out.print(s+",");} } class C { public static void main (String[] args) {B.m1("main"); new B().m1();} }

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: main,B.m1 Compile-time error Run-time error None of the above

Resposta:

4 a Prints:

Suppose a superclass method is not private and is accessible to code

main,B.m1

in a subclass. If the superclass method is declared static, then any subclass method sharing the same signature must also be declared static. Similarly, if the superclass method is not declared static, then any subclass method sharing the same signature must not be declaredstatic. The rules governing method overloading are different. If a superclass method is declared static, then any subclass method that overloads the superclass method is free to be declared static or non-static. Similarly, if a method is declared non-static, then any overloading method is free to be declared static or non-static. MethodB.m1() shares the same signature as the non-static superclass method A.m1(), so B.m1() must also be non-static. The method B.m1(String s) overloads the method name m1, but does not share the same signature with any superclass method; therefore, B.m1(String s) can be declared static even though the other methods of the same name are non-static.

Question 5
Which of the following are true statements?
a. The relationship between a class and its superclass is an example of a "has-a" relationship. b. The relationship between a class and its superclass is an example of an "is-a" relationship. c. The relationship between a class and an object referenced by a field within the class is an example of a "has-a" relationship. d. The relationship between a class and an object referenced by a field within the class is an example of an "is-a" relationship.
Resposta:

The relationship between a class and its superclass is an example of an "is-a" b relationship. The relationship between 5 c a class and an object referenced by a field within the class is an example of a "has-a" relationship.

Inheritance is an example of an "is-a" relationship, because the subclass "is-a" specialized type of the superclass. The relationship between a class and an object referenced by a field declared within the class is an example of a "has-a" relationship, because the class "has-a" object.

Question 6
class A {String s1 = "A.s1"; String s2 = "A.s2";} class B extends A { String s1 = "B.s1";

public static void main(String args[]) { B x = new B(); A y = (A)x; System.out.println(x.s1+" "+x.s2+" "+y.s1+" "+y.s2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: B.s1 A.s2 B.s1 A.s2 Prints: B.s1 A.s2 A.s1 A.s2 Prints: A.s1 A.s2 B.s1 A.s2 Prints: A.s1 A.s2 A.s1 A.s2 Run-time error Compile-time error None of the above

Resposta:

The variables of a subclass can hide the variables of a superclass or interface. The variable that is accessed is determined at compile-time Prints: based on the type of the reference--not the run-time type of the object. B.s1 A.s2 The two references x and y refer to the same instance of type B. The 6b A.s1 name x.s1 uses a reference of type B; so it refers to the A.s2 variable s1declared in class B. The name y.s1 uses a reference of type A; so it refers to the variable s1 declared in class A.

Question 7
class C { void printS1() {System.out.print("C.printS1 ");} static void printS2() {System.out.print("C.printS2 ");} } class D extends C { void printS1(){System.out.print("D.printS1 ");} void printS2() {System.out.print("D.printS2 ");} public static void main (String args[]) { C c = new D(); c.printS1(); c.printS2(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: C.printS1 C.printS2 Prints: C.printS1 D.printS2 Prints: D.printS1 C.printS2 Prints: D.printS1 D.printS2 Run-time error Compile-time error None of the above

Resposta:

Suppose a superclass method is not private and is accessible to code in a subclass. If the superclass method is declared static, then any subclass method sharing the same signature must also be Compile- declared static. Similarly, if the superclass method is declared non7f time error static, then any subclass method sharing the same signature must also be declared non-static. The attempted declaration of the non-static method D.printS2 generates a compile-time error; because the superclass method, C.printS2, is static.

Question 8
class E { void printS1(){System.out.print("E.printS1 ");} static void printS2() {System.out.print("E.printS2");} } class F extends E { void printS1(){System.out.print("F.printS1 ");} static void printS2() {System.out.print("F.printS2");} public static void main (String args[]) { E x = new F(); x.printS1(); x.printS2(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: E.printS1 E.printS2 Prints: E.printS1 F.printS2 Prints: F.printS1 E.printS2 Prints: F.printS1 F.printS2 Run-time error Compile-time error None of the above

Resposta:

Prints: 8 c F.printS1 E.printS2

A static method is selected based on the compile-time type of the reference--not the run-time type of the object. A non-static method is selected based on the run-time type of the object--not the compile-time type of the reference. Both method invocation expressions, x.printS1() and x.printS2(), use a reference of the superclass type, E, but the object is of the subclass type, F. The first of the two expressions invokes an instance method on an object of the subclass type; so the overriding subclass method is selected. The second invokes a static method using a reference of the superclass type; so the superclass method is selected.

Question 9

class P { static void printS1(){System.out.print("P.printS1 ");} void printS2() {System.out.print("P.printS2 ");} void printS1S2(){printS1();printS2();} } class Q extends P { static void printS1(){System.out.print("Q.printS1 ");} void printS2(){System.out.print("Q.printS2 ");} public static void main(String[] args) { new Q().printS1S2(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: P.printS1 P.printS2 Prints: P.printS1 Q.printS2 Prints: Q.printS1 P.printS2 Prints: Q.printS1 Q.printS2 Run-time error Compile-time error None of the above

Resposta:

Prints: 9 b P.printS1 Q.printS2

Suppose a method m1 is invoked using the method invocation expression m1(). If m1 is a static member of the class where the invocation expression occurs, then that is the implementation of the method that is invoked at run-time regardless of the run-time type of the object. If m1 is non-static, then the selected implementation is determined at run-time based on the run-time type of the object. The program invokes method printS1S2 on an instance of class Q. The body of method printS1S2 contains two method invocation expressions, printS1() and printS2(). Since method printS1 is static, the implementation declared in class P is invoked. Since printS2 is non-static and the run-time type of the object is Q, the invoked method is the one declared in class Q.

Question 10
class R { private void printS1(){System.out.print("R.printS1 ");} protected void printS2() {System.out.print("R.printS2 ");} protected void printS1S2(){printS1();printS2();} } class S extends R { private void printS1(){System.out.print("S.printS1 ");} protected void printS2(){System.out.print("S.printS2 ");} public static void main(String[] args) { new S().printS1S2(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: R.printS1 R.printS2 Prints: R.printS1 S.printS2 Prints: S.printS1 R.printS2 Prints: S.printS1 S.printS2 Run-time error Compile-time error None of the above

Resposta:

Prints: 10 b R.printS1 S.printS2

A private method of a superclass is not inherited by a subclass. Even if a subclass method has the same signature as a superclass method, the subclass method does not override the superclass method. Suppose a non-static method m1 is invoked using the method invocation expression m1(). If m1 is a private member of the class T where the invocation expression occurs, then the implementation in class T is selected at run-time regardless of the run-time type of the object. If the non-static method m1 is notprivate, then the selected implementation is determined at runtime based on the run-time type of the object. The program invokes the non-static method printS1S2 on an instance of class S, so the run-time type is S. The body of method R.printS1S2 contains two method invocation expressions, printS1() and printS2(). Since classR contains a private implementation of the instance method printS1, it is the implementation that is selected regardless of the run-time type of the object. Since printS2is not private and not static, the selected implementation of printS2 depends on the run-time type of the object. The method printS1S2 is invoked on an instance of class S; so the runtime type of the object is S, and the implementation of printS2 declared in class S is selected.

Question 11
class T { private int i1, i2; void printI1I2() {System.out.print("T, i1="+i1+", i2="+i2);} T(int i1, int i2) {this.i1=i1; this.i2=i2;} } class U extends T { private int i1, i2; void printI1I2() {System.out.print("U, i1="+i1+", i2="+i2);} U(int i1, int i2) {this.i1=i1; this.i2=i2;} public static void main(String[] args) { T t = new U(1,2); t.printI1I2(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: U, i1=1, i2=2 Prints: T, i1=1, i2=2 Prints: U, i1=null, i2=null Prints: T, i1=null, i2=null Run-time error Compile-time error None of the above

Resposta:

Compile11 f time error

The two-parameter constructor of U does not explicitly invoke the two-parameter constructor of T; therefore, the constructor of U will try to invoke a no-parameter constructor ofT, but none exists.

Question 12
interface I {String s1 = "I";} class A implements I {String s1 = "A";} class B extends A {String s1 = "B";} class C extends B { String s1 = "C"; void printIt() { System.out.print(((A)this).s1 + ((B)this).s1 + ((C)this).s1 + ((I)this).s1); } public static void main (String[] args) {new C().printIt();} }

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: ABCI Run-time error Compile-time error None of the above

Resposta:

Suppose that a class extends a superclass, X, or implements an interface, X. The field access Prints: 12 a expression ((X)this).hiddenField is used to access the hidden ABCI field,hiddenField, that is accessible within the superclass or interface, X.

Question 13

abstract class D {String s1 = "D"; String getS1() {return s1;}} class E extends D {String s1 = "E"; String getS1() {return s1;}} class F { public static void main (String[] s) { D x = new E(); System.out.print(x.s1 + x.getS1()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: DD Prints: DE Prints: ED Prints: EE Run-time error Compile-time error None of the above

Resposta:

At run-time, the actual field that is accessed depends on the compile-time type of the reference--not the run-time type of the object. The compiletime type of the reference x in the name x.s1 is D; so the selected field is the one declared in class D. A non-static method is selected based on Prints: the run-time type of the object--not the compile-time type of the 13 b DE reference. The same reference variable x is used in the method invocation expression x.getS1(), and the compile-time type is still D. At runtime, the actual type of the object is E; so the selected method is the one declared in class E.

Question 14
class A {static void m() {System.out.print("A");}} class B extends A {static void m() {System.out.print("B");}} class C extends B {static void m() {System.out.print("C");}} class D { public static void main(String[] args) { C c = new C(); c.m(); B b = c; b.m(); A a = b; a.m(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: AAA Prints: ABC Prints: CBA Prints: CCC Compile-time error Run-time error

g. None of the above


Resposta:

Class C extends B, and B extends A. The static method C.m hides method B.m, and B.m hides A.m. In the method invocation expression c.m(), the compile-time type of the reference c is C. A static method is invoked based on the compile-time type of the Prints: reference; so the method invocation expression c.m() invokes the 14 c CBA method mdeclared in class C. The compile-time type of the reference b is B; so the method invocation expression b.m() invokes the method m declared in class B. The compile-time type of the reference a is A; so the method invocation expression a.m() invokes the method m declared in class A.

Question 15
class A {String s1 = "A";} class B extends A {String s1 = "B";} class C extends B {String s1 = "C";} class D { static void m1(A x) {System.out.print(x.s1);} static void m1(B x) {System.out.print(x.s1);} static void m1(C x) {System.out.print(x.s1);} public static void main(String[] args) { A a; B b; C c; a = b = c = new C(); m1(a); m1(b); m1(c); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: AAA Prints: ABC Prints: CBA Prints: CCC Compile-time error Run-time error None of the above

Resposta:

In all three cases, the object passed to method m1 is an instance of class C; however, the type of the reference is different for each method. Prints: 15 b ABC Since fields are accessed based on the type of the reference, the value printed by each method is different even though the same instance is used for each method invocation.

Question 16
class Leg{} class Fur{} abstract class Pet { public abstract void eat(); public abstract void sleep(); } class Dog extends Pet { Leg leftFront = new Leg(), rightFront = new Leg(); Leg leftRear = new Leg(), rightRear = new Leg(); Fur fur = new Fur(); public Fur shed() {return fur;} public void eat() {} public void sleep() {} } class Cat extends Dog { public void ignoreOwner() {} public void climbTree() {} }

Which of the following statements is not a true statement?


a. A Cat object inherits an instance of Fur and four instances of Leg from the Dog superclass. b. A Cat object is able to sleep and eat. c. A Cat object is able to climb a tree. d. The relationship between Dog and Pet is an example of an appropriate use of inheritance. e. The relationship between Cat and Dog is an example of an appropriate use of inheritance. f. None of the above.
Resposta:

The relationship between Cat and Dog 16 e is an example of an appropriate use of inheritance.

An appropriate inheritance relationship includes a subclass that "is-a" special kind of the superclass. The relationship between the Dog subclass and the Pet superclass is an example of an appropriate inheritance relationship, because a Dog "is-a" Pet. The relationship between the Cat subclass and the Dog superclass is not an example of an appropriate use of inheritance, because a Cat is not a special kind of a Dog. The goal of the OO paradigm is to develop software models that are accurate and reusable. If the software model is not accurate, then it probably is not reusable and the goals of the OO paradigm are not achieved. Code reuse and maintenance becomes increasingly difficult when inheritance is used to model inappropriate relationships. For example, suppose that somebody implements a herdSheep method in the Dog class. The Cat subclass would inherit the method and suddenly each instance of Cat would acquire the

unwanted capability to make an attempt to herd sheep. It is difficult to imagine that a Cat would perform well in that role, so additional maintenance would be required to resolve the problem.

Question 17
class A { A() {System.out.print("CA ");} static {System.out.print("SA ");} } class B extends A { B() {System.out.print("CB ");} static {System.out.print("SB ");} public static void main (String[] args) {B b = new B();} }

What is the result of attempting to compile and run the above program?
a. b. c. d. e. f. g. Prints: SA CA SB CB Prints: SA SB CA CB Prints: SB SA CA CB Prints: SB CB SA CA Runtime Exception Compiler Error None of the above

Resposta:

The static initializer of the super class runs before the static initializer Prints: SA of the subclass. The body of the superclass constructor runs to 17 b SB CA completion before the body of the subclass constructor runs to CB completion.

Question 18
class A {String s1="A";} class B extends A {String s1="B";} class C extends B {String s1="C";} class D extends C { String s1="D"; void m1() { System.out.print(this.s1 + ","); System.out.print(((C)this).s1 + ","); System.out.print(((B)this).s1 + ","); System.out.print(((A)this).s1);

// // // //

1 2 3 4

} public static void main (String[] args) { new D().m1(); // 5 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: D,D,D,D Prints: D,C,B,A Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. Compile-time error at 5. Run-time error None of the above

Resposta:

A field of a superclass can be inherited by a subclass if the superclass field is not private and not hidden by a field declaration in the subclass and is accessible to code in the subclass. The field D.s1 hides C.s1, and C.s1 hides B.s1, and B.s1 hides A.s1. The keyword this serves as a reference to the object on which a method has been invoked. In the field access expression this.s1 appearing Prints: on line 1, the keyword this denotes a reference to the object of 18 b D,C,B,A type D on which method m1 has been invoked. In the field access expression ((C)this).s1 appearing on line 2, the reference denoted by the keyword this is cast from type D to type C. The field that is accessed at run-time depends on the compile-time type of the reference; so the field access expression ((C)this).s1 refers the the variable s1 declared in class C.

Question 19
class SuperA {String s1="SuperA";} class SuperB {String s1="SuperB";} class A extends SuperA { String s1="A"; class B extends SuperB { // 1 String s1="B"; void m1() { System.out.print(this.s1 + ","); // System.out.print(super.s1 + ","); // System.out.print(A.this.s1 + ","); // System.out.print(A.super.s1); // } } public static void main (String[] args) { new A().new B().m1(); // 6

2 3 4 5

}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: B,SuperB,B,SuperB Prints: B,SuperB,A,SuperA Compile-time error at 1. Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. Compile-time error at 5. Compile-time error at 6. Run-time error None of the above

Resposta:

19 b

Prints: B,SuperB,A,SuperA

The expression A.this.s1 is an example of a qualified this expression. It accesses the variable s1 declared in class A. The expression A.super.s1 is equivalent to((SuperA)A.this).s1. It accesses the variable s1 declared in class SuperA.

Question 20
class A {void m1() {System.out.print("A");}} class B extends A {void m1(){System.out.print("B");}} class C extends B {void m1() {System.out.print("C");}} class D extends C { void m1() {System.out.print("D");} void m2() { m1(); ((C)this).m1(); // 1 ((B)this).m1(); // 2 ((A)this).m1(); // 3 } public static void main (String[] args) { new D().m2(); // 4 }}

What is the result of attempting to compile and run the program?


a. Prints: DCBA b. Prints: DDDD c. Compile-time error at 1.

d. e. f. g. h.

Compile-time error at 2. Compile-time error at 3. Compile-time error at 4. Run-time error None of the above

Resposta:

20 b

Prints: DDDD

The instance method that is invoked depends on the run-time type of the object--not the compile-time type of the reference. In each case, the method m1 is invoked on an object of type D; so the implementation of m1 in type D is selected each time.

Question 21
class A {public void m1() {System.out.print("A1");}} class B extends A { public void m1() {System.out.print("B1");} public void m2() {System.out.print("B2");} } class C { public static void main(String[] args) { A a1 = new B(); a1.m1(); // 1 a1.m2(); // 2 ((B)a1).m1(); // 3 ((B)a1).m2(); // 4 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: A1B2B1B2 Prints: B1B2B1B2 Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Compile-time error at 4 Run-time error None of the above

Resposta:

The method invocation expression a1.m2() generates a compiletime error, because the named method, m2, is declared in class B, but Compilethe reference is of the superclass type,A. The reference a1 is of 21 d time error type A; so a1 is able to access only those methods that are declared in at 2 class A and subclass methods that override those of class A. Only one method,m1, is declared in A; so a reference of type A can be used to

invoke A.m1 or an overriding implementation of m1 that is declared in a subclass of A. Class B extends A and overrides method m1. A reference of type A can be used to invoke method m1 on an instance of type B. Class B declares an additional method, m2, that does not override a method of class A; so a reference of type A can not invoke B.m2.

Method Overloading Question 1


class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D extends C { void m1(D d) {System.out.print("D");} public static void main(String[] args) { A a1 = new A(); B b1 = new B(); C c1 = new C(); D d1 = new D(); d1.m1(a1); d1.m1(b1); d1.m1(c1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: AAA Prints: ABC Prints: DDD Prints: ABCD Compile-time error Run-time error None of the above

Resposta:

The method invocation expression d1.m1(a1) uses reference d1 of type D to invoke method m1. Since the reference d1 is of type D, the Prints: class D is searched for an applicable implementation of m1. The methods 1b ABC inherited from the superclasses, C, B and A, are included in the search. The argument, a1, is a variable declared with the type A; so method A.m1(A a) is invoked.

Question 2
class GFC215 { static String m(float i) {return "float";} static String m(double i) {return "double";}

public static void main (String[] args) { int a1 = 1; long b1 = 2; System.out.print(m(a1)+","+ m(b1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: float,float Prints: float,double Prints: double,float Prints: double,double Compile-time error Run-time error None of the above

Resposta:

A method invocation conversion can widen an argument of type float to match a method parameter of type double, so any argument that can be passed to m(float i) can also be passed to m(double i) without generating a compile-time type error. For that reason, we can say that m(float i) is more specific than m(double i). Since both methods are applicable, the more specific of the two, m(float i), is chosen over the less specific, m(double i). The arguments of the method invocation Prints: 2a float,float expressions, m(a1) and m(b1), are of types int and long respectively. A method invocation conversion can widen an argument of type int or long to match either of the two method parameter types float ordouble; so both methods, m(float i) and m(double i), are applicable to the two method invocation expressions. Since both methods are applicable, the more specific of the two, m(float i) is chosen rather than the less specific, m(double i).

Question 3
class A {} class B extends A {} class C extends B {} class D { void m1(A a) {System.out.print("A");} void m1(B b) {System.out.print("B");} void m1(C c) {System.out.print("C");} public static void main(String[] args) { A c1 = new C(); B c2 = new C(); C c3 = new C(); D d1 = new D(); d1.m1(c1); d1.m1(c2); d1.m1(c3); }}

What is the result of attempting to compile and run the program?


a. Prints: AAA

b. c. d. e. f.

Prints: ABC Prints: CCC Compile-time error Run-time error None of the above

Resposta:

Three methods overload the method name m1. Each has a single parameter of type A or B or C. For any method invocation expression of the form m1(referenceArgument), the method is selected based on the declared type of the variable referenceArgument--not the run-time type of the referenced object. The method invocation expression d1.m1(c1)uses reference d1 of type D to invoke method m1 on an instance of type D. The argument, c1, is a reference of Prints: type A and the run-time type of the referenced object is C. The argument 3b ABC type is determined by the declared type of the reference variable c1--not the run-time type of the object referenced by c1. The declared type of c1 is type A; so the method m1(A a) is selected. The declared type of c2 is type B; so the method invocation expression d1.m1(c2) invokes method m1(B b). The declared type of c3 is type C; so the method invocation expression d1.m1(c3) invokes method m1(C c).

Question 4
class GFC216 { static String m(float i) {return "float";} static String m(double i) {return "double";} public static void main (String[] args) { char a1 = 1; long b1 = 2; System.out.print(m(a1)+","+ m(b1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: float,float Prints: float,double Prints: double,float Prints: double,double Compile-time error Run-time error None of the above

Resposta:

4a

A method invocation conversion can widen an argument of Prints: float,float type float to match a method parameter of type double, so any

argument that can be passed to m(float i) without generating a compile-time type error can also be passed to m(double i). For that reason, we can say that m(float i) is more specific than m(double i). The arguments of the method invocation expressions, m(a1) and m(b1), are of types char and long respectively. A method invocation conversion can widen an argument of type char or long to match either of the two method parameter types float or double; so both methods, m(float i) and m(double i), are applicable to the two method invocation expressions. Since both methods are applicable, the more specific of the two, m(float i) is chosen rather than the less specific, m(double i).

Question 5
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) { A c1 = new C(); B c2 = new C(); C c3 = new C(); C c4 = new C(); c4.m1(c1); c4.m1(c2); c4.m1(c3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: AAA Prints: ABC Prints: CCC Compile-time error Run-time error None of the above

Resposta:

Three methods overload the method name m1. Each has a single parameter of type A or B or C. For any method invocation expression of the form m1(referenceArgument), the method is selected based on the declared type of the variable referenceArgument--not the run-time type of the referenced object. The method invocation Prints: expression c4.m1(c1)uses reference c4 of type C to invoke 5b ABC method m1 on an instance of type C. The argument, c1, is a reference of type A and the run-time type of the referenced object is C. The argument type is determined by the declared type of the reference variable c1--not the run-time type of the object referenced by c1. The declared type of c1 is type A; so the method A.m1(A a) is selected. The declared type of c2 is type B; so the method invocation

expression c4.m1(c2) invokes method B.m1(B b). The declared type of c3 is type C; so the method invocation expression c4.m1(c3) invokes method C.m1(C c).

Question 6
class GFC217 { static String m(int i) {return "int";} static String m(float i) {return "float";} public static void main (String[] args) { long a1 = 1; double b1 = 2; System.out.print(m(a1)+","+ m(b1)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: float,float Prints: float,double Prints: double,float Prints: double,double Compile-time error Run-time error None of the above

Resposta:

The method invocation expression, m(b1), contains an argument of type double. A method invocation conversion will not implicitly narrow the argument to match the parameter type of the Compile6e method, m(float i). The method invocation expression, m(a1), time error contains an argument of type long. A method invocation conversion will widen the argument to match the parameter type of the the method, m(float i).

Question 7
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) { A c1 = new C(); C c2 = new C(); c1.m1(c2); }}

What is the result of attempting to compile and run the program?


a. Prints: A

b. c. d. e. f.

Prints: B Prints: C Compile-time error Run-time error None of the above

Resposta:

The reference c1 is of the superclass type, A; so it can be used to invoke only the method m1 declared in class A. The methods that overload the method name m1 in the subclasses, B andC, can not be invoked using the reference c1. A method invocation conversion promotes the argument referenced by c2 from type C to type A, and the method declared in class A is executed. Class A declares only one method, m1. The single parameter is of type A. Class B inherits the method declared in class A and overloads the method name with a new method that has a single parameter of type B. Both methods sharing the overloaded name, m1, can be invoked using a reference of type B; however, a reference of type A can be used to Prints: invoke only the method declared in class A. Class C inherits the methods 7a A declared in classes A and B and overloads the method name with a new method that has a single parameter of type C. All three methods sharing the overloaded name, m1, can be invoked using a reference of type C; however, a reference of type B can be used to invoke only the method declared in class B and the method declared in the superclass A. The method invocation expression c1.m1(c2) uses reference c1 of type A to invoke method m1. Since the reference c1 is of type A, the search for an applicable implementation of m1 is limited to class A. The subclasses, B and C, will not be searched; so the overloading methods declared in the subclasses can not be invoked using a reference of the superclass type.

Question 8
class GFC218 { static void m(Object x) {System.out.print("Object");} static void m(String x) {System.out.print("String");} public static void main(String[] args) {m(null);} }

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: Object Prints: String Compile-time error Run-time error None of the above

Resposta:

A method invocation conversion can widen an argument of type String to match a method parameter of type Object, so any argument that can be passed to m(String x) without generating a compile-time type error can also be passed to m(Object x). For that Prints: reason, we can say that m(String x) is more specific than m(Object 8b String x). The argument of the method invocation expression, m(null), is of type null and can be converted to either type String or Object by method invocation conversion, so both methods, m(String x) and m(Object x), are applicable. The more specific of the two, m(String x), is chosen over the less specific, m(Object x).

Question 9
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) { A a1 = new A(); A b1 = new B(); A c1 = new C(); C c4 = new C(); a1.m1(c4); b1.m1(c4); c1.m1(c4); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: AAA Prints: ABC Prints: CCC Compile-time error Run-time error None of the above

Resposta:

The declared type of the reference variables, a1, b1 and c1, is the superclass type, A; so the three reference variables can be used to invoke only the method m1(A a) that is declared in the superclass, A. The Prints: methods that overload the method name m1 in the subclasses, B and C, can 9a AAA not be invoked using a reference variable of the superclass type, A. A method invocation conversion promotes the argument referenced by c4 from type C to type A, and the method declared in class A is executed.

Question 10

class GFC200 {} class GFC201 { static void m(Object x) {System.out.print("Object");} static void m(String x) {System.out.print("String");} static void m(GFC200 x) {System.out.print("GFC200");} public static void main(String[] args) {m(null);} }

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: Object Prints: String Prints: GFC200 Compile-time error Run-time error None of the above

Resposta:

The type of the argument is null and could be converted to any of the types Object, String or GFC200, by method invocation conversion. All three methods are applicable, but none of the three is more specific than both of the other two. The ambiguity results in a compile-time type error. If type GFC200 were a subclass of type String; then any argument that could be pass to m(GFC200 Compilex) could also be passed to m(String x) without causing a 10 d time error compile-time type error, and we could say that m(GFC200 x) is more specific thanm(String x). Since GFC200 is not a subclass of type String, a method invocation conversion is not able to widen an argument of type GFC200 to match a method parameter of type String, so m(GFC200 x) is not more specific than m(String x).

Question 11
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) { A a1 = new A(); B b1 = new B(); C c1 = new C(); A c2 = new C(); c2.m1(a1); c2.m1(b1); c2.m1(c1); }}

What is the result of attempting to compile and run the program?


a. Prints: AAA b. Prints: ABC

c. d. e. f.

Prints: CCC Compile-time error Run-time error None of the above

Resposta:

11 a

Prints: AAA

The reference c2 is of the superclass type, A; so it can be used to invoke only the method, m1, declared in class A. The methods that overload the method name m1 in the subclasses, B andC, can not be invoked using the reference c2.

Question 12
class GFC202 {} class GFC203 extends GFC202 {} class GFC204 { static void m(GFC202 x) {System.out.print("GFC202");} static void m(GFC203 x) {System.out.print("GFC203");} public static void main(String[] args) {m(null);} }

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: GFC202 Prints: GFC203 Compile-time error Run-time error None of the above

Resposta:

12 b

Prints: GFC203

The type of the argument is null and could be converted to either type GFC202 or GFC203 by method invocation conversion; so both methods are applicable. The more specific of the two, m(GFC203 x), is chosen. Type GFC203 is a subclass of type GFC202; so any argument that can be passed to m(GFC203 x) can also be passed to method m(GFC202 x)without causing a compile-time type error; therefore, we can say that method m(GFC203 x) is more specific than m(GFC202 x).

Question 13
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) {

A a1 = new A(); B b1 = new A(); C c1 = new A(); C c2 = new C(); c2.m1(a1); c2.m1(b1); c2.m1(c1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: AAA Prints: ABC Prints: CCC Compile-time error Run-time error None of the above

Resposta:

13 d

Compiletime error

The declarations of b1 and c1 cause compile-time errors, because a reference of a subclass type can not refer to an instance of the superclass type.

Question 14
class GFC205 {} class GFC206 extends GFC205 {} class GFC207 extends GFC206 { static void m(GFC205 x, GFC205 y) {System.out.print("GFC205,GFC205");} static void m(GFC205 x, GFC206 y) {System.out.print("GFC205,GFC206");} static void m(GFC206 x, GFC205 y) {System.out.print("GFC206,GFC205");} static void m(GFC206 x, GFC206 y) {System.out.print("GFC206,GFC206");} public static void main(String[] args) { GFC207 gfc207 = new GFC207(); m(gfc207, gfc207); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: GFC205,GFC205 Prints: GFC205,GFC206 Prints: GFC206,GFC205 Prints: GFC206,GFC206 Compile-time error Run-time error None of the above

Resposta:

14 d

Prints: Type GFC207 is a subclass of types GFC206 and GFC205, GFC206,GFC206 so any of the four methods are applicable to the method

invocation expression, m(gfc207, gfc207). The most specific of the four, m(GFC206 x, GFC206 y), is chosen. Type GFC206 is a subclass of type GFC205, and method m(GFC206 x, GFC206 y) is more specific than the other three, because any invocation of m(GFC206 x, GFC206 y) could also be handled by any of the other three without causing a compile-time type error.

Question 15
class A {void m1(A a) {System.out.print("A");}} class B extends A {void m1(B b) {System.out.print("B");}} class C extends B {void m1(C c) {System.out.print("C");}} class D { public static void main(String[] args) { A a1 = new A(); B b1 = new B(); C c1 = new C(); C c2 = new A(); c2.m1(a1); c2.m1(b1); c2.m1(c1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: AAA Prints: ABC Prints: CCC Compile-time error Run-time error None of the above

Resposta:

15 d

The declaration of c2 causes a compile-time error, because a Compile-time reference of a subclass type can not refer to an instance of the error superclass class.

Question 16
class GFC211 {} class GFC212 extends GFC211 {} class GFC213 extends GFC212 { static void m(GFC211 x, GFC211 y) {System.out.print("GFC211,GFC211");} static void m(GFC211 x, GFC212 y) {System.out.print("GFC211,GFC212");} static void m(GFC212 x, GFC211 y) {System.out.print("GFC212,GFC211");} static void m(GFC212 x, GFC212 y) {System.out.print("GFC212,GFC212");} static void m(GFC211 x, GFC213 y) {System.out.print("GFC211,GFC213");} public static void main(String[] args) {

GFC213 gfc213 = new GFC213(); m(gfc213, gfc213); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: GFC211,GFC211 Prints: GFC211,GFC212 Prints: GFC212,GFC211 Prints: GFC212,GFC212 Prints: GFC211,GFC213 Compile-time error Run-time error None of the above

Resposta:

The method invocation expression, m(gfc213, gfc213), is ambiguous; because, no applicable method is more specific than all of the others. Method m(GFC212 x, GFC212 y) is more specific than m(GFC212 x, GFC211 y), because any invocation of m(GFC212 x, GFC212 y) could also be handled Compile- by m(GFC212 x, GFC211 y)without causing a compile-time 16 f time error type error. However, some invocations of m(GFC212 x, GFC212 y) can not be handled by m(GFC211 x, GFC213 y), so m(GFC212 x, GFC212 y) is not more specific than m(GFC211 x, GFC213 y). Furthermore, not all invocations of m(GFC211 x, GFC213 y) could be handled by m(GFC212 x, GFC212 y).

Question 17
class GFC214 { static void m1(boolean b1) {System.out.print("boolean ");} static void m1(byte b1) {System.out.print("byte ");} static void m1(short s1) {System.out.print("short ");} static void m1(char c1) {System.out.print("char ");} static void m1(int i1) {System.out.print("int ");} public static void main(String[] args) { byte b1; m1(b1 = 1); m1(b1); m1(b1 == 1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: byte byte byte Prints: byte byte boolean Prints: int int int Compile-time error

e. Run-time error f. None of the above


Resposta:

Prints: 17 b byte byte boolean

Variable b1 was initialized by the first method invocation statement, so the second method invocation statement does not result in a compile-time error. The assignment expression, b1 = 1, initializes variable b1 with the value 1, and the same value is passed as an argument to method m1(byte b1). The method invocation expression, m1(b1), invokes the same method,m1(byte b1). The argument of the third method invocation expression, m1(b1 == 1), is the result of the equality expression, b1 == 1. The type of the result and the argument isboolean, so the invoked method is m1(boolean b1).

Question 18
class A {} class B extends A {} class C extends B { static void m(A x, A y) {System.out.print("AA");} static void m(A x, B y) {System.out.print("AB");} static void m(B x, A y) {System.out.print("BA");} static void m(B x, B y) {System.out.print("BB");} public static void main(String[] args) { A a1; B b1; m(null,null); m(a1=null,b1=null); m(b1, a1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: BBABAB Prints: BBABBA Prints: BBBBAB Prints: BBBBBA Prints: BBBBBB Compile-time error Run-time error None of the above

Resposta:

Type B is a subclass of type A, and method m(B x, B y) is more specific than the other three; because any invocation of it could be handled by any of the other three without causing a compile-time Prints: type error. All four methods are applicable to the first method 18 b BBABBA invocation expression, m(null,null). The most specific method, m(B x, B y), is chosen; and both arguments are converted to type B. In the second method invocation

expression, m(a1=null,b1=null), simple assignment expressions initialize the local variables a1 and b1 withnull references of types A and B respectively. The invoked method is m(A x, B y). In the third method invocation expression, the positions of the arguments are reversed relative to the previous invocation: The type of the first argument is now B and the second is A. The invoked method is m(B x, A y).

Question 19
class A {} class B extends A {} class C extends B { static void m1(A x) {System.out.print("m1A");} static void m2(B x) {System.out.print("m2B"); m1(x);} static void m2(A x) {System.out.print("m2A"); m1(x);} static void m3(C x) {System.out.print("m3C"); m2(x);} static void m3(B x) {System.out.print("m3B"); m2(x);} static void m3(A x) {System.out.print("m3A"); m2(x);} public static void main(String[] args) {m3(new C());} }

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: m3Am2Am1A Prints: m3Bm2Bm1A Prints: m3Cm2Bm1A Prints: m3Cm2Am1A Compile-time error Run-time error None of the above

Resposta:

19 c

Prints: m3Cm2Bm1A

The method invocation expression, m3(new C()), invokes method m3(C x), because the argument type matches the parameter type of the method declaration exactly. Method m3uses the parameter as the argument of the next invocation expression, m2(x). Of the two overloaded versions of m2, the most specific is invoked, m2(B x). Type B is a subclass of A, so any invocation of m2(B x) could be handled by m2(A x) without causing a compile-time type error. For that reason, m2(B x) is more specific than m2(A x).

Nested Classes Question 1


Which of the follow are true statements.
a. A nested class is any class that is declared within the body of another class or interface. b. A nested class can not be declared within the body of an interface declaration. c. An inner class is a nested class that is not static. d. A nested class can not be declared static. e. A named class is any class that is not anonymous.
Resposta:

Every class declared within the body of another class or interface is known as a nested class. If the nested class does not have a name, then it is an anonymous class. If the nested class has a A nested class is any class that is name, then it is not anonymous. If the nested declared within the body of a class has a name and is not declared inside of a another class or interface. An 1 c method, constructor or any block, then it is a inner class is a nested class that e member class. If a member class is not static, is not static. A named class is then it is an inner class. If a class is not nested, any class that is not anonymous. then it is a top level class. A nested class that is static is sometimes referred to as a top level class, but that usage of the term is confusing and should be avoided.

Question 2
Which of the follow are true statements.
a. b. c. d. e. A local class is declared within a method, constructor or block. An anonymous class is always a local class. A local class is a nested class. A local class is a member class. A local class is always a named class.

Resposta:

A local class is declared a within a method, 2 c constructor or block. A e local class is a nested class. A local class is

Every class declared within the body of another class is known as a nested class. If the nested class does not have a name, then it is an anonymous class. If the nested class has a name, then it is not anonymous. If the nested class has a name and is declared inside of a

always a named class.

method, constructor or any block, then it is a local class. If a nested class does not have a name, then it can not be called a local class even if it is declared inside of a block. Therefore, an anonymous class is never called a local class. If the nested class has a name and is not declared inside of a method, constructor or any block, then it is a member class. If the class is not nested, then it is a top level class. Please note that this question is more rigorous than those that one might expect to find on the real exam. It has been included here as a convenient place to define some terms that are used to explain the answers to some of the other questions that appear in this mock exam.

Question 3
Which of the following are class modifiers? Select all that are applicable to a top-level class and all that are applicable to a nested class. It is not required that a modifier be applicable to both.
a. b. c. d. e. f. g. h. i. j. k. abstract extends final implements private protected public static synchronized transient volatile

Resposta:

The access modifiers, public, protected and private, can not be a applied to a local class. The c protected and private access e modifiers can be applied to member 3 abstract final private protected public static f classes, but not to a top level class. g The public modifier can be applied h to a top level class or a member class, but not a local class. The static modifier can be applied to a

member class, but not to a local class or top level class. The keywords extends and implements are not modifiers. The synchronized modifier can be applied to a method, but not to a class. The modifiers, transient and volatile, can be applied to a field, but not to a class.

Question 4
Which of the following modifiers can be applied to a member class?
a. b. c. d. e. f. g. h. abstract final public protected private static synchronized transient

Resposta:

A nested class that has a name and is not a local class is a member a class. A member class can be static b or non-static. A non-static member c 4 abstract final public protected private static class is also known as an inner d class. All of the class modifiers e may be applied to a member class. f The modifiers, synchronized and transient, are not class modifiers.

Question 5
Which of the following modifiers can be applied to a local class?
a. b. c. d. public protected private abstract

e. static f. final
Resposta:

If a nested class has a name and is declared inside of a method, d constructor or any block, then it is a local class. No access modifier 5 abstract final f can be applied to a local class declaration. A local class can not be static. A local class can be abstract, and can be final.

Question 6
class Z { abstract class A {} final class B {} private class C {} protected class D {} public class E {} } // // // // // 1 2 3 4 5

Which class declaration results in a compile-time error?


a. b. c. d. e. f. 1 2 3 4 5 None of the above

Resposta:

6f

None of the above

The following modifiers can be applied to a member class: abstract, private, protected, public, static and final.

Question 7
class Z { static class F {} // 1 synchronized class G {} // 2 transient class H {} // 3 volatile class I {} // 4 }

Which class declaration does not result in a compile-time error?


a. 1 b. 2

c. 3 d. 4 e. None of the above


Resposta:

Please note that this question asks which class declaration does NOT result in a compile-time error. The following modifiers can be applied to a member class: abstract, private, protected, public, static and final. The synchronized modifier 7a 1 can not be applied to any class, because it is a method modifier. The modifiers, transient and volatile, can not be applied to any class, because they are field modifiers.

Question 8
class Z { void m1() { abstract class A {} final class B {} private class C {} protected class D {} public class E {} } } // // // // // 1 2 3 4 5

Which class declarations result in compile-time errors?


a. b. c. d. e. 1 2 3 4 5

Resposta:

c d The abstract and final modifiers can be applied to a method local class 3 4 5 e declaration.

Question 9
class Z { void m1() { static class F {} synchronized class G {} transient class H {} volatile class I {} abstract class A {} final class B {} } // // // // // // 1 2 3 4 5 6

Compile-time errors are generated at which lines?


a. b. c. d. e. f. 1 2 3 4 5 6

Resposta:

a The modifiers, abstract and final, can be applied to a method local class b declaration. The synchronized modifier can not be applied to a class, 9 1 2 3 4 c because it is a method modifier. The modifiers, transient and volatile, d can not be applied to any class, because they are field modifiers.

Question 10
class A { A() {} int A; void A() {} class A {} } // // // // 1 2 3 4

Which line results in a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

A method and a field can share the same name, because they are used in different contexts and use different lookup procedures. They can even share the same name with the class in which they are declared. Please note that class 10 d 4 names usually begin with an upper case letter while method and field names usually begin with a lower case letter. A nested class can not share the same name with its enclosing class.

Question 11

class A { int B; void B() {} class B {} }

// 1 // 2 // 3

Which line results in a compile-time error?


a. b. c. d. 1 2 3 None of the above

Resposta:

A method, field, and a nested class can share the same name, because they are used in different contexts and use different lookup procedures. Please note that class names usually begin with an upper case letter None of while method and field names usually begin with a lower case letter. 11 d the Also note that a nested class can not share the same name with its above enclosing class; however, a method and field can share a name with the enclosing class. Even so, it is not a good idea to name a method with the name of the enclosing class, because it could be confused with a constructor.

Question 12
abstract class A { private abstract void m1(); private abstract class B {} private class C extends B {} } // // // // 1 2 3 4

Which line results in a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above.

Resposta:

An abstract method has no implementation, and is not useful until an extending class implements the method. Private methods are not inherited and can not be overridden. If an abstract method is declared private, then it can not be 12 b 2 implemented in a subclass. Although a method may not be both private and abstract, a nested class can be; because another nested class can extend the abstract class and implement any abstract methods.

Question 13
abstract class A { abstract final void m1(); abstract final class B {} class C extends B {} } // // // // 1 2 3 4

Which line does not result in a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

Please note that this question asks which line does NOT result in a compiletime error. An abstract method has no implementation and is not useful until an extending class implements the method. A final method can not be overridden by a subclass method. An abstract final method can not be implemented and is 13 a 1 not legal. An abstract class may contain abstract method declarations and is assumed to be incomplete. A final class can not be extended. The implementation of an abstract final class could not be completed. The declaration of class C results in a compiler error, because a final class may not be listed in the extends clause.

Question 14
abstract class A { abstract synchronized void m1(); abstract synchronized class B {} synchronized class C extends B {} } // // // // 1 2 3 4

Which line does not result in a compile-time error?


a. b. c. d. e. 1 2 3 4 None of the above

Resposta:

Please note that this question asks which line does NOT result in a compiletime error. The modifier, synchronized, is a method modifier, but is not a class modifier. Any attempt to declare a synchronized class results in a compile-time 14 a 1 error. Since the synchronized modifier specifies an implementation detail it makes no sense to use it with an abstract method that provides no implementation.

Question 15
class A { private static String s1 = "s1"; final String s2 = "s2"; A () { new Z("s5","s6");} class Z { final String s3 = "s3"; String s4 = "s4"; Z (final String s5, String s6) { System.out.print(???); }} public static void main(String args[]) {new A();} }

Which variable can not be substituted for ??? without causing a compile-time error?
a. b. c. d. e. f. g. s1 s2 s3 s4 s5 s6 None of the above

Resposta:

None of 15 g the above

Please note that this question asks which variable can NOT be substituted. Class Z is a non-static member class of class A; therefore, all of the fields and methods of class A (static, non-static, and private) are available to class Z.

Question 16
class B { private static String s1 = "s1"; final String s2 = "s2"; B () {new Z("s5","s6");} static class Z { final String s3 = "s3";

static String s4 = "s4"; Z (final String s5, String s6) { System.out.print(???); }} public static void main(String args[]) {new B();} }

Which variable can not be substituted for ??? without causing a compile-time error?
a. b. c. d. e. f. g. s1 s2 s3 s4 s5 s6 None of the above

Resposta:

Please note that this question asks which variable can NOT be substituted. Class Z is a static member class of class B; therefore, all of the static fields and methods of the enclosing class B are available to Z. For example, from within the static member class Z, the static field s1 of the enclosing class B can be accessed using the simple name s1. The simple name s1 does not need to be qualified with a reference to an instance of the enclosing class B, because s1 is not associated with a particular instance of the enclosing class. 16 b s2 In contrast, non-static fields and methods of the enclosing class B are associated with a particular instance of class B. From the static context of class Z, the instance fields and methods of the enclosing class B can be accessed only if the simple name of the instance field or method is qualified with a reference to a specific instance of class B. Suppose a reference variable r1 refers to an instance of the enclosing class B. Then the instance member s2 of the enclosing class instance referenced by r1 could be accessed using the expression r1.s2.

Question 17
class C { private static String s1 = "s1"; String s2 = "s2"; C() {m1("s5","s6");} void m1(final String s5, String s6) { final String s3 = "s3"; String s4 = "s4"; class Z {Z() {System.out.print(???);}} new Z(); } public static void main(String args[]) {new C();} }

Which variable names can be substituted for ??? without causing a compile-time error?
a. b. c. d. e. f. s1 s2 s3 s4 s5 s6

Resposta:

Class Z is a local class defined within the code block of method m1 of class C. All of the fields and methods of class C (static, non-static, and private) are available to Class Z. Additionally, the parameters of method m1 that are declared final are available to class Z. If a final local variable declaration appears before the declaration of class Z, then it is also available to class Z. Parameter s6 and variable s4 are not final and are therefore not available to class Z. There are at least two reasons why non-final a variables are not available to a local inner class. The first reason is b 17 s1 s2 s3 s5 because the life cycle of a local variable might be shorter than that c of a local class. A local variable lives on the stack and disappears e as soon as the method is exited. A local class, however, might continue to exist even after the method has been exited. The second reason is due to multithreading issues. Suppose a local class extends the Thread class or implements the Runnable interface, and it is used to spawn a new Thread from within the method m1. If the local variables of method m1 were available to the local class, then a mechanism for synchronizing access to the variables would be required.

Question 18
class D { D() {System.out.print("D");} class Z {Z(){System.out.print("Z");}} public static void main(String args[]) { new D.Z(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: D Prints: Z Prints: DZ Prints: ZD

e. Run-time error f. Compile-time error g. None of the above


Resposta:

An instance of class Z must be associated with an enclosing instance of class D. In a static context, an unqualified class instance creation expression of the form new ClassType(ArgumentListopt) ClassBodyopt can not be used to create an instance of an inner class. Instead, a qualified class instance creation expression of the formReference.new Identifier(ArgumentListopt) Compile18 f ClassBodyopt is required to create an association between an time error instance of the enclosing class and the new instance of the inner class. The reference could be provided by a reference variable of the type of the enclosing class, or it could be provided by a class instance creation expression such as new D(). In a static context, the expression new D().new Z() can be used to create the new instance of the enclosing class D and the new instance of the inner class Z.

Question 19
class E { E() {System.out.print("E");} static class Z {Z(){System.out.print("Z");}} public static void main(String args[]) { new E.Z(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: E Prints: Z Prints: EZ Prints: ZE Run-time error Compile-time error None of the above

Resposta:

Class Z is a static member class of class E. Static member classes are similar to ordinary top-level classes with the added advantage that all of the static fields and methods of the enclosing class (including those that Prints: 19 b are private) are available to the member class. The class instance creation Z expression new E.Z() creates an instance of the static nested class E.Z. The instance of the static nested class is not associated with any instance of the enclosing class, and no instance of the enclosing class is created.

For that reason, only the letter "Z" is printed.

Question 20
class F { public void m1() {Z.m1();} // 1 private static class Y { private static void m1() { System.out.print("Y.m1 "); }} private static class Z { private static void m1(){ System.out.print("Z.m1 "); Y.m1(); // 2 }} public static void main(String[] args) { new F().m1(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Compile-time error at line 1 Compile-time error at line 2 Run-time error at line 1 Run-time error at line 2 Prints: Z.m1 Y.m1 None of the above

Resposta:

Prints: 20 e Z.m1 Y.m1

The private fields and methods of the member classes are available to the enclosing class. The private fields and methods of the member classes are also available to other member classes.

Question 21
class G { final String s1 = "G.s1"; class Z { String s1; void m1() {System.out.println(???);} } public static void main(String args[]) { G g = new G(); g.new Z().m1(); }}

Which name or expression could be used in place of ??? to cause the program to print "G.s1"?

a. b. c. d. e. f.

s1 G.s1 ((G)this).s1 G.this.s1 G.super.s1 None of the above

Resposta:

21 d G.this.s1

The qualified this expression ClassName.this.name can be used to access shadowed variables declared within an enclosing class.

Question 22
class Outer { static class StaticNested { static final int a = 25; // static final int b; // static int c; // int d; // static {b = 42;} // } class NonStaticInner { static final int e = 25; // static final int f; // static int g; // int h; // static {f = 42;} // }} 1 2 3 4 5 6 7 8 9 10

Compile-time errors are generated at which lines?


a. b. c. d. e. f. g. h. i. j. 1 2 3 4 5 6 7 8 9 10

Resposta:

g A non-static nested class is called an inner class. An inner class can not 22 h 7 8 10 declare a static field unless it is a compile-time constant. Even though f j is final, it does not have a value at compile time; so it causes a

compilation error. Member variable g also causes a compile-time error, because it is static. The static initializer of NonStaticInner causes a compile-time error, because inner classes (i.e. non-static nested classes) can not declare static initializers.

Question 23
class Red { private static final int a = 10; protected static int b = 20; int c = 30; static class StaticNested { int d = a; int e = b; int f = c; } class NonStaticInner { int g = a; int h = b; int i = c; }} // 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8 // 9

A compile-time error is generated at which line?


a. b. c. d. e. f. g. h. i. 1 2 3 4 5 6 7 8 9

Resposta:

The non-static members of an enclosing class are not directly available to a static nested class. From within StaticNested, the non-static members of the enclosing class can not be referred to by a simple name. Instead, a qualified 23 f 6 name is required. Suppose a reference variable r1 refers to an instance of the enclosing class Red. Then the instance member c of the enclosing class instance referenced by r1 could be accessed using the qualified name r1.c.

Question 24
class Red { static class StaticNested {interface ABC {}} class NonStaticInner {interface DEF {}} // 1 // 2

interface GHI {} }

// 3

A compile-time error is generated at which line?


a. b. c. d. 1 2 3 None of the above

Resposta:

24 b 2

A member interface is implicitly static; therefore, it can not be declared as a member of a non-static nested class.

Question 25
class A { private static int counter; public static int getCounter(){return counter++;} private static int innerCounter; public static int getInnerCounter(){return innerCounter++;} private String name; A() {name = "A" + getCounter();} class B { private String name; B() { name = "B" + getInnerCounter(); System.out.print(A.this.name + name); // 1 }} public static void main(String[] args) { new A().new B(); // 2 A a1 = new A(); a1.new B(); // 3 a1.new B(); // 4 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: A0B0A1B1A1B2 Prints: A0B0A1B1A2B2 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4 Other compile-time error. Run-time error None of the above

Resposta:

Class A is the enclosing class of the inner class B. An instance of class B must be associated with an enclosing instance of class A. In a static context such as the main method, instantiation of a named inner class requires the use of a qualified class instance creation expression of the form Reference.new Identifier(ArgumentListopt). The reference could be provided by a reference variable of the type of the enclosing class, or it could be provided by another class instance creation expression. At line 2, the qualified class instance creation expression new A().new B() first creates a new Prints: instance of the enclosing class A, then it creates an instance 25 a A0B0A1B1A1B2 of B. The new instance of A is the first instance created; so the name is A0. The new instance of B is the first instance created; so the name is B0. At line 3, the qualified class instance creation expression a1.new B() creates an instance of B that is associated with a previously existing instance of class A that is referenced by variable a1. The instance of class A referenced by variable a1 is the second instance created so the name is A1. The new instance of B is the second instance created; so the name is B1. At line 4, a new instance of B is created and associated with the instance of A this is referenced by variable a1.

Question 26
class A { private static int counter; public static int getCounter(){return counter++;} private static int innerCounter; public static int getInnerCounter(){return innerCounter++;} private String name; A() {name = "A" + getCounter();} class B { private String name; B() { name = "B" + getInnerCounter(); System.out.print(A.this.name + name); // 1 }} void m1() {new A().new B();} // 2 void m2() {this.new B();} // 3 void m3() {new B();} // 4 public static void main(String[] args) { A a1 = new A(); a1.m1(); a1.m2(); a1.m3(); }}

What is the result of attempting to compile and run the program?


a. Prints: A0B0A1B1A1B2

b. c. d. e. f. g. h. i. j.

Prints: A0B0A1B1A2B2 Prints: A1B0A0B1A0B2 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4 Other compile-time error. Run-time error None of the above

Resposta:

Class A is the enclosing class of the inner class B. An instance of class B must be associated with an enclosing instance of class A. In a static context, instantiation of a named inner class requires the use of a qualified class instance creation expression of the form Reference.new Identifier(ArgumentListopt). The reference could be provided by a reference variable of the type of the enclosing class, or it could be provided by another class instance creation expression. If the enclosing class is not an inner class, then the enclosing class could be instantiated with an unqualified class instance creation expression such as the following, new EnclosingClass(). The qualified class instance creation expression new A().new B() first creates a new instance of A, then it creates an instance of B. Prints: 26 c A1B0A0B1A0B2 The new instance of A is the second instance created; so the name is A1. The new instance of B is the first instance created; so the name is B0. In the qualified class instance creation expression this.new B(), the keyword this, denotes a reference to the enclosing instance on which the method m2has been invoked. A new instance of the enclosing class is not created; so the name of the enclosing instance is A0. The new instance of B is the second instance created; so the name is B1. Since method m3 is an instance method, the inner class B can be instantiated using the unqualified class instance creation expression new B(). The enclosing instance is the instance on which the method m3 has been invoked. It is the same instance that is referenced by the keyword this and the reference variable a1.

Question 27
class A { private static int counter; public static int getCounter(){return counter++;} private static int innerCounter;

public static int getInnerCounter(){return innerCounter++;} private String name; A() {name = "A" + getCounter();} class B { private String name; B() { name = "B" + getInnerCounter(); System.out.print(A.this.name + name); }} void m1() {new A().new B();} // 1 void m2() {new A.B();} // 2 void m3() {new B();} // 3 public static void main(String[] args) { A a1 = new A(); a1.m1(); a1.m2(); a1.m3(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. Prints: A0B0A1B1A1B2 Prints: A0B0A1B1A2B2 Prints: A1B0A0B1A0B2 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4 Other compile-time error. Run-time error None of the above

Resposta:

Class A is the enclosing class of the inner class B. An instance of class B must be associated with an enclosing instance of class A. In a static context, instantiation of a named inner class requires the use of a qualified class instance creation expression of the form Reference.new Identifier(ArgumentListopt). The reference could be provided by a reference variable of the type of the enclosing class, or it could be provided by another class instance creation expression. If the enclosing class is not an inner Prints: 27 c A1B0A0B1A0B2 class, then the enclosing class could be instantiated with an unqualified class instance creation expression such as the following, new EnclosingClass(). At line 1, the qualified class instance creation expression new A().new B() first creates a new instance of A, then it creates an instance of B. The new instance of A is the second instance created; so the name is A1. The new instance of B is the first instance created; so the name is B0. At line 2, a new instance of the named inner class B is created using the class instance

creation expression new A.B(). The fully qualified name of classB is A.B. Since the class instance creation expression new A.B() appears within a method that is a member of class A, the use of the fully qualified name is unnecessary. Within methodA.m2, the class instance creation expression new A.B() could be replaced by the expression new B() without changing the result. Using either expression, a new instance of class B is created without creating a new instance of class A. Instead, the new instance of class B is associated with the same instance of class A on which the method m2 has been invoked. It is the same instance of class A that is referenced by the keyword this and the reference variable a1. Since it was the first instance created, the name is A0. The new instance of B is the second instance created; so the name is B1. At line 3, a new instance of the named inner class B is created using the unqualified class instance creation expression new B(). The new instance of Bis the third instance created; so the name is B2. The new instance of the inner class is associated with the same instance of the enclosing class on which the method m3 has been invoked. It is the same instance that is referenced by the keyword this and the reference variable a1. Since it was the first instance created, the name is A0.

Question 28
class A { private static int counter; public static int getCounter(){return counter++;} private static int innerCounter; public static int getInnerCounter(){return innerCounter++;} private String name; A() {name = "A" + getCounter();} class B { private String name; B() { name = "B" + getInnerCounter(); System.out.print(A.this.name + name); // 1 }} static void m1() {new A().new B();} // 2 static void m2() {this.new B();} // 3 static void m3() {new B();} // 4 public static void main(String[] args) { m1(); m2(); m3(); }}

What are the results of attempting to compile and run the program?

a. b. c. d. e. f. g.

Prints: A0B0A1B1A1B2 Prints: A0B0A1B1A2B2 Prints: A1B0A0B1A0B2 Compile-time error at line 1 Compile-time error at line 2 Compile-time error at line 3 Compile-time error at line 4

Resposta:

Compile-time error at line f 28 3 Compileg time error at line 4

Class A is the enclosing class of the inner class B. An instance of class B must be associated with an enclosing instance of class A. In a static context, instantiation of a named inner class requires the use of a qualified class instance creation expression of the form Reference.new Identifier(ArgumentListopt). The reference could be provided by a reference variable of the type of the enclosing class, or it could be provided by another class instance creation expression. If the enclosing class is not an inner class, then the enclosing class could be instantiated with an unqualified class instance creation expression such as the following, new EnclosingClass(). The qualified class instance creation expression new A().new B() first creates a new instance of A, then it creates an instance of B. The qualified class instance creation expression this.new B() generates a compile-time error, because the keyword this can not be used within a static method. Since methods m1, m2 and m3 are static methods, an instance of the named inner class B can not be created inside any of the three methods using an unqualified class instance creation expression of the form new ClassType(ArgumentListopt).

Anonymous Classes Question 1


Which of the following is a true statement?
An anonymous class can extend only the Object class. An anonymous class can not implement an interface. An anonymous class declaration can not have an implements clause. An anonymous class declaration can name more than one interface in the implements clause. e. The class instance creation expression for an anonymous class must never include arguments. a. b. c. d.

f. None of the above


Resposta:

An anonymous class 1 c declaration can not have animplementsclause.

A class instance creation expression can create an instance of a named class or an anonymous class. For example, the class instance creation expression new Object() creates an instance of the class named Object. If a class body appears in the class instance creation expression, then an anonymous class is created. For example, the expression new Object() {void doNothing(){}} creates an instance of an anonymous class that extends Object and implements a method named doNothing. In other words, if a class name immediately follows the keyword new, then the anonymous class extends the named class. When a named class is being extended, then the class instance creation expression can contain an optional argument list. The arguments will be passed to the direct superclass constructor that has a matching parameter list. An anonymous class declaration can not have animplements clause or an extends clause.

Question 2
Which of the following are true statements?
An anonymous class is implicitly abstract. An anonymous class is implicitly final. An anonymous class is implicitly static. A static reference variable can reference an instance of an anonymous class. An anonymous class declaration must have at least one explicit constructor declaration. f. An anonymous class declaration can have more than one explicit constructor declaration. a. b. c. d. e.
Resposta:

An anonymous class is b implicitly final. Astatic reference 2 d variable can reference an instance of an anonymous class.

An anonymous class can extend Object and implement an interface, or the anonymous class can extend a named class including Object. An anonymous class can not be extended; so it can not be abstract. An anonymous class declaration always creates an

instance of a class; so it is not surprising that an anonymous class can not be declared static. Even so, astatic reference variable can refer to an anonymous class. A constructor shares the same name as the class in which it is declared, but an anonymous class has no name. For that reason, it is not surprising that an anonymous class declaration can not contain an explicit constructor declaration. Instead, an anonymous class can contain an instance initializer.

Question 3
abstract class A { private int x = 4, y = 2; public int x() {return x;} public void x(int x) {this.x = x;} public int y() {return y;} public void y(int y) {this.y = y;} public abstract int math(); } class B { static A a1 = new A(2,1) { public A(int i1, int i2) {x(i1);y(i2);}; public int math() {return x()+y();} }; public static void main(String[] args) { System.out.print(a1.math()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 8 Prints: 3122 Compile-time error Run-time error None of the above

Resposta:

3c

Compile-time error

An anonymous class declaration can not contain an explicit declaration of a constructor.

Question 4

class A { private static int f1 = 1; private int f2 = 2; void m1(int p1, final int p2) { int l1 = 5; final int l2 = 6; Object x = new Object() { int a = f1; // 1 int b = f2; // 2 int c = p1; // 3 int d = p2; // 4 int e = l1; // 5 int f = l2; // 6 };}}

Compile-time errors are generated at which lines?


a. b. c. d. e. f. 1 2 3 4 5 6

Resposta:

Local method variables and method parameters are stored on the stack and go out of scope after the method is exited. Although a local reference variable is stored on the stack, the referenced object is stored on the heap; so the object can continue to exist long after the method runs to completion. An object that c 4 3 5 is instantiated within a method or block is not permitted to refer to a variable e that is declared within the method or block unless the variable is declared final and the variable declaration precedes the creation of the object.

Question 5
abstract class A { private int x = 1, y = 1; public A(int x, int y) {this.x = x; this.y = y;} public abstract int math(); } class B { static A a1 = new A(2,1) {public int math() {return static A a2 = new A(2,1) {public int math() {return static A a3 = new A(2,1) {public int math() {return static A a4 = new A(2,1) {public int math() {return public static void main(String[] args) { System.out.print("" + a1.math() + a2.math() + a3.math() + a4.math()); }}

x x x x

+ * /

y;}}; y;}}; y;}}; y;}};

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 3122 Prints: 2011 Compile-time error Run-time error None of the above

Resposta:

Compile5c time error

The instance variables x and y in class A are private, so they are not accessible to the anonymous subclasses. If you want to access the private variables of a superclass, then you will need to add accessor methods to the superclass such as getX and getY.

Question 6
abstract class A { private int x = 4, y = 2; public int x() {return x;} public void x(int x) {this.x = x;} public int y() {return y;} public void y(int y) {this.y = y;} public abstract int math(); } class B { static A a1 = new A() {public int math() {return static A a2 = new A() {public int math() {return static A a3 = new A() {public int math() {return static A a4 = new A() {public int math() {return public static void main(String[] args) { System.out.print("" + a1.math() + a2.math() + a3.math() + a4.math()); }}

x()+y();}} x()-y();}} x()*y();}} x()/y();}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 18 Prints: 6282 Compile-time error Run-time error None of the above

Resposta:

Compile6c time error

When an anonymous class declaration is the last thing that appears in a statement, then a semicolon must follow the declaration. Anonymous class declarations provide an excellent opportunity for trick questions involving statements with missing semicolons.

Question 7
class A {String m1() {return "A.m1";}} interface B {String m2();} class C { static class D extends A implements B { public String m1() {return "D.m1";} public String m2() {return "D.m2";} } static A a1 = new A() implements B { public String m1() {return "m1";} public String m2() {return "m2";} }; public static void main(String[] args) { System.out.print(a1.m1() + "," + new C.D().m2()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: m1,D.m2 Prints: A.m1,D.m2 Compile-time error Run-time error None of the above

Resposta:

An anonymous class can extend Object and implement an interface, or the anonymous class can extend a named class including Object. Compile- An anonymous class declaration can not have 7c time error an implements clause. In this case, the declaration of the anonymous class referenced by a1 generates a compile-time error as a result of the attempt to extend class A and implement interface B.

Question 8
abstract class A { private int x = 4, y = 2; public A(int i1, int i2) {x=i1;y=i2;} public int x() {return x;} public void x(int x) {this.x = x;} public int y() {return y;} public void y(int y) {this.y = y;} public abstract int math(); } class B { static A a1 = new A(2,1) {public int math() {return x()+y();}}; static A a2 = new A(2,1) {public int math() {return x()-y();}};

static A a3 = new A(2,1) {public int math() {return x()*y();}}; static A a4 = new A(2,1) {public int math() {return x()/y();}}; public static void main(String[] args) { System.out.print("" + a1.math() + a2.math() + a3.math() + a4.math()); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 8 Prints: 3122 Compile-time error Run-time error None of the above

Resposta:

8b

Prints: 3122

The arguments that appear in the class instance creation expression of an anonymous class are passed to a constructor of the superclass.

Encapsulation Question 1
Which of the following are true statements?
a. b. c. d. e. Encapsulation is a form of data hiding. A tightly encapsulated class is always immutable. Encapsulation is always used to make programs run faster. Encapsulation helps to protect data from corruption. Encapsulation allows for changes to the internal design of a class while the public interface remains unchanged.

Resposta:

Encapsulation is a form of data hiding. Encapsulation helps to protect data from a corruption. Encapsulation 1 d allows for changes to the e internal design of a class while the public interface remains unchanged.

A tightly encapsulated class does not allow direct public access to the internal data model. Instead, access is permitted only through accessor (i.e. get) and mutator (i.e. set) methods. The additional time required to work through the accessor and mutator methods typically slows execution speed. Encapsulation is a form of data hiding. A tightly encapsulated class does not allow public access to any data member that can be changed in any way; so encapsulation helps to protect internal data from the possibility of corruption from external influences. The mutator

methods can impose contraints on the argument values. If an argument falls outside of the acceptable range, then a mutator method could throw an IllegalArgumentException. The internal design of a tightly encapsulated class can change while the public interface remains unchanged. An immutable class is always tightly encapsulated, but not every tightly encapsulation class is immutable.

Question 2
Which of the following are true statements?
a. A top-level class can not be called "tightly encapsulated" unless it is declared private. b. Encapsulation enhances the maintainability of the code. c. A tightly encapsulated class allows fast public access to member fields. d. A tightly encapsulated class allows access to data only through accessor and mutator methods. e. Encapsulation usually reduces the size of the code. f. A tightly encapsulated class might have mutator methods that validate data before it is loaded into the internal data model.
Resposta:

The data members of a tightly encapsulated class are declared private; so Encapsulation enhances the changes to the data model are less likely maintainability of the code. A tightly to impact external code. Access to internal encapsulated class allows access to data can be provided by public accessor b data only through accessor and mutator (i.e. get) and mutator (i.e. set) methods. 2 d methods. A tightly encapsulated class The mutator methods can be used to f might have mutator methods that validate the data before it is loaded into validate data before it is loaded into the the internal data model. The use of internal data model. accessor and mutator methods is likely to increase the size of the code and slow execution speed.

Question 3
A class can not be called "tightly encapsulated" unless which of the following is true?

a. b. c. d.

The class is declared final. All local variables are declared private. All method parameters are declared final. No method returns a reference to any object that is referenced by an internal data member. e. None of the above
Resposta:

If a class A has a method that returns a reference to an internal, mutable object; then external code can use the reference to modify the internal None of state of class A. Therefore, class A can not be considered tightly 3 e the encapsulated. However, the methods of a tightly encapsulated class may above return a reference to an immutable object or a reference to a copy or clone of an internal object.

Question 4
A class can not be called "tightly encapsulated" unless which of the following is true?
a. b. c. d. e. f. All of the methods are declared private. All of the methods are synchronized. All local variables are declared final. The class is a direct subclass of Object. Accessor methods are used to prevent fields from being set with invalid data. None of the above

Resposta:

One answer option reads as follows: "Accessor methods are used to prevent fields from being set with invalid data." The answer would be None of correct if the word "Accessor" were replaced by the word "Mutator". 4 f the Accessor methods are used to read data members; mutator methods are above used to set data members. The mutator methods can validate the parameter values before the values are used to change the state of the internal data model.

Question 5
A class can not be called "tightly encapsulated" unless which of the following are true?
a. The data members can not be directly manipulated by external code.

b. The class is declared final. c. It has no public mutator methods. d. The superclass is tightly encapsulated.
Resposta:

The data members can not be directly a 5 manipulated by external code. The d superclass is tightly encapsulated.

If a class A is not tightly encapsulated, then no subclass of A is tightly encapsulated.

Question 6
A class can not be called "tightly encapsulated" unless which of the following is true?
a. b. c. d. e. The class is a nested class. The constructors are declared private. The mutator methods are declared private. The class implements the Encapsulated interface. None of the above

Resposta:

6e

None of the above

A tightly encapsulated class may have public mutator methods.

Question 7
A class can not be called "tightly encapsulated" unless which of the following is true?
a. All member fields are declared final. b. The class is not anonymous. c. The internal data model can be read and modified only through accessor and mutator methods. d. The class is an inner class. e. None of the above
Resposta:

The internal data model can be read and modified only 7c through accessor and mutator methods.

A class is not tightly encapsulated if the internal data model can be read and/or modified without working through accessor (i.e. get) and mutator (i.e. set) methods.

Question 8
class GFC500 {private String name;} class GFC501 { private String name; private void setName(String name) {this.name = name;} private String getName() {return name;} } class GFC502 { private String name; public void setName(String name) {this.name = name;} public String getName() {return name;} }

Which class is not tightly encapsulated?


a. b. c. d. GFC501 GFC502 GFC503 None of the above

Resposta:

8d

All three classes are tightly encapsulated, because the data members are None of private. A tightly encapsulated class can have public accessor and the above mutator methods, but it is not required to have those methods.

Question 9
class GFC505 extends GFC504 { public void setName(String name) {this.name = name;} public String getName() {return name;} } class GFC504 extends GFC503 { private void setName(String name) {this.name = name;} private String getName() {return name;} } class GFC503 {String name;}

Which class is tightly encapsulated?


a. b. c. d. GFC503 GFC504 GFC505 None of the above

Resposta:

9d

None of the above

Class GFC503 is not tightly encapsulated; so no subclass of GFC503 is tightly encapsulated.

Question 10
class GFC506 {private String name;} class GFC507 extends GFC506 { String name; public void setName(String name) {this.name = name;} public String getName() {return name;} } class GFC508 extends GFC506 { private String name; public GFC508(String name) {setName(name);} public void setName(String name) {this.name = name;} public String getName() {return name;} }

Which class is not tightly encapsulated?


a. b. c. d. GFC506 GFC507 GFC508 None of the above

Resposta:

10 b GFC507 Class GFC507 has a public field; so it is not tightly encapsulated.

Garbage Collection Question 1


class B { private String name; public B(String s) {name = s;} protected void finalize() {System.out.print(name);} } class E { public static void m() { B x1 = new B("X"), y1 = new B("Y"); } public static void main(String[] args) { m(); System.gc(); }}

Which of the following could not be a result of attempting to compile and run the program?
a. Prints: XY b. Prints: YX

c. Prints: XXYY d. Nothing is printed. e. None of the above


Resposta:

1c

Prints: XXYY

The program will not print XXYY. Please note that the question asks which could NOT be a result of attempting to compile and run the program. The finalize method of each instance can only run once; so X or Y can never be printed more than once. The instances referenced by x1 and y1 become eligible for garbage collection when method m returns; so both could be finalized at that time, but there is no guarantee that they will be. Even though System.gc is invoked in the main method, there is no guarantee that the garbage collector will run at that time. If the garbage collector does run before the program terminates, then the name of each object could be printed at most one time. The order in which the names are printed depends on the order in which the objects are finalized. If the garbage collector does not run, then nothing will be printed.

Question 2
void m1() { Q q1 = null; for (int i = 0; i < 10; i++) { q1 = new Q(); // 1 m2(q1); // 2 } System.out.print("All done"); // 3 }

When the processing of line 3 begins, how many objects of type Q that were created at line 1 have become eligible for garbage collection?
a. b. c. d. e. f. g. h. 0 1 9 10 Indeterminate. Compile-time error Run-time error None of the above

Resposta:

2 e Indeterminate.

Since we don't know what method m2 might be doing, we can not know if the objects are eligible for garbage collection. Suppose that

method m2 is declared inside of a class that also contains 10 instance variables (instance variables are non-static member fields) that are references to instances of class A. The argument that appears in the method invocation expression m2(q1) is a reference to an instance of class Q. Suppose that m2 saves each argument value in one of the ten instance variables or in an element of an array of type Q[]. When the loop in method m1 runs to completion, each instance of class Q would still be referenced by a one of the ten instance variables. Since the instance variables would continue to reference each instance of class Q when line 3 is executed, none of the instances would be eligible for garbage collection at that point. A second possibility is that method m2 does not save the reference values. In that case, all of the instances that were created inside the loop would be eligible for garbage collection when line 3 is executed.

Question 3
class Q { private int id; protected void finalize() {System.out.print(id);} public Q(int i) {id = i;} } class R { public static void main(String[] args) { Q q1 = null; for (int i = 0; i < 10; i++) {q1 = new Q(i);} // 1 System.gc(); // 2 }}

When the processing of line 2 begins, how many objects of type Q that were created at line 1 have become eligible for garbage collection?
a. b. c. d. e. f. g. h. 0 1 9 10 Indeterminate. Compile-time error Run-time error None of the above

Resposta:

With each pass through the loop, q1 references a new object, and the old object 3 c 9 becomes eligible for garbage collection. When the processing of line 2 begins, the last object referenced by q1 is not eligible for garbage collection.

Question 4
class I { private I other; public void other(I i) {other = i;} } class J { private void m1() { I i1 = new I(), i2 = new I(); I i3 = new I(), i4 = new I(); i1.other(i3); i2.other(i1); i3.other(i2); i4.other(i4); } public static void main (String[] args) { new J().m1(); }}

Which object is not eligible for garbage collection after method m1 returns?
a. b. c. d. e. f. g. i1 i2 i3 i4 Compile-time error Run-time error None of the above

Resposta:

Please note that this question asks which object is NOT eligible for garbage collection after method m1 returns. The objects referenced by i1, i2 and i3 form a ring such that each object is referenced by None of another. Even so, nothing outside of method J.m1 references any of those 4 g the objects. When method J.m1 returns, the ring becomes an island of above isolated objects that are not reachable by any part of the user program. A key point to remember is that an object that is referenced by another object can be eligible for garbage collection if the two objects form an island of isolated objects.

Question 5
class I { private String name; public I(String s) {name = s;} private I other; public void other(I i) {other = i;} }

class J { private I i1 = new I("A"), i2 = new I("B"), i3 = new I("C"); private void m1() { i1.other(i2); i2.other(i1); i3.other(i3); i1 = i3; i2 = i3; m2(); } private void m2() {/* Do amazing things. */} public static void main (String[] args) { new J().m1(); }}

Which of the three objects, A, B or C, is not eligible for garbage collection when method m2 begins to execute?
a. b. c. d. A B C None of the above

Resposta:

Please note that this question asks which objects are NOT eligible for garbage collection when method m2 begins to execute? All three references, i1, i2 and i3, refer to object named C; so C is not eligible for 5 c C garbage collection when method m2 begins to execute. The objects named A and B have references to each other, but no other objects refer to A and B. The objects A and B form an island of islolated objects and are eligible for garbage collection.

Question 6
class I { private String name; protected void finalize() {System.out.print(name);} public I(String s) {name = s;} } class J { private static void m1(I[] a1) { a1[0] = a1[1] = a1[2] = null; } public static void main (String[] args) { I[] a1 = new I[3]; // 1 a1[0] = new I("A"); // 2 a1[1] = new I("B"); // 3 a1[2] = new I("C"); // 4 m1(a1); System.gc(); }}

After method m1 returns, the object created on which line is not eligible for garbage collection?

a. b. c. d. e. f. g.

1 2 3 4 None of the above Compile-time error Run-time error

Resposta:

Please note that this question asks which objects are NOT eligible for garbage collection after method m1 returns. After method m1 returns, the 6 a 1 array a1 created on line 1 is not eligible for garbage collection. Method m1 sets all elements of the array to null; so the objects created on lines 2, 3 and 4 are eligible for garbage collection when method m1 returns.

Question 7
class I { private String name; public String toString() {return name;} public I(String s) {name = s;} } class J { private static void m1(I[] a1) {a1 = null;} public static void main (String[] args) { I[] a1 = new I[3]; // 1 a1[0] = new I("A"); // 2 a1[1] = new I("B"); // 3 a1[2] = new I("C"); // 4 m1(a1); for (int i = 0; i < a1.length; i++) { System.out.print(a1[i]); }}}

After method m1 returns, the object created on which line is eligible for garbage collection?
a. b. c. d. e. f. g. 1 2 3 4 Compile-time error Run-time error None of the above

Resposta:

After method m1 returns, none of the objects are eligible for garbage None of collection. Method m1 sets the parameter variable a1 to null, but that 7 g the does not change the reference a1 in theJ.main method. Since above array a1 continues to reference all three objects, none of the three are eligible for garbage collection.

Question 8
class A { private String name; private A otherA; public A(String name) {this.name = name;} public void other(A otherA) {this.otherA = otherA;} public A other() {return otherA;} public String toString() {return name;} protected void finalize() {System.out.print(name);} } class B { public static void m1() { A a1 = new A("A1"), a2 = new A("A2"), a3 = new A("A3"), a0 = a3; a1.other(a2); a2.other(a3); a3.other(a1); for(int i = 0; i<4; i++){System.out.print(a0 = a0.other());} } public static void main(String[] args) {m1(); System.gc();} }

Which of the following could be a result of attempting to compile and run the program?
a. b. c. d. e. f. A1A2A3A1 A0A0A0A0A1A2A3 A1A2A3A1A2A3 A1A2A3A1A1A2A3 A1A2A3A1A3A2A1 A0A1A2A3A1A2A3

Resposta:

a c 8 d e

The three instances of class A form an isolated ring where each instance references the next instance and the third references the first instance. Four iterations of the for loop are processed. Inside the body of A1A2A3A1 the for statement, the invocation of the print method A1A2A3A1A2A3 contains the argument expression a0 = a0.other(). A1A2A3A1A1A2A3 On the first iteration, the reference variable a0 references A1A2A3A1A3A2A1 the instance named A3. The value returned by the method named other is a reference to the instance named A1. The reference is assigned to the reference variable a0 and is also the value produced by the expression a0 =

a0.other(). That reference value is passed as an argument to the print method, and the print method invokes the A.toString method. With each iteration of the loop, the reference moves to the next object in the loop and the name of the object is printed. After four iterations, the loop ends and the method m1 returns. The invocation of the System.gc method serves as a suggestion that the garbage collector should be allowed to run. The system could ignore the suggestion, so there is no guarantee that the eligible arguments will be garbage collected. If they are collected, there is no guarantee which will be collected first. The only guarantee is that the finalize method will be invoked on each particular instance before the resources that had been allocated to that instance are reclaimed.

Question 9
class B { private String name; public B(String name) {this.name = name;} public String toString() {return name;} protected void finalize() {System.out.print(name);} } class H { static B ba = new B("Ba"); static int i = 1; static B m1(B b) {return b = new B("B" + i++);} public static void main (String[] args) { B x = m1(ba); m1(x); System.out.println(", " + ba + ", " + x); }}

Which of the following could be a result of attempting to compile and run the program?
a. b. c. d. e. f. Ba, B1, B2 B1, Ba, B2 , Ba, B1 B2, Ba, B1 BaB1b2, null, null B1B2, ba, null

Resposta:

, Ba, c 9 B1 B2, d Ba, B1

Class H declares two static member variables named ba and i. The type of i is int, and the value is initialized to 1. The type of ba is B. The declaration of ba contains the class instance creation expression new B("Ba"). The constructor of class B assigns the argument value to the instance variable called name. Inside the main method of class H, the

method invocation expression m1(ba) invokes method m1. The argument is the static member variable ba. The body of method m1 contains a return statement with the expressionb = new B("B" + i++). The assignment expression contains the class instance creation expression new B("B" + i++) which creates a new instance of the class B. For this first invocation of method m1, the argument appearing in the class instance creation expression is the String value B1. The reference to the new String is assigned to the parameter variable b, but that assignment does not change the value of the member variable ba. The value of the assignment expression is the reference to the new instance of class B with the name B1, and that reference value is returned by the method m1. The returned value is assigned to the local variable x. The next statement inside the main method is another invocation of method m1. The argument appearing in the method invocation expression m1(x) is the local reference variable x. The method invocation does not change the value of x. The value returned by this second invocation of m1 is a reference to a new instance of class B that has the name B2. The returned reference value is not assigned to a variable, so the instance named B2 is eligible for garbage collection. There is no guarantee that the garbage collector will run before the print statement is invoked. If it does run, then the instance named B2 could be finalized causing the name to be printed.

Question 10
class B { private String name; public B(String name) {this.name = name;} public String toString() {return name;} protected void finalize() {System.out.print(name);} } class J { static B bc; static int i = 1; static B m1(B b) {bc = b; return new B("B" + i++);} public static void main (String[] args) { B x = m1(new B("Ba")), y = m1(new B("Bb")); System.out.println(", " + x + ", " + y + ", " + bc); }}

Which of the following could be a result of attempting to compile and run the program?
a. b. c. d. BaBb, B1, B2, B2 B1B2, null, null, Bb , Ba, Bb, Bb BaBbB1B2, null, null, null

e. f. g. h.

Ba, B1, B2, Bb Compile-time error Run-time error None of the above

Resposta:

Ba, B1, 10 e B2, Bb

Class J declares two static member variables named bc and i. The type of i is int, and the value is initialized to 1. The type of bc is B. Inside the main method of class J, the method invocation expression m1(new B("Ba")) invokes method m1. The argument is the class instance creation expression new B("Ba"). The constructor of class B assigns the argument value to the instance variable called name, so a new instance of class B named Ba is created. The reference to the new instance of class B is the argument that is passed to method m1. The body of method m1 contains two statements. The first contains the assignment expression bc = b that assigns the value of the method parameter b to the static member variable bc, so bc now references the instance of class B named Ba. The second statement in the body of m1 is a return statement with the class instance creation expression new B("B" + i++). For this first invocation of method m1, the argument appearing in the class instance creation expression is the String value B1. The reference to the new Stringis returned by method m1. The returned value is assigned to the local variable x. Inside the main method, the declaration of the local variable y contains another invocation of methodm1. The argument appearing in the method invocation expression m1(new B("Bb")) is the class instance creation expression new B("Bb"), so the argument value for the invocation of method m1 is a reference to a new instance of class B named Bb. Inside the body of method m1, the reference to the new instance of class B named Bb is assigned to the static member variable Bc. At that point, the instance of class B named Ba becomes eligible for garbage collection. Method m1 returns a reference to a new instance of class B namedB2. There is no guarantee that the garbage collector will run before the print statement is invoked. If it does run, then the instance named Ba could be finalized causing the name to be printed.

Question 11
class I { private String name; public String name() {return name;} public I(String s) {name = s;} } class J { public static void m1(I i) {i = null;} public static void main (String[] args) { I i = new I("X"); // 1 m1(i); // 2

System.out.print(i.name()); // 3 }}

Which of the following is a true statement?


a. b. c. d. e. The object created a line 1 is eligible for garbage collection after line 2. A NullPointerException is generated at line 3. The program compiles, runs and prints X. The program fails to compile. None of the above

Resposta:

The program 11 c compiles, runs and prints X.

The parameter i of method m1 is a copy of the local variable i of method J.main. Setting the parameter variable i of method m1 to null does not change the local variable i of method J.main.

Threads Question 1
Which of the following methods are members of the Object class?
a. b. c. d. e. f. g. h. join notify notifyAll run sleep start yield wait

Resposta:

b c h

notify notifyAll wait

Question 2
Which of the following methods are static members of the Thread class?
a. join

b. c. d. e. f. g. h.

notify notifyAll run sleep start yield wait

Resposta:

e g

sleep yield

Question 3
Which of the following methods are deprecated members of the Thread class?
a. b. c. d. e. f. g. h. i. j. k. join notify notifyAll resume run sleep start stop suspend yield wait

Resposta:

For the purposes of the exam, you don't need to memorize the deprecated methods of d the Thread class. Even though a question such as 3 h resume stop suspend this will not be on the exam, every Java programmer i should know that the deprecated methods should not be used in new programs.

Question 4
Which of the following methods name the InterruptedException in its throws clause?

a. b. c. d. e. f. g. h.

join notify notifyAll run sleep start yield wait

Resposta:

a e h

join sleep wait

Question 5
A timeout argument can be passed to which of the following methods?
a. b. c. d. e. f. g. h. join notify notifyAll run sleep start yield wait

Resposta:

a e h

join sleep wait

Question 6
Which of the following instance methods should only be called by a thread that holds the lock of the instance on which the method is invoked?
a. b. c. d. e. f. join notify notifyAll run start wait

Resposta:

b c f

notify notifyAll wait

Question 7
Which of the following is a checked exception?
a. b. c. d. e. IllegalMonitorStateException IllegalThreadStateException IllegalArgumentException InterruptedException None of the above

Resposta:

The d InterruptedExc methods Object.wait, Thread.join and Thread.sleep name Int 7 eption erruptedException in their throws clauses.

Question 8
Which kind of variable would you prefer to synchronize on?
a. A member variable of a primitive type b. A member variable that is an object reference c. A method local variable that is a reference to an instance that is created within the method d. None of the above
Resposta:

Primitives don't have locks; therefore, they can not be used to synchronize threads. A method local variable that is a reference to an instance that is created within the method should not be used to A member synchronize threads, because each thread has its own instance of variable that is 8b the object and lock. Synchronization on an instance that is created an object locally makes about as much sense as placing on your doorstep a reference box full of keys to the door. Each person that comes to your door would have their own copy of the key; so the lock would provide no security.

Question 9

synchronized (expression) block

The synchronized statement has the form shown above. Which of the following are true statements?
a. b. c. d. e. f. g. h. i. A compile-time error occurs if the expression produces a value of any reference type A compile-time error occurs if the expression produces a value of any primitive type A compile-time error does not occur if the expression is of type boolean The sychronized block may be processed normally if the expression is null If execution of the block completes normally, then the lock is released If execution of the block completes abruptly, then the lock is released A thread can hold more than one lock at a time Synchronized statements can be nested Synchronized statements with identical expressions can be nested

Resposta:

A compile-time error occurs if the expression produces a value of any primitive b type If execution of the block completes normally, then the lock is released If e f 9 execution of the block completes abruptly, then the lock is released A thread can g hold more than one lock at a time Synchronized statements can be h i nested Synchronized statements with identical expressions can be nested

Question 10
Which of the following is a true statement?
a. The process of executing a synchronized method requires the thread to acquire a lock b. Any overriding method of a synchronized method is implicitly synchronized c. If any method in a class is synchronized, then the class itself must also be declared using the synchronized modifier d. If a thread invokes a static synchronized method on an instance of class A, then the thread must acquire the lock of that instance of class A e. None of the above
Resposta:

The synchronized modifier can not be applied to a class. A method that overrides a synchronized method does not The process of have to be synchronized. If a thread invokes a synchronized executing a instance method on an instance of class A, then the thread synchronized 10 a must acquire the lock of that instance of class A. The same method requires the is not true for synchronized static methods. A synchronized thread to acquire a static method is synchronized on the lock for lock the Class object that represents the class for which the method is a member.

Question 11
Which of the following thread state transitions model the lifecycle of a thread?
a. b. c. d. e. f. g. The Dead state to the Ready state The Ready state to the Not-Runnable state The Ready state to the Running state The Running state to the Not-Runnable state The Running state to the Ready state The Not-Runnable state to the Ready state The Not-Runnable state to the Running state

Resposta:

c The Ready state to the Running state The Running state to 11 d the Not-Runnable state The Running state to the Ready e f state The Not-Runnable state to the Ready state

A dead thread can not be restarted.

Question 12
Which of the following are true statements?
a. b. c. d. e. f. g. The Thread.yield method might cause the thread to move to the Not-Runnable state The Thread.yield method might cause the thread to move to the Ready state The same thread might continue to run after calling the Thread.yield method The Thread.yield method is a static method The behavior of the Thread.yield method is consistent from one platform to the next The Thread.sleep method causes the thread to move to the Not-Runnable state The Thread.sleep method causes the thread to move to the Ready state

Resposta:

b c 12 d f

The Thread.yield method might cause the thread to move to the Ready state The same thread might continue to run after calling the Thread.yield method The Thread.yield method is a static method The Thread.sleep method causes the thread to move to the Not-Runnable state

The Thread.yield method is intended to cause the currently executing thread to move from the Running state to the Ready state and offer the thread scheduler an opportunity to allow a different thread to execute based on the discretion of the thread scheduler. The

thread scheduler may select the same thread to run immediately, or it may allow a different thread to run. The Thread.yield method is a native method; so the behavior is not guaranteed to be the same on every platform. However, at least some implementations of the yield method will not yield to a thread that has a lower priority.

Question 13
Which of the following will not force a thread to move into the NotRunnable state?
a. b. c. d. e. f. g. Thread.yield method Thread.sleep method Thread.join method Object.wait method By blocking on I/O Unsuccessfully attempting to acquire the lock of an object None of the above

Resposta:

The Thread.yield method may cause a thread to move into the Ready state, but that state transition is not guaranteed. The JLS states that theThread.yield method provides a hint 13 a Thread.yield method to the thread scheduler, but the scheduler is free to interpret--or ignore--the hint as it sees fit. Nothing in the JLS suggests that the thread might move to the NotRunnable state.

Question 14
Which of the following will cause a dead thread to restart?
a. Thread.yield method b. Thread.join method

c. Thread.start method d. Thread.resume method e. None of the above


Resposta:

14 e None of the above

A dead thread can not be restarted.

Question 15
When a thread is created and started, what is its initial state?
a. b. c. d. e. f. New Ready Not-Runnable Runnning Dead None of the above

Resposta:

15

Ready

Question 16
Which of the following are true statements?
a. The Thread.run method is used to start a new thread running b. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler c. The Runnable interface declares the start method d. The Runnable interface declares the run method e. The Thread class implements the Runnable interface f. If an Object.notify method call appears in a synchronized block, then it must be the last method call in the block g. No restriction is placed on the number of threads that can enter a synchronized method h. Some implementations of the Thread.yield method will not yield to a thread of lower priority
Resposta:

16

b The Thread.start method causes a new The Object.notify method can only d thread to get ready to run at the discretion of be called by the thread that holds

e the thread h scheduler TheRunnable interface declares the run method TheThread class implements the Runnable interface Some implementations of the Thread.yield method will not yield to a thread of lower priority

the lock of the object on which the method is invoked. Suppose that thread T1enters a block that is synchronized on an object, A. Within the block, thread T1 holds the lock of A. Even if thread T1 calls the notify method immediately after entering the synchronized block, no other thread can grab the lock of object A until T1 leaves the synchronized block. For that reason, the transfer of control from thread T1 to any waiting thread can not be accelerated by moving the notify method to an earlier point in the synchronized block. The behavior of Thread.yield is platform specific. However, at least some implementations of the yield method will not yield to a thread that has a lower priority. Invoking the Thread.yield method is like offering a suggestion to the JVM to allow another thread to run. The response to the suggestion is platform specific.

Question 17
Which of the following are true statements?
a. b. c. d. e. f. g. h. i. Thread.MAX_PRIORITY == 10 Thread.MAX_PRIORITY == 5 Thread.NORM_PRIORITY == 5 Thread.NORM_PRIORITY == 3 Thread.NORM_PRIORITY == 0 Thread.MIN_PRIORITY == 1 Thread.MIN_PRIORITY == 0 Thread.MIN_PRIORITY == -5 Thread.MIN_PRIORITY == -10

Resposta:

17

a c Thread.MAX_PRIORITY == 10 Thread.NORM_PRIORITY == f 5 Thread.MIN_PRIORITY == 1

Question 18
Which of the following are true statements?
a. b. c. d. e. A program will terminate only when all daemon threads stop running A program will terminate only when all user threads stop running A daemon thread always runs at Thread.MIN_PRIORITY A thread inherits its daemon status from the thread that created it The daemon status of a thread can be changed at any time using the Thread.setDaemon method f. The Thread.setDaemon method accepts one of two argument values defined by the constants Thread.DAEMON and Thread.USER
Resposta:

18

b A program will terminate only when all user threads stop running A thread d inherits its daemon status from the thread that created it

Question 19
class A extends Thread { public A(Runnable r) {super(r);} public void run() {System.out.print("A");} } class B implements Runnable { public void run() {System.out.print("B");} } class C { public static void main(String[] args) { new A(new B()).start(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: A Prints: B Prints: AB Prints: BA Compile-time error Run-time error None of the above

Resposta:

19 a

Prints: If a Runnable target object is passed to the constructor of A

the Thread class, then the Thread.run method will invoke the run method of theRunnable target. In this case, the Thread.run method is overridden by A.run. The A.run method does nothing more than print the letter A. The invocation of the A.start method inside the main method results in the invocation of A.run, and the letter A is printed. The B.run method is never invoked.

Question 20
class A implements Runnable { public void run() {System.out.print(Thread.currentThread().getName());} } class B implements Runnable { public void run() { new A().run(); new Thread(new A(),"T2").run(); new Thread(new A(),"T3").start(); }} class C { public static void main (String[] args) { new Thread(new B(),"T1").start(); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: T1T1T1 Prints: T1T1T2 Prints: T1T2T2 Prints: T1T2T3 Prints: T1T1T3 Prints: T1T3T3 Compile-time error Run-time error None of the above

Resposta:

Prints: 20 e T1T1T3

The Thread.currentThread method returns a reference to the currently executing thread. When the run method is invoked directly it does not start a new thread; so T1 is printed twice.

Question 21
class AnException extends Exception {} class A extends Thread { public void run() throws AnException {

System.out.print("A"); throw new AnException(); }} class B { public static void main (String[] args) { A a = new A(); a.start(); System.out.print("B"); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: A Prints: B Prints: AB Prints: BA Compile-time error Run-time error None of the above

Resposta:

21 e

Compiletime error

The Runnable.run method does not have a throws clause; so any implementation of run can not throw a checked exception.

Question 22
class A extends Thread { public void run() {System.out.print("A");} } class B { public static void main (String[] args) { A a = new A(); a.start(); a.start(); // 1 } }

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. The program compiles and runs without error The second attempt to start thread t1 is successful The second attempt to start thread t1 is ignored Compile-time error at marker 1 An IllegalThreadStateException is thrown at run-time None of the above

Resposta:

For the purposes of the exam, invoking 2 e An IllegalThreadStateExcept the start method on a thread that has 2 ion is thrown at run-time already been started will generate

anIllegalThreadStateExceptio n. The actual behavior of the method might be different. If the start method is invoked on a thread that is already running, then an IllegalThreadStateExcepti on will probably be thrown. However, if the thread is already dead then the second attempt to start the thread will probably be ignored, and no exception will be thrown. For the purposes of the exam, the exception is always thrown in response to the second invocation of the start method. This is a case where the exam tests your knowledge of the specification and ignores the actual behavior of the 1.4 version of the JVM.

Hashcodes Question 1
Suppose that an instance of class C has legal implementations of the hashCode and equals methods. Within any one execution of the Java application, the hash code contract requires that each invocation of the hashCode method on the same instance of class C must consistently return the same result as long as the fields used for theequals comparison remain unchanged. Resposta:
a. b. false true 1 b true

Question 2
If two instances of a class type are equal according to the equals method, then the same integer value must be returned by the hashCode method of the two objects.

a. false b. true
Resposta:

If two objects are equal according to the equals method, then the hashcodes produced by the hashCode method must also be equal. If two objects are not equal according to the equals method, then the hashcodes may or may 2 b true not be equal. It is preferable that unequal objects have different hashcodes, but that is not always possible. Since the hash code value is a 32 bit primitive int, it is not possible to produce a unique hash code for each value of a primitive long.

Question 3
If two instances of a class type are not equal according to the equals method, then the same integer value must not be returned by the hashCode method of the two objects.
a. false b. true
Resposta:

If two objects are equal according to the equals method, then the hashcodes must also be equal. If two objects are not equal according to the equals method, then the hashcodes may or may not be equal. It is 3 a false preferable that unequal objects have different hashcodes, but that is not always possible. Since the hash code value is a 32 bit primitiveint, it is not possible to produce a unique hash code for each value of a primitive long.

Question 4
class A { static void m1 (B a, B b, B c, B d, B e, B f, B g, B h) { if (a.equals(b)) {System.out.print("A");} if (!c.equals(d)) {System.out.print("B");} if (e.hashCode() == f.hashCode()) {System.out.print("C");} if (g.hashCode() != h.hashCode()) {System.out.print("D");} }}

Suppose that method m1 is invoked with eight instances of the same class and the output is ABCD. If the B.equals and B.hashCode methods are implemented according to the hash code contract, then which of the following statements must always be true?

a. b. c. d.

(a.hashCode() == b.hashCode()) (c.hashCode() != d.hashCode()) (e.equals(f)) (!g.equals(h))

Resposta:

a (a.hashCode() == d b.hashCode()) (!g.equals(h))

If two objects are equal according to the equals method, then the hashcodes must also be equal. If two objects are not equal according to the equals method, then the hashcodes may or may not be equal. If two objects have the same hash code, then the objects may or may not be equal. If two objects have different hashcodes, then the objects must not be equal.

Question 5
class B { private int i1; public int hashCode() {return 1;} } class C { private int i1; public int hashCode() {return -1;} } class D { private int i1; public int hashCode() {return i1;} }

Suppose that the equals method of classes B, C and D all make use of the value of the int variable, i1. Which class has a hashCode method that is not consistent with the hash code contract?
a. b. c. d. B C D None of the above

Resposta:

5d

None of Suppose that the hashCode method is invoked on the same object more the than once during the same execution of a Java application. If no

above

information used in the equalscomparison is modified, then each invocation of the hashCode method must produce the same hash code value. The hashCode methods of classes B and C will always return the same value during an execution of the Java application and are therefore consistent with the hash code contract. Even so, the hashCode methods of classes B and C are not efficient, because they will cause hashtables to place every instance of classes B and C in the same bucket. The hashCode method of class D is appropriate and will allow a hash table to operate efficiently.

Question 6
Which of the following classes override both the equals and hashCode methods?
a. b. c. d. e. java.lang.Byte java.lang.Integer java.util.Vector java.lang.String java.lang.StringBuffer

Resposta:

a b 6 c d

The wrapper classes and the collection classes override the equals and hash Code methods. java.lang.Byte java.lang.Integer java.ut The String class il.Vector java.lang.String overrides the equals and hash Code methods, butStringBuffer d oes not.

Question 7
class A { int i1, i2; public void setI1(int i) {i1 = i;} public int getI1() {return i1;} public void setI2(int i) {i2 = i;} public int getI2() {return i2;} public A(int ii1, int ii2) {i1 = ii1; i2 = ii2;} public boolean equals(Object obj) { if (obj instanceof A) {

return (i1 == ((A)obj).getI1()); } return false; } public int hashCode() { // Insert statement here. }}

Which of the following statements could be inserted at the specified location without violating the hash code contract?
a. b. c. d. return return return return 31; getI1(); getI2(); 31 * getI1() + getI2();

Resposta:

return a 31; return 7 b getI1();

A hashCode method that returns the constant value 31 is consistent with the hash code contract. Even so, a hashCode method that returns the same value regardless of the internal state of the object is not very good, because it will cause hashtables to place every instance of the class in the same bucket. If the equals method determines that two instances are equal, then the two instances must produce the same hash code. For that reason, the hash code must not be calculated using fields that are not used to determine equality. In this case, the equals method determines equality based on the value of i1. The value of i2 is not used to determine equality; therefore, i2 can not be used to calculate the hash code.

Question 8
class A { int i1, i2; public void setI1(int i) {i1 = i;} public int getI1() {return i1;} public void setI2(int i) {i2 = i;} public int getI2() {return i2;} public A(int ii1, int ii2) {i1 = ii1; i2 = ii2;} public boolean equals(Object obj) { if (obj instanceof A) { return (i1 == ((A)obj).getI1()) & (i2 == ((A)obj).getI2()); } return false; } public int hashCode() { // Insert statement here. }}

If inserted at the specified location, which of the following statements would produce the most efficient hashCode method?
a. b. c. d. e. f. return 31; return getI1(); return getI2(); return getI1() + getI2(); return 31 * getI1() + getI2(); None of the above

Resposta:

All of the statements would produce a hashCode method that is consistent with the hash code contract. The expression 31 * getI1() + getI2() produces the most return 31 * efficient hashCode method, because it is most likely to produce 8 e getI1() + unique hashcodes for various combinations of i1 and i2. The getI2(); expression getI1() + getI2() is less efficient, because it produces the same hash code when the values of i1 and i2 are swapped.

String and StringBuffer Question 1


Which of the following are not methods of the java.lang.String class?
a. b. c. d. e. f. g. append concat delete insert replace substring valueOf

Resposta:

The StringBuffer class has methods named append, delete and insert, but a 1 c append delete insert the String class does not. A typical trick question d will attempt to invoke StringBuffermethods on a String instance.

Question 2
Which of these methods modify the contents of the String instance on which it is invoked?
a. b. c. d. e. f. g. h. append concat delete insert replace substring valueOf None of the above.

Resposta:

Strings are immutable. No method of the of a String class will change the contents of a String instance. Some String methods such None as concat, replace, substring andtrim will return a 2 h of the new String with the desired modifications. above. The StringBuffer methods append, delete and insert are not members of the java.lang.String class. A typical trick question will attempt to invoke StringBuffer methods on a String instance.

Question 3
class MWC204 { static void m1(StringBuffer s1) { s1 = s1.append("B"); System.out.print(s1); } static void m2(StringBuffer s1) { s1.append("C"); System.out.print(s1); } public static void main(String[] s) { StringBuffer s1 = new StringBuffer("A"); m1(s1); m2(s1); System.out.print(s1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: AAA Prints: ABAA Prints: ABACA Prints: ABABAB Prints: ABABCAB

f. g. h. i. j.

Prints: ABABCABC Prints: ABCABCABC Compile-time error Run-time error None of the above

Resposta:

Instances of type StringBuffer are not immutable. In method m1, the method invocation expression s1.append("B") appends the String literal "B" to the StringBufferinstance referenced by variable s1. The append method returns a reference to the same StringBuffer instance on which it is invoked; so the assignment expression s1 = s1.append("B") does not assign a different reference value to variable s1. The new value, AB, is printed in method m1. In method m2, the method invocation 3 f Prints:ABABCABC expressions1.append("C") appends the String literal "C" to the StringBuffer instance referenced by variable s1. The new value, ABC, is printed in method m2. In the main method, a copy of the reference value contained by the reference variable s1 is passed as an argument to methods m1 and m2. Since StringBuffer instances are not immutable, methods m1 andm2 are able to change the original StringBuffer instance that is declared in the main method. The new value, ABC, is printed in the main method.

Question 4
Which of these methods is a static member of the java.lang.String class?
a. b. c. d. e. f. g. h. append concat delete insert replace substring valueOf None of the above.

Resposta:

The valueOf method is static. It returns a String representation of the argument. The StringBuffer methods append, delete and insert are 4 g valueOf not members of thejava.lang.String class. A typical trick question will attempt to invoke StringBuffer methods on a String instance.

Question 5
class MWC205 { static void m1(StringBuffer s1) { s1.append("B"); System.out.print(s1); } static void m2(StringBuffer s1) { s1 = new StringBuffer("C"); System.out.print(s1); } public static void main(String[] s) { StringBuffer s1 = new StringBuffer("A"); m1(s1); m2(s1); System.out.print(s1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: AAA Prints: ABCA Prints: ABCAB Prints: ABCABC Prints: ABCAC Prints: ABABCABC Compile-time error Run-time error None of the above

Resposta:

Instances of type StringBuffer are not immutable. In method m1, the method invocation expression s1.append("B") appends the String literal "B" to the StringBufferinstance referenced by the parameter variable s1. The new value, AB, is 5 c Prints: ABCAB printed in method m1. The reference variable s1 declared in the main method refers to the same modifiedStringBuffer instance. In method m2, the class instance creation expression new StringBuffer("C") creates a new instance of type StringBuffer containing the value C. The assignment

expression s1 = new StringBuffer("C") assigns a reference to the new StringBuffer instance to the method parameter variable s1. The value C is printed in method m1. The method local reference variable s1 in the main method remains unchanged by the assignment expression contained in method m2. In the main method, a copy of the reference value contained by the reference variable s1 is passed as an argument to methods m1 and m2. Since StringBuffer instances are not immutable, method m1 is able to change the original instance of the StringBuffer declared in the main method. Since references are passed by value, method m2 can not change the reference variable declared in the main method. Regardless of anything that happens in method m2, the reference variable s1 that is declared in the main method will continue to reference the original StringBuffer instance. Since the content of the original instance was modified by method m1, the new value, AB, is printed in the main method.

Question 6
class MWC106 { static void m1(String s) { s = s.trim(); s = s.concat("D"); } public static void main(String[] s) { String s1 = "A", s2 = " B ", s3 = "C"; m1(s2); System.out.print(s1 + s2 + s3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: ABC Prints: A B C Prints: ABCD Prints: ABDC Prints: A B CD Prints: A B DC Compile-time error Run-time error None of the above

Resposta:

6b

Prints: A The String instance referenced by s2 is passed to the m1 method by passing the value of the reference. The reference value used in B C

method m1 is a local copy of the reference. If the local copy used in method m1 is changed, then the original reference variable in the main method remains unchanged.

Question 7
class MWC107 { public static void main(String[] s) { String s1 = "A", s2 = " B ", s3 = "C"; s2.trim(); s3.concat("D"); System.out.print(s1 + s2 + s3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: ABC Prints: A B C Prints: ABCD Prints: ABDC Prints: A B CD Prints: A B DC Compile-time error Run-time error None of the above

Resposta:

Strings are immutable. No method will change the contents of a String instance. Some String methods such Prints: A as concat, replace, substring and trim will return a 7b B C newString instance with the desired modifications. In this case, the String instances returned by the methods trim and concat are ignored.

Question 8
class MWC108 { public static void main(String[] s) { String s1 = "A", s2 = " B ", s3 = "C"; s2.trim(); s3.append("D"); System.out.print(s1 + s2 + s3); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g. h. i.

Prints: ABC Prints: A B C Prints: ABCD Prints: ABDC Prints: A B CD Prints: A B DC Compile-time error Run-time error None of the above

Resposta:

8g

Compiletime error

The StringBuffer class has an append method, but the String class does not. A compile-time error is generated due to the attempt to invoke the append method on an instance of type String.

Question 9
class MWC110 { static void m1(String s1, String s2) { s1.insert(1,"D"); s1 = s1 + s2; } public static void main(String[] s) { String s1 = "A", s2 = "B"; m1(s1,s2); System.out.print(s1 + s2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: AB Prints: ABB Prints: ADB Prints: ADBB Compile-time error Run-time error None of the above

Resposta:

9e

Compiletime error

The StringBuffer class has an insert method, but the String class does not. A compile-time error is generated due to the attempt to invoke the insert method on an instance of type String.

Question 10
class MWC111 { static void m1(String s1) { s1.replace('A','Y'); System.out.print(s1); } static void m2(String s1) { s1 = s1.replace('A','Z'); System.out.print(s1); } public static void main(String[] s) { String s1 = "A"; m1(s1); m2(s1); System.out.print(s1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: AAA Prints: YZA Prints: YAA Prints: AZA Prints: AZZ Compile-time error Run-time error None of the above

Resposta:

Instances of type String are immutable. In method m1, the replace method returns a new instance of type String that contains the value Y, but the String instance referenced bys1 remains unchanged. The original value, A, is printed in method m1. In method m2, the replace method returns a new instance of type String that contains the value Z, and a reference to the new instance is assigned to reference variable s1. The new value, Z, is printed in method m2. In the main method, a copy of the reference value contained by the reference variable s1 is passed 10 d Prints: AZA as an argument to methods m1 and m2. Since String instances are immutable, methods m1 and m2 can not change the original String instance that is declared in the mainmethod. Since references are passed by value, methods m1 and m2 can not change the reference variable declared in the main method. Regardless of anything that happens in methods m1 andm2, the reference variable s1 that is declared in the main method will continue to reference the original String instance that contains the value A.

Question 11

class MWC112 { static void m1(String s1) { s1 = s1.toUpperCase(); System.out.print(s1); } static void m2(String s1) { s1.toLowerCase(); System.out.print(s1); } public static void main(String[] s) { String s1 = "Ab"; m1(s1); m2(s1); System.out.print(s1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: AbAbAb Prints: ABabab Prints: ABabAb Prints: ABAbAb Prints: Ababab Compile-time error Run-time error None of the above

Resposta:

Instances of type String are immutable. In method m1, the toUpperCase method returns a new instance of type String that contains the value AB, and a reference to the new instance is assigned to reference variable s1. The new value, AB, is printed in method m1. In method m2, the toLowerCase method returns a new instance of type String that contains the valueab, but the String instance referenced by s1 remains unchanged. The original value, Ab, is printed in method m2. In the main method, a copy of the reference value contained by the 11 d Prints:ABAbAb reference variable s1 is passed as an argument to methods m1 and m2. Since String instances are immutable, methods m1 and m2 can not change the original String instance that is declared in the main method. Since references are passed by value, methods m1 and m2 can not change the reference variable declared in the main method. Regardless of anything that happens in methods m1 and m2, the reference variable s1 that is declared in the main method will continue to reference the original String instance that contains the value Ab.

Question 12
class MWC113 { public static void main(String[] s) { String s1 = "1", s2 = "2", s3 = s1 + s2; s1 += s2; s3 += s1; System.out.println(s3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 3 Prints: 6 Prints: 33 Prints: 1212 Compile-time error Run-time error None of the above

Resposta:

The reference variable s3 is initialized with a reference to an instance of type String containing the value "12". The expression s1 += s2 is equivalent to the expression s1 = s1 12 d Prints: 1212 + s2. Further simplification produces s1 = "1" + "2" = "12". The expression s3 += s1 is equivalent to the expression s3 = "12" + "12" = "1212".

Question 13
class MWC114 { public static void main(String[] s) { String s1 = new String("ABCDEFG"), s2 = new String("EFGHIJ"); String s3 = s1.substring(4,7), s4 = s2.substring(0,3); System.out.println((s3 == s4) + "," + (s3 + s4).equals(s4 + s3)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

The reference variable s1 is initialized with a reference to an instance of type String containing the value "ABCDEFG". The reference variable s2 is initialized with a reference to an instance of type String containing the value "EFGHIJ". The expression s3 = s1.substring(4,7) initializes the reference variable s3 with a reference to a unique instance of typeString containing the value "EFG". The expression s4 = s2.substring(0,3) initializes the reference variable s4 with a reference to a unique instance of type Stringcontaining the value "EFG". The 13 b Prints:false,true expression s3 == s4 compares two unique reference values and produces the value false even though s3 and s4 reference two String instances that contain the same value, "EFG". The expression s3 + s4 produces a unique instance of type String containing the value "EFGEFG". Similarly, the expression s4 + s3 produces a unique instance of type String containing the value "EFGEFG". The expression (s3 + s4).equals(s4 + s3) compares the contents of two unique instances of type Stringthat contain the value "EFGEFG". The result of the comparison is true.

Question 14
class MWC115 { public static void main(String[] s) { String s1 = new String("ABCDEFG"), s2 = s1.substring(0,3); String s3 = s1.substring(4,6); char c1 = s1.charAt(3); System.out.println(s2.concat(String.valueOf(c1)).concat(s3)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: "ABCDEFG" Prints: "ABCEFG" Prints: "ABCDDEFG" Prints: "ABCDEF" Prints: "ABCEF" Prints: "ABCDDEF" Compile-time error Run-time error None of the above

Resposta:

The reference variable s1 is initialized with a reference to an instance of type String containing the value "ABCDEFG". The expression s2 = s1.substring(0,3) initializes the reference variable s2 with a reference to a unique instance of type String containing the value "ABC". The expression s3 = s1.substring(4,6) creates a unique instance of typeString containing the value "EF". The expression c1 = s1.charAt(3) initializes the primitive variable c1 with the value 'D'. The expression String.valueOf(c1) invokes the static valueOf method with an argument of type primitive char and value 'D'. The valueOf method creates a new instance of type String. The value contained by the new 1 d Prints:"ABCDE instance is "D". The 4 F" expression s2.concat(String.valueOf(c1)) invokes the concat method on the instance of type String referenced by the variable s2. The instance referenced by s2 contains the value "ABC". The value contained by the argument is "D". The result of the concatenation operation is a new instance of type String containing the value"ABCD". The expression s2.concat(String.valueOf(c1)).concat (s3) invokes the concat method on the previously created instance containing the value "ABCD". The instance referenced by the argument s3 contains the value "EF". The result of the concatenation operation is a new instance of type String containing the value "ABCDEF".

Question 15
class MWC118 { public static void main(String[] args) { byte[] b = {'a', 'b', 'c'}; char[] c = {'a', 'b', 'c'}; String s = "abc"; StringBuffer sb = new StringBuffer("abc"); byte b2 = 'a'; char c2 = 'a'; String s1 = new String(b); // 1 String s2 = new String(c); // 2 String s3 = new String(s); // 3 String s4 = new String(sb); // 4 String s5 = new String(b2); // 5 String s6 = new String(c2); // 6 }}

Compile-time errors are generated at which lines?


a. 1

b. c. d. e. f.

2 3 4 5 6

Resposta:

The overloaded contructors for the String class accept a parameter of type String or StringBuffer or an array of byte or char. There is e 15 5 6 no constructor that will accept a primitive byte or char. Please note that if f you want to convert a primitive to a String then you can use the static String.valueOf method.

Question 16
class MWC101 { public static void main(String[] args) { String s1 = "A", s2 = "a", s3 = "b"; s1.toLowerCase(); s3.replace('b','a'); System.out.print((s1.equals(s2)) + "," + (s2.equals(s3))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

String instances are immutable. String methods such as String.toLowerCase and String.replace create and return a new String instance. The instance on which the method has been Prints: 16 a false,false invoked remains unchanged. In the program, the equals method is invoked on the original instances of s1 and s2--not the new instances.

Question 17
class MWC200 { public static void main (String[] args) {

String s1 = "ABC"; StringBuffer s2 = new StringBuffer(s1); System.out.print(s2.equals(s1) + "," + s1.equals(s2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

StringBuffer.equals does not override the Object.equals method; so StringBuffer.equals just compares reference values. Since the reference variables s1 and s2 refer to different objects, the equals method of the StringBuffer instance s2 returns the value false. The String.equals method does override Prints: 17 a false,false the Object.equals, method. The String.equals method returns falseanytime the argument is not an instance of type String. The method invocation expression s1.equals(s2) produces the value false, because the argument is an instance of typeStringBuffer.

Question 18
class MWC102 { public static void main (String[] args) { String s1 = "ABCDE"; System.out.print(s1.substring(1,2)+s1.substring(3)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: AABC Prints: ACDE Prints: ABABC Prints: ABCDE Prints: BABCD Prints: BDE Prints: BCABCD Prints: BCDE

i. Compile-time error j. Run-time error k. None of the above


Resposta:

The substring method returns a new String instance that is a substring of the original String instance. The single parameter form of Prints: the substring method creates a newString that begins at the index 18 f BDE specified by the argument value. The two parameter form creates a substring that starts at the index of the first parameter and ends at the index of the second parameter. The character at the start index is included in the substring, but the character at the end index is not.

Question 19
class MWC201 { public static void main (String[] args) { String s1 = new String("ABC"), s2 = new String("ABC"); StringBuffer sb1 = new StringBuffer(s1); StringBuffer sb2 = new StringBuffer(s2); System.out.print(s1.equals(s2) + "," + sb1.equals(sb2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

String.equals overrides Object.equals. The String.equals method compares the contents of the String instances--not the references. Since the contents of s1 and s2 are the same, the method invocation expression s1.equals(s2) produces the value true. Prints: The StringBuffer.equals method does not override Object.equals. 19 c true,false The StringBuffer.equals method compares the reference values--not the contents of the StringBuffer instances. Since the reference values sb1 and sb2 are different, the method invocation expression sb1.equals(sb2) produces the value false.

Question 20
class MWC104 { public static void main (String[] args) { char[] c = {'a','b','c','d'}; String s1 = new String(c); boolean b = true; for (int i = 0; i < s1.length; i++) { b &= (c[i] == s1.charAt(i)); } System.out.print(b); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false Prints: true Compile-time error Run-time error None of the above

Resposta:

20 c

Compile-time A compile-time error is generated due to the attempt to access the error length method of the String class as though it were a variable.

Question 21
class MWC202 { public static void main (String[] args) { StringBuffer sb1 = new StringBuffer("ABC"); StringBuffer sb2 = new StringBuffer("ABC"); System.out.print((sb1==sb2)+","+sb1.equals(sb2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

21 a

Prints: StringBuffer.equals does not override Object.equals. false,false The StringBuffer.equals method compares the reference values--not

the contents of the StringBuffer instances. The expressionssb1==sb2 and sb1.equals(sb2) produce the same results.

Question 22
class MWC203 { public static void main (String[] args) { String s1 = new String("ABC"), s2 = new String("ABC"); StringBuffer sb1 = new StringBuffer(s1); StringBuffer sb2 = new StringBuffer(s2); boolean b1 = s1.hashCode() == s2.hashCode(); boolean b2 = sb1.hashCode() == sb2.hashCode(); System.out.print(b1 + "," + b2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

The StringBuffer class does not override the equals and hashCode methods of the Object class. The Object.equals method does not return the value true unless the argument is a reference to the same object on which the method is invoked. For example, the method invocation expression obj1.equals(obj2) only produces the value true when obj1 == obj2 is also true. The Object.hashCode method tends to return distinct hashcode values for distinct objects regardless of the internal contents of the object. Prints: Suppose that the reference variables sb1 and sb2 are of 22 c true,false type StringBuffer. The expression sb1.hashCode() == sb2.hashCode() will not produce the value true unless the expression sb1 == sb2 is also true. The String class does override the equals and hashCode methods of the Object class. The String.hashCode method returns a hashcode value that is computed based on the contents of the String object. Suppose that the reference variables s1 and s2 are of type String. The expression s1.hashCode() == s2.hashCode() must produce the value true anytime the method invocation

expression s1.equals(s2) produces the value true.

Question 23
class MWC109 { public static void main(String args[]) { String a = "A", b = "B", c = a+b, d = a+b; System.out.print(((a+b)==(a+b)) + ","); System.out.print((c==d) + ","); System.out.print(c.equals(d)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true

Resposta:

At run-time, the expression a+b is evaluated four times. Each evaluation produces a new String instance containing the value "AB". Each of the four instances has a unique reference. If any two of the four instances appear as the operands of the equality operator, then the result is always false. The left and right operands of the equality Prints: expression (a+b)==(a+b) reference 23 b false,false,true unique String instances. Since the two references are not the same, the equality expression produces the value false. Similarly, the expression c==d produces the value false. Since the contents of the String instances referenced by c and d are the same, the method invocation expression c.equals(d) produces the value true.

Question 24
class MWC116 { public static void main(String[] args) { String s1 = " B C D E "; System.out.print('A' + s1.trim() + 'F'); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: ABCDEF Prints: A B C D E F Prints: A BCDEF Prints: ABCDE F Prints: AB C D EF Compile-time error Run-time error None of the above

Resposta:

24 e

Prints: AB C D EF

The trim method creates a new String instance with the leading and trailing white space removed.

Question 25
class MWC117 { public static void main (String[] args) { System.out.print(String.valueOf(1) + String.valueOf(2)); String s1 = "S1"; String s2 = s1.toString(); System.out.print("," + (s1==s2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 3,false Prints: 3,true Prints: 12,false Prints: 12,true Compile-time error Run-time error None of the above

Resposta:

25 d

Prints: 12,true

The valueOf method returns a String representation of the input parameter. The input parameter may be of type Object, char[], or any primitive type. The toString method returns a reference to the existing String instance. It does not create a new instance of the String.

Math Question 1
class SRC102 { public static void main (String[] args) { int i1 = Math.round(0.5f); int i2 = Math.round(1.5d); System.out.print(i1 + "," + i2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 0,1 Prints: 0,2 Prints: 1,1 Prints: 1,2 Compile-time error Run-time error None of the above

Resposta:

There are two versions of the Math.round method. One accepts an argument of type float; the return type is int. The other accepts an Compileargument of type double; the return type islong. A compile-time 1e time error error is generated here due to the attempt to assign the long return value to the int variable, i2.

Question 2
class SRC103 { public static void main (String[] args) { int i1 = Math.round(0.5f); int i2 = Math.round(1.5f); System.out.print(i1 + "," + i2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 0,1 Prints: 0,2 Prints: 1,1 Prints: 1,2 Compile-time error Run-time error

g. None of the above


Resposta:

2d

The Math.round method returns the floor of the argument value plus 0.5. Prints: If the argument is of type float, then the return type is int. If the 1,2 argument is of type double, then the return type is long.

Question 3
class SRC104 { public static void main (String[] args) { System.out.print(Math.round(Float.NaN)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: NaN Prints: 0.0 Prints: 0 Compile-time error Run-time error None of the above

Resposta:

If NaN is the argument passed to Math.round, then the return value is zero. Prints: 3c If the argument type is float, then the return type is int. If the 0 argument type is double, then the return type is long.

Question 4
class SRC105 { public static void main(String[] args) { double d1 = Math.ceil(0.5); double d2 = Math.ceil(1.5); System.out.print(d1 + "," + d2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 0.0,1.0 Prints: 0.0,2.0 Prints: 1.0,1.0 Prints: 1.0,2.0 Compile-time error

f. Run-time error g. None of the above


Resposta:

Prints: 4d 1.0,2.0

The Math.ceil method name is not overloaded. The Math.ceil method accepts an argument of type double and returns a double. The returned value is the smallest whole number that is greater than or equal to the argument.

Question 5
class SRC106 { public static void main(String[] args) { double d1 = Math.floor(0.5); double d2 = Math.floor(1.5); System.out.print(d1 + "," + d2); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: 0.0,1.0 Prints: 0.0,2.0 Prints: 1.0,1.0 Prints: 1.0,2.0 Compile-time error Run-time error None of the above

Resposta:

5a

Prints: 0.0,1.0

The Math.floor method name is not overloaded. The Math.floor method accepts an argument of type double and returns a double. The returned value is the largest whole number that is smaller than or equal to the argument.

Question 6
class SRC107 { public static void main (String[] args) { int a = -1; long b = -2; float c = -3.0f; double d = -4.0; a = Math.abs(a); b = Math.abs(b); c = Math.abs(c); d = Math.abs(d); System.out.print(a+b+c+d); }}

What is the result of attempting to compile and run the program?

a. b. c. d.

Prints: 10.0 Compile-time error Run-time error None of the above

Resposta:

The Math class declares four versions of the abs method; each declares one parameter. The parameter can be of type int, long, float or double. The return type is the same as the Prints: 6a argument type. At run-time, the argument might not match the parameter 10.0 type; so the argument might require an implicit conversion to an acceptable type. If the argument is of typebyte, short or char, then it will be promoted to type int.

Question 7
class SRC109 { public static void main (String[] args) { short x3 = 0; short x4 = 1; short b1 = Math.min(x3,x4); // 1 int c1 = Math.min(0,1); // 2 long d1 = Math.min(0L,+1L); // 3 System.out.print(b1+","+c1+","+d1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 0,0,0 Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Run-time error None of the above

Resposta:

At line 1, the invocation of the Math.min method produces a return value of type int. The variable b1 is of type short; so the assignment expression results in a compile-time error. The Math class declares four versions of the min method; each declares a pair of Compile- parameters of the same type. The parameter pair can be of 7 b time error type int, long, float or double. The return type is the same as at 1 the argument types. At run-time, the arguments might not match the declared parameter types; so one argument or both might require an implicit conversion to an acceptable type. If both arguments are of type byte, short or char, then both will be promoted to type int. If only one argument is of type byte, short or char, then it will be

promoted to the type of the other argument. If both arguments are of type int, long, float or double but the types differ, then a primitive widening conversion will be applied to one of the two arguments.

Question 8
class SRC110 { public static void main (String[] args) { byte x1 = 0; byte x2 = 1; byte a1 = Math.min(x1,x2); // 1 int c1 = Math.min(0,1); // 2 long d1 = Math.min(0L,+1L); // 3 System.out.print(a1+","+c1+","+d1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 0,0,0 Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Run-time error None of the above

Resposta:

At line 1, the invocation of the Math.min method produces a return value of type int. The variable a1 is of type byte; so the assignment expression results in a compile-time error. TheMath class declares four versions of the min method; each declares a pair of parameters of the same type. The parameter pair can be of type int, long, float or double. The return type is the same as Compile- the argument types. At run-time, the arguments might not match the 8 b time error declared parameter types; so one argument or both might require an at 1 implicit conversion to an acceptable type. If both arguments are of type byte, short or char, then both will be promoted to type int. If only one argument is of type byte, short or char, then it will be promoted to the type of the other argument. If both arguments are of type int, long, float or double but the types differ, then a primitive widening conversion will be applied to one of the two arguments.

Question 9
class SRC111 { static String m(byte i) {return "byte";}

static String m(short i) {return "short";} static String m(char i) {return "char";} static String m(int i) {return "int";} static String m(double i) {return "double";} public static void main (String[] args) { byte b = 0; short s = 0; char c = 0; System.out.print(m(Math.min(b,b))+","); System.out.print(m(Math.min(s,s))+","); System.out.print(m(Math.min(c,c))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: byte,byte,byte Prints: short,short,short Prints: int,int,int Prints: byte,short,int Prints: short,short,int Prints: byte,short,char Compile-time error Run-time error None of the above

Resposta:

The Math class declares four versions of the min method; each declares a pair of parameters of the same type. The parameter pair can be of type int, long, float or double. The return type is the same as the argument types. At run-time, the arguments might not match the declared parameter types; so one argument or both might require an implicit conversion to an acceptable type. If both arguments are of Prints: 9c int,int,int type byte, short or char, then both will be promoted to type int. If only one argument is of type byte, short or char, then it will be promoted to the type of the other argument. If both arguments are of type int, long, float or double but the types differ, then a primitive widening conversion will be applied to one of the two arguments.

Question 10
class SRC112 { static String m(byte i) {return "byte";} static String m(int i) {return "int";} static String m(long i) {return "long";} static String m(double i) {return "double";} public static void main (String[] args) { byte b = 0; System.out.print(m(Math.min(b,b))+","); System.out.print(m(Math.min(b,1))+","); System.out.print(m(Math.min(b,1L)));

}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: byte,byte,byte Prints: byte,int,long Prints: int,int,int Prints: int,int,long Prints: long,long,long Compile-time error Run-time error None of the above

Resposta:

The Math class declares four versions of the min method; each declares a pair of parameters of the same type. The parameter pair can be of type int, long, float or double. The return type is the same as the argument types. At run-time, the arguments might not match the declared parameter types; so one argument or both might require an implicit conversion to an acceptable type. If both Prints: arguments are of type byte, short or char, then both will be 10 d int,int,long promoted to type int. If only one argument is of type byte, short or char, then it will be promoted to the type of the other argument. If both arguments are of type int, long, float or double but the types differ, then a primitive widening conversion will be applied to one of the two arguments.

Question 11
class SRC113 { static String m(byte i) {return "byte";} static String m(short i) {return "short";} static String m(char i) {return "char";} static String m(int i) {return "int";} static String m(long i) {return "long";} static String m(float i) {return "float";} static String m(double i) {return "double";} public static void main (String[] args) { byte b = 0; short s = 0; char c = 0; System.out.print(m(Math.min(b,1L))+","); System.out.print(m(Math.min(s,1.0f))+","); System.out.print(m(Math.min(c,1.0))); }}

What is the result of attempting to compile and run the program?


a. Prints: int,int,int

b. c. d. e. f. g. h.

Prints: byte,short,char Prints: long,float,double Prints: double,double,double Prints: long,long,long Compile-time error Run-time error None of the above

Resposta:

The Math class declares four versions of the min method; each declares a pair of parameters of the same type. The parameter pair can be of type int, long, float or double. The return type is the same as the argument types. At run-time, the arguments might not match the declared parameter types; so one argument or both might require an implicit conversion to an acceptable Prints: 11 c long,float,double type. If both arguments are of type byte, short or char, then both will be promoted to type int. If only one argument is of type byte, short or char, then it will be promoted to the type of the other argument. If both arguments are of type int, long, float or double but the types differ, then a primitive widening conversion will be applied to one of the two arguments.

Question 12
class SRC114 { static String m(int i) {return "int";} static String m(long i) {return "long";} static String m(float i) {return "float";} static String m(double i) {return "double";} public static void main (String[] args) { System.out.print(m(Math.random())); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: int Prints: long Prints: float Prints: double Compile-time error Run-time error None of the above

Resposta:

12 d

Prints: double

The Math.random method returns a value of type double. The range of values is greater than or equal to zero and less than one.

Question 13
class SRC115 { static String m(int i) {return "int";} static String m(long i) {return "long";} static String m(float i) {return "float";} static String m(double i) {return "double";} public static void main (String[] args) { long seed = 1L; System.out.print(m(Math.random(seed))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: int Prints: long Prints: float Prints: double Compile-time error Run-time error None of the above

Resposta:

13 e

Compile-time The Math.random method does not accept a seed value. If your error application requires a seed, then use java.util.Random.

Question 14
class SRC116 { static String m(int i) {return "int";} static String m(long i) {return "long";} static String m(float i) {return "float";} static String m(double i) {return "double";} public static void main (String[] args) { System.out.print(m(Math.sin(0.0f))+","); System.out.print(m(Math.cos(0.0f))+","); System.out.print(m(Math.tan(0.0f))); }}

What is the result of attempting to compile and run the program?


a. Prints: int,int,int b. Prints: long,long,long

c. d. e. f. g.

Prints: float,float,float Prints: double,double,double Compile-time error Run-time error None of the above

Resposta:

14 d

Prints: double,double,double

The Math.sin, Math.cos and Math.tan methods return a value of type double.

Question 15
class SRC117 { public static void main (String[] args) { double d1 = Math.random(); boolean b1 = (d1 < 0.0), b2 = (d1 <= 0.0), b3 = (d1 == 0.0); boolean b4 = (d1 >= 0.0), b5 = (d1 < 1.0), b6 = (d1 <= 1.0); boolean b7 = (d1 == 1.0), b8 = (d1 >= 1.0), b9 = (d1 > 1.0); }}

Which of the boolean variables will never be initialized to the value true?
a. b. c. d. e. f. g. h. i. b1 b2 b3 b4 b5 b6 b7 b8 b9

Resposta:

15

a g The Math.random method returns a value that is equal to or b1 b7 b8 b9 h i greater than zero and less than 1.0.

Question 16
Which method of the java.lang.Math class is not static?
a. abs b. ceil

c. d. e. f. g. h. i. j. k. l.

floor max min random round sin cos tan sqrt None of the above

Resposta:

16 l None of the above

All methods of the java.lang.Math class are static.

Question 17
Some of the following method names are overloaded and some are not. Which of the following method names are overloaded such that for each of the following four primitive types int, long, float and double there is at least one corresponding method that returns that type?
a. b. c. d. e. f. g. h. i. j. k. abs ceil floor max min random round sin cos tan sqrt

Resposta:

17

a d e

abs max min

Question 18
class SRC118 {

static String m1(int i) {return "I";} static String m1(long i) {return "L";} static String m1(float i) {return "F";} static String m1(double i) {return "D";} public static void main (String[] args) { System.out.print(m1(Math.abs(1.0)) + m1(Math.ceil(1.0f))); System.out.print(m1(Math.max(1.0,1.0)) + m1(Math.round(1.0))); System.out.print(m1(Math.sin(1.0)) + m1(Math.sqrt(1.0))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. Prints: DDDDDD Prints: LLLLLL Prints: DLLLDD Prints: DIDLDD Prints: DLDLDD Prints: DDDLDD Prints: DIDIDD None of the above

Resposta:

The round method does not return either of the two floating point primitive types, float or double. Prints: The ceil, sin and sqrt methods return only a value of 18 f DDDLDD type double. Theabs and max methods are able to return an int, long, float or double depending on the argument type.

Question 19
class SRC119 { static String m1(int i) {return "I";} static String m1(long i) {return "L";} static String m1(float i) {return "F";} static String m1(double i) {return "D";} public static void main (String[] args) { System.out.print(m1(Math.floor(1.0f)) + m1(Math.floor(1.0d))); System.out.print(m1(Math.ceil(1.0f)) + m1(Math.ceil(1.0d))); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: IIII Prints: ILIL Prints: LLLL Prints: FDFD Prints: DDDD

f. None of the above


Resposta:

19 e

Prints: DDDD

The floor and ceil methods are not overloaded. There is only one version of each method. The parameter type is double, and the return type is double.

Wrappers Question 1
class A { public static void Boolean b1 = new Boolean b2 = new Boolean b3 = new Boolean b4 = new Boolean b5 = new Boolean b6 = new }} main(String[] args) { Boolean(true); // 1 Boolean(false); // 2 Boolean(TRUE); // 3 Boolean(FALSE); // 4 Boolean("TrUe"); // 5 Boolean("fAlSe"); // 6

Compile-time errors are generated at which lines?


a. b. c. d. e. f. 1 2 3 4 5 6

Resposta:

The boolean literals true and false are written with lower case letters; c 1 3 4 upper case letters produce a compile-time error. A String representation of d a boolean literal is acceptable in both upper and lower case letters.

Question 2
class A { public static void main (String args[]) { byte primitiveByte = 1; // 1 Byte b1 = new Byte(primitiveByte); // 2 Byte b2 = new Byte(1); // 3 System.out.print(b1.byteValue() + b2.byteValue()); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e. f. g.

Prints: 2 Prints: 11 Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Run-time error None of the above

Resposta:

The Byte class has only two constructors: one accepts a primitive byte; the other accepts a String. The argument that appears in the class instance creation expression new Byte(1) is of type int, but the compiler will not implicitly narrow the int to a byte. At line 1, the assignment expression primitiveByte = 1 causes the compiler to implicitly narrow a literal of type int to type byte. The compiler will implicitly do a narrowing conversion for Compile- an assignment expression if the right hand operand is a compile-time 2 e time error constant of type byte, short, char or int and the value falls at 3 within the range of the variable on the left and the variable is of type byte, short, or char. For that reason, a constant int expression that is equal to 1 may be assigned to a byte without an explicit cast. The same is not true for the parameters of a method or constructor. The designers of the Java programming language felt that implicit narrowing conversions of method and constructor arguments would add unnecessary complexities to the process of resolving overloaded method calls.

Question 3
Which of the following class instance creation expressions would generate a compile-time error?
a. b. c. d. e. f. new Short(1) new Short('1') new Short('b' - 'a') new Short((short)1 - (short)2) new Short((byte)1) new Short((short)1)

Resposta:

a new Short(1) new 3 b Short('1') new c Short('b' - 'a') new

The Short class has only two constructors: one accepts a primitive short; the other accepts a String. The argument that appears in the class instance creation

d Short((short)1 (short)2)

expression new Short(1) is of type int, but the compiler will not implicitly narrow the int to a short. The argument that appears in the class instance creation expression new Short('1') is of type char, but the compiler will not implicitly convert the char to a short. The argument that appears in the class instance creation expression new Short('b' - 'a') is of type int, but the compiler will not implicitly narrow the int to a short. The argument that appears in the class instance creation expression new Short((short)1 (short)2) is of type int, but the compiler will not implicitly narrow the int to a short. If both operands of a binary arithmetic expression are of type byte, char or short; then both are implicitly widened to type int, and the result of the expression is of type int.

Question 4
class A { public static void main (String args[]) { byte primitiveByte = 1; char primitiveChar = 'b'-'a'; int primitiveInt = 1; short primitiveShort = 1; String s = "1"; Integer i1 = new Integer(primitiveByte); Integer i2 = new Integer(primitiveChar); Integer i3 = new Integer(primitiveShort); Integer i4 = new Integer(primitiveInt); Integer i5 = new Integer(s); int p1 = i1.intValue() + i2.intValue() + i3.intValue() + i4.intValue() + i5.intValue(); System.out.print(p1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 5 Prints: 5.0 Compile-time error Run-time error None of the above

Resposta:

4a

Prints: The Integer class has only two constructors: one accepts a 5 primitive int, and the other accepts a String. If the argument is of

type byte, short or char, then it is implicitly promoted to type int.

Question 5
class A { public static void main (String args[]) { byte primitiveByte = 1; int primitiveInt = 1; long primitiveLong = 1L; float primitiveFloat = 1f; String s = "1"; Long i1 = new Long(primitiveByte); Long i2 = new Long(primitiveInt); Long i3 = new Long(primitiveLong); Long i4 = new Long(primitiveFloat); Long i5 = new Long(s); int i6 = i1.intValue() + i2.intValue() + i3.intValue() + i4.intValue() + i5.intValue(); System.out.print(i6); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 5 Prints: 5.0 Compile-time error Run-time error None of the above

Resposta:

Long has two constructors: one accepts an argument of type primitive long; the other accepts an argument of type String. The Compile- class instance creation expression new 5c time error Long(primitiveFloat) generates a compile-time error, because the compiler will not implicitly apply a primitive narrowing conversion to the argument.

Question 6
class A { public static void main (String args[]) { byte primitiveByte = 1; char primitiveChar = 1; double primitiveDouble = 1; String s = "1"; Double d1 = new Double(primitiveByte); Double d2 = new Double(primitiveChar); Double d3 = new Double(primitiveDouble);

Double d4 = new Double(s); double d5 = d1.doubleValue() + d2.doubleValue() + d3.doubleValue() + d4.doubleValue(); System.out.print(d5); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 4 Prints: 4.0 Compile-time error Run-time error None of the above

Resposta:

6b

Prints: 4.0

The Double constructor is overloaded: one accepts an argument of type primitive double; the other accepts an argument of type String.

Question 7
class C { public static void main (String[] args) { Float f1 = new Float(1.0); // 1 Float f2 = new Float("1.0"); // 2 Float f3 = new Float("1.0f"); // 3 Float f4 = new Float("1e1f"); // 4 Float f5 = new Float(".1e1d"); // 5 }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Compile-time error at 4 Compile-time error at 5 Run-time error at 1 Run-time error at 2 Run-time error at 3 Run-time error at 4 Run-time error at 5 None of the above

Resposta:

7k

None of the

The Float constructor is overloaded: one version accepts a primitive of type float; one accepts a primitive of type double; one accepts

above

a String representation of a floating-point literal.

Question 8
class B { public static void main(String[] args) { Boolean b1 = new Boolean(true); Boolean b2 = new Boolean(true); Boolean b3 = new Boolean("TrUe"); Boolean b4 = new Boolean("tRuE"); System.out.print((b1==b2) + ","); System.out.print((b1.booleanValue()==b2.booleanValue()) + ","); System.out.println(b3.equals(b4)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

Four instances of type Boolean containing the value true are created. The equality expression b1==b2 evaluates to false, because the unique instances of type Booleanhave different reference values. The instance method Boolean.booleanValue returns a copy of the primitive boolean value that is contained by the Prints: d instance. Since the booleanvalues of b1 and b2 are the same, the 8 false,true,tru result of the equality e expression b1.booleanValue()==b2.booleanValue() is true. The equals method compares the values of the primitives that are wrapped by the Boolean instances. Since the wrapped primitive values are the same, the result of the method invocation expressionb3.equals(b4) is true.

Question 9
class B { public static void main (String args[]) {

Byte b1 = new Byte(1); // 1 Byte b2 = new Byte('2'); // 2 Byte b3 = new Byte("3"); // 3 byte i1 = b1.byteValue()+b2.byteValue()+b3.byteValue(); // 4 System.out.print(i1); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. Prints: 6 Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Compile-time error at 4 Run-time error

Resposta:

The Byte class has only two constructors: one accepts a primitive byte; the other accepts a String. The argument that appears in the class instance creation expression new Byte(1) is of type int, but the compiler will not Compile-time error implicitly narrow it to type byte. The argument that appears b at 1 Compile-time 9 c in the class instance creation expression new error at 2 Compilee Byte('2') is of type char, but the compiler will not time error at 4 implicitly narrow it to type byte. At line 4, the result of the additive expression is of type int, but the variable is of type byte. The assignment expression generates a compiletime error.

Question 10
Which of the following class instance creation expressions would generate a compile-time error?
a. b. c. d. e. f. new Short("1") new Short("-1") new Short("1.0") new Short("0x1") new Short("011") None of the above

Resposta:

None of None of the String arguments would generate a compile-time error, 10 f the but two would generate a run-time error. The argument 1.0 would above

generate a run-time error, because a floating-point value is not acceptable. The argument 0x1 would generate a run-time error, because a hexadecimal integer literal is not acceptable. The argument must be a decimal integer literal. The leading 0 of the argument 011 is ignored and the argument is interpreted as a decimal integer literal.

Question 11
class A { public static void main (String args[]) { int primitiveInt = 1; long primitiveLong = 1L; float primitiveFloat = 1.0f; String s = "1"; Integer i1 = new Integer(primitiveInt); Integer i2 = new Integer(primitiveLong); Integer i3 = new Integer(primitiveFloat); Integer i4 = new Integer(s); int i5 = i1.intValue() + i2.intValue() + i3.intValue() + i4.intValue(); System.out.print(i5); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: 4 Prints: 4.0 Compile-time error Run-time error None of the above

Resposta:

The Integer class has only two constructors: one accepts a primitive int, and the other accepts a String. The class instance Compile- creation expression new Integer(primitiveLong) generates a 11 c time compile-time error, because the compiler will not apply an implicit error narrowing conversion to the argument. For the same reason, the class instance creation expression new Integer(primitiveFloat) generates a compile-time error.

Question 12
class B { public static void main (String args[]) { Long i1 = new Long(1); Long i2 = new Long(i1); System.out.print((i1==i2) + "," + i1.equals(i2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

Resposta:

Long has two constructors: one accepts an argument of type primitive long; the other accepts an argument of type String. The Compile12 e class instance creation expression new Long(i1) generates a time error compile-time error, because there is no constructor that accepts a reference to an instance of type Long.

Question 13
class A { public static void main (String args[]) { Double d1 = new Double(1.0); Double d2 = new Double(d1); System.out.print(d1.equals(d2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false Prints: true Compile-time error Run-time error None of the above

Resposta:

13 c

Compiletime error

The Double constructor is overloaded: one accepts an argument of type primitive double; the other accepts an argument of type String. There is no constructor that accepts a reference to an instance of type Double.

Question 14
class F { public static void main (String[] args) {

Float f1 = new Float('B' - 'A'); // 1 Float f2 = new Float(010); // 2 Float f3 = new Float(0x10); // 3 Float f4 = new Float(.1e1); // 4 Float f5 = new Float(1.0); // 5 Float f6 = new Float(1.0d); // 6 System.out.print(f1+","+f2+","+f3+","+f4+","+f5+","+f6); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. l. m. n. o. Compile-time error at 1 Compile-time error at 2 Compile-time error at 3 Compile-time error at 4 Compile-time error at 5 Compile-time error at 6 Run-time error at 1 Run-time error at 2 Run-time error at 3 Run-time error at 4 Run-time error at 5 Run-time error at 6 Prints: 1.0,10.0,10.0,1.0,1.0,1.0 Prints: 1.0,8.0,16.0,1.0,1.0,1.0 None of the above

Resposta:

The Float constructor is overloaded: one version accepts a primitive of type float; one accepts a primitive of type double; one accepts Prints: 14 n a String representation of a floating-point literal. All 1.0,8.0,16.0,1.0,1.0,1.0 numeric values can be promoted to type double; so all numeric values are accepted by the float constructor.

Question 15
class C { public static void main(String[] args) { Boolean b1 = Boolean.valueOf(true); Boolean b2 = Boolean.valueOf(true); Boolean b3 = Boolean.valueOf("TrUe"); Boolean b4 = Boolean.valueOf("tRuE"); System.out.print((b1==b2) + ","); System.out.print((b1.booleanValue()==b2.booleanValue()) + ","); System.out.println(b3.equals(b4));

}}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. j. k. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true Compile-time error Run-time error None of the above

Resposta:

The Boolean class contains two public static final Boolean instances: Boolean.FALSE wraps the primitive boolean value false; Boolean.TRUE wraps the primitive boolean value true. Depending on the value of the argument, the Boolean.valueOf method returns a reference to Prints: either Boolean.FALSE or Boolean.TRUE. Reference 15 h true,true,true variables b1 and b2 are both initialized with a reference value returned by the method invocation expression Boolean.valueOf(true); so the equality expression b1==b2 istrue. Please note that the valueOf method that accepts an argument of type primitive boolean was introduced in the 1.4 version of Java.

Question 16
class D { public static void main (String args[]) { Byte a = new Byte("1"); byte b = a.byteValue(); short c = a.shortValue(); char d = a.charValue(); int e = a.intValue(); long f = a.longValue(); float g = a.floatValue(); double h = a.doubleValue(); System.out.print(b+c+d+e+f+g+h); }}

What is the result of attempting to compile and run the program?

a. b. c. d. e.

Prints: 7 Prints: 7.0 Compile-time error Run-time error None of the above

Resposta:

16 c

Compiletime error

A compile-time error is generated, because the Byte class does not have a charValue method. The Byte class extends the Number class and implements all six of the methods declared in Number.

Question 17
Which of the following class instance creation expressions would generate a run-time error?
a. b. c. d. e. f. new Short("1") new Short("-1") new Short("+1") new Short("1.0") new Short("0x1") new Short("011")

Resposta:

The Short class has only two constructors: one accepts a primitive short; the other accepts a String. A String argument must represent an integral primitive type. A leading minus sign can be added to indicate a negative value. A leading plus sign generates a run-time c new Short("+1") new error. The constructor is not able to determine the radix of 17 d Short("1.0") new the String value by examing a prefix such as 0 or 0x. e Short("0x1") The 0 prefix used to identify octal values is accepted, but the String is parsed as a decimal value. The prefix 0x generates a run-time error. A run-time error is generated if the String argument is not formatted as a decimal integer. A floating-point format results in a run-time error.

Question 18
class A { public static void main (String args[]) {

Integer i1 = new Integer(1); Integer i2 = new Integer(i1); System.out.print(i1.equals(i2)); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false Prints: true Compile-time error Run-time error None of the above

Resposta:

18 c

Compiletime error

The Integer class has only two constructors: one accepts a primitive int, and the other accepts a String. There is no constructor that accepts an argument that is an instance of type Integer.

Collections Question 1
Which implementation of the List interface produces the slowest access to an element in the middle of the list by means of an index?
a. b. c. d. Vector ArrayList LinkedList None of the above

Resposta:

ArrayList and Vector both use an array to store the elements of the list; so access to any element using an index is very fast. 1 c LinkedList A LinkedList is implemented using a doubly linked list; so access to an element requires the list to be traversed using the links.

Question 2
import java.util.*; class GFC100 { public static void main (String args[]) { Object a1 = new LinkedList(), b1 = new TreeSet();

Object c1 = new TreeMap(); System.out.print((a1 instanceof Collection)+","); System.out.print((b1 instanceof Collection)+","); System.out.print(c1 instanceof Collection); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

The List and Set interfaces extend the Collection interface; so both List and Set could be cast to type Collection without generating a ClassCastException. Therefore, the first two of the three Prints: 2g true,true,false relational expressions return true. The Map interface does not extend Collection. The reference variable c1 refers to an instance of TreeMap; so the relational expression c1 instanceof Collection returns the value false.

Question 3
Each element must be unique. Contains no duplicate elements. Elements are not key/value pairs. Accessing an element can be almost as fast as performing a similar operation on an array.

Which of these classes provides the specified features?


a. b. c. d. e. LinkedList TreeMap TreeSet HashMap HashSet

f. LinkedHashMap g. Hashtable h. None of the above


Resposta:

The elements of a Map are key/value pairs; so a Map is not a good choice. A List generally accepts duplicate elements. A Set stores a collection of unique elements. Any attempt to store a duplicate element in a Set is rejected. Adding and removing an element in a TreeSet involves walking the tree to determine the location of the element. A HashSet stores the elements in a hashtable; so elements in a HashSet can be accessed almost as quickly as elements in an 3 e HashSet array as long as the hash function disperses the elements properly. Although theLinkedHashSet is not among the answer options it could arguably satisfy the requirements. However, the put and remove methods of the LinkedHashSet are a little slower than the same methods of the HashSet due to the need to maintain the linked list through the elements of the LinkedHashSet.

Question 4
import java.util.*; class GFC101 { public static void main (String args[]) { Object a1 = new HashMap(), b1 = new ArrayList(); Object c1 = new HashSet(); System.out.print((a1 instanceof Collection)+","); System.out.print((b1 instanceof Collection)+","); System.out.print(c1 instanceof Collection); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

4 d Prints:

The Map interface does not extend Collection. The reference

false,true,true variable a1 refers to an instance of HashMap; so the relational expression a1 instanceof Collection returns the value false. The List and Set interfaces extend the Collection interface; so both List and Set could be cast to type Collection without generating aClassCastException. Therefore, the second and third relational expressions return true.

Question 5
Entries are organized as key/value pairs. Duplicate entries replace old entries.

Which interface of the java.util package offers the specified behavior?


a. b. c. d. List Map Set None of the above

Resposta:

5 b Map

The List and Set interfaces do not support key/value pairs. A list generally allows duplicate entries. A Set rejects duplicate entries.

Question 6
import java.util.*; class GFC102 { public static void main (String args[]) { Object a = new HashSet(); System.out.print((a instanceof Set)+","); System.out.print(a instanceof SortedSet); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false,false Prints: false,true Prints: true,false Prints: true,true None of the above

Resposta:

6c

Prints: true,false

HashSet implements the Set interface, but not the SortedSet interface.

Question 7
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. b. c. d. Vector ArrayList LinkedList None of the above

Resposta:

ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to 7 c LinkedList make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, theLinkedList allows for fast insertions and deletions.

Question 8
import java.util.*; class GFC103 { public static void main (String args[]) { Object a1 = new TreeSet(); System.out.print((a1 instanceof Set)+","); System.out.print(a1 instanceof SortedSet); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. Prints: false,false Prints: false,true Prints: true,false Prints: true,true None of the above

Resposta:

8d

Prints: true,true

TreeSet implements the Set interface and the SortedSet interface.

Question 9
Stores key/value pairs. Duplicate entries replace old entries. Entries are sorted using a Comparator or the Comparable interface.

Which of these classes provides the specified features?


a. b. c. d. e. f. g. LinkedList TreeMap TreeSet HashMap HashSet Hashtable None of the above

Resposta:

The requirement to store key/value pairs is directly satisfied by a concrete implementation of the Map interface. The List and Set interfaces recognize objects, but do not recognize 9 b TreeMap keys and values. TreeMap and TreeSet store elements in a sorted order based on the key, but the TreeSet does not support key/value pairs.

Question 10
import java.util.*; class GFC104 { public static void main (String args[]) { LinkedList a1 = new LinkedList(); ArrayList b1 = new ArrayList(); Vector c1 = new Vector(); System.out.print((a1 instanceof List)+","); System.out.print((b1 instanceof List)+","); System.out.print(c1 instanceof List); }}

What is the result of attempting to compile and run the program?


a. b. c. d. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true

e. f. g. h. i.

Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

10 h

Prints: true,true,true

The 1.2 version of Java introduced the updated Vector class that implements the List interface.

Question 11
Entries are not organized as key/value pairs. Duplicate entries are rejected.

Which interface of the java.util package offers the specified behavior?


a. b. c. d. List Map Set None of the above

Resposta:

11 c Set

The Map interface organizes entries as key/value pairs. A list generally allows duplicate entries. A Set rejects duplicate entries.

Question 12
import java.util.*; class GFC105 { public static void main (String args[]) { Object a = new HashSet(), b = new HashMap(); Object c = new Hashtable(); System.out.print((a instanceof Collection)+","); System.out.print((b instanceof Collection)+","); System.out.print(c instanceof Collection); }}

What is the result of attempting to compile and run the program?


a. Prints: false,false,false b. Prints: false,false,true c. Prints: false,true,false

d. e. f. g. h. i.

Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

HashSet is a subclass of AbstractSet and AbstractCollection; therefore, it implements the Collection interface. HashMap and Hashtable do not Prints: 12 e true,false,false implement theCollection interface. Instead, HashMap extends AbstractMap and implements the Map interface. Hashtable extends Dictionary and implements the Map interface.

Question 13
Elements are not key/value pairs. Contains no duplicate elements. The entries can be sorted using the Comparable interface.

Which of these classes provides the specified features?


a. b. c. d. e. f. g. LinkedList TreeMap TreeSet HashMap HashSet Hashtable None of the above

Resposta:

The elements are not key/value pairs; so a Map is not a good choice. A List generally accepts duplicate elements. A Set stores a 13 c TreeSet collection of unique objects; so any attempt to store a duplicate object is rejected. TreeSet stores elements in an order that is determined either by a Comparator or by the Comparable interface.

Question 14

import java.util.*; class GFC106 { public static void main (String args[]) { Object a = new HashSet(), b = new HashMap(); Object c = new Hashtable(); System.out.print((a instanceof Map)+","); System.out.print((b instanceof Map)+","); System.out.print(c instanceof Map); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

HashSet implements the Set interface, but not the Map interface. HashMap extends AbstractMap and Prints: 14 d implements false,true,true the Map interface. Hashtable extends Dictionary and implements the Map interface.

Question 15
Stores key/value pairs. Allows null elements, keys, and values. Duplicate entries replace old entries. Entries are not sorted.

Which of these classes provides the specified features?


a. b. c. d. e. f. LinkedList TreeMap TreeSet HashMap HashSet Hashtable

g. None of the above


Resposta:

The requirement to store key/value pairs is directly satisfied by a concrete implementation of the Map interface. The List and Set interfaces recognize objects, but do not recognize 15 d HashMap keys and values. The requirement to allow null elements is not satisfied by a Hashtable. TreeMap and TreeSet store elements in a sorted order based on the key.

Question 16
import java.util.*; class GFC107 { public static void main (String args[]) { Object a = new HashSet(), b = new HashMap(); Object c = new Hashtable(); System.out.print((a instanceof Cloneable)+","); System.out.print((b instanceof Cloneable)+","); System.out.print(c instanceof Cloneable); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

16 h Prints: true,true,true

All three implement Cloneable.

Question 17
Entries are not organized as key/value pairs. Generally accepts duplicate elements. Entries may be accessed by means of an index.

Which interface of the java.util package offers the specified behavior?


a. b. c. d. List Map Set None of the above

Resposta:

The Map interface organizes entries as key/value pairs. A list generally 17 a List allows duplicate entries. A Set rejects duplicate entries. A List allows entries to be accessed using an index.

Question 18
import java.util.*; import java.io.Serializable; class GFC108 { public static void main (String args[]) { HashMap a = new HashMap(); boolean b1, b2, b3; b1 = (a instanceof Cloneable) & (a instanceof Serializable); b2 = a instanceof Map; b3 = a instanceof Collection; System.out.print(b1 + "," + b2 + "," + b3); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

18 g

Prints: true,true,false

HashMap does not implement the Collection interface.

Question 19

Which of the following classes allow unsynchronized read operations by multiple threads?
a. b. c. d. e. f. Vector Hashtable TreeMap TreeSet HashMap HashSet

Resposta:

c 1 9 d e f

The Vector and Hashtable methods are synchronized and do not allow for simultaneous access by multiple threads. The concrete subclasses of the AbstractList, AbstractMap, and AbstractSet classes allow for unsynchronized read operations by multiple threads. Additionally, the TreeMap TreeSet HashMap Has sychronized wrapper methods of hSet the Collections class allow for the instantiation of aCollection, List, Map, Set, Sort edMap, or SortedSet with synchronized methods. If simultaneous read and write operations are necessary then a synchronized instance should be used.

Question 20
Entries are organized as key/value pairs. Duplicate entries replace old entries. Entries are sorted using a Comparator or the Comparable interface.

Which interface of the java.util package offers the specified behavior?


a. b. c. d. e. f. List Map Set SortedSet SortedMap None of the above

Resposta:

The List and Set interfaces do not support key/value pairs. A list generally allows duplicate entries. A Set rejects duplicate entries. A Map organizes the entries as key/value pairs. 20 e SortedMap TheSortedMap is similar to a Map except that the ordering of the elements is determined by a Comparator or the Comparable interface.

Question 21
import java.util.*; class GFC110 { public static void main (String[] args) { Object m = new LinkedHashMap(); System.out.print((m instanceof Collection)+","); System.out.print((m instanceof Map)+","); System.out.print(m instanceof List); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

21 c

Prints: false,true,false

LinkedHashMap does not implement the Collection interface or the List interface.

Question 22
import java.util.*; class GFC109 { public static void main (String[] args) { Object v = new Vector(); System.out.print((v instanceof Collections)+","); System.out.print((v instanceof Arrays)+","); System.out.print(v instanceof List); }}

What is the result of attempting to compile and run the program?


a. b. c. d. e. f. g. h. i. Prints: false,false,false Prints: false,false,true Prints: false,true,false Prints: false,true,true Prints: true,false,false Prints: true,false,true Prints: true,true,false Prints: true,true,true None of the above

Resposta:

The Collections class is not the same as the Collection interface. The Collections class contains Prints: a variety of methods used to work with collections. For 22 b false,false,true example,Collections.shuffle is used to randomly shuffle the elements of a Collection. Similarly, the Arrays class provides utility methods for working with arrays.

Assertions Question 1
Which of the following are command-line switches used to enable assertions in non-system classes?
a. b. c. d. e. f. g. h. -ea -ae -aon -aoff -enableassertions -assertionsenable -assertionson -assertionsoff

Resposta:

a -ea e enableassertions

Two command-line switches used to enable assertions in non-system classes are -ea and -enableassertions.

Question 2

Which of the following are command-line switches used to disable assertions in non-system classes?
a. b. c. d. e. f. g. h. -da -ad -aon -aoff -disableassertions -assertionsdisable -assertionson -assertionsoff

Resposta:

a -da 2 e disableassertions

Two command-line switches used to disable assertions are da and -disableassertions. Remember that all of the letters are lower case.

Question 3
Which of the following are command-line switches used to disable assertions in non-system classes?
a. b. c. d. e. f. -disableassertions -disableAssertions -assertionsDisable -assertionsOn -assertionsOff None of the above

Resposta:

3a

Two command-line switches used to disable assertions in nonsystem classes are -da and -disableassertions. Remember that all disableassertions of the letters are lower case.

Question 4
Which of the following are command-line switches used to enable assertions in system classes?
a. -saon b. -saoff

c. d. e. f. g. h.

-esa -sae -systemassertionson -systemassertionsoff -enablesystemassertions -systemassertionsenable

Resposta:

c -esa g enablesystemassertions

Two command-line switches used to enable assertions in system classes are -esa and -enablesystemassertions. Remember that all of the letters are lower case.

Question 5
Which of the following statements are true?
a. By default assertions are disabled at run-time. b. Assertions can be selectively enabled for any named class. c. If assertions are selectively enabled for a named class then assertions are automatically enabled for any subclass of the named class. d. Assertions can be selectively enabled for any named package. e. If assertions are selectively enabled for any named package then assertions are automatically enabled for the subpackages. f. Assertions can be selectively enable for the unnamed package in the current working directory. g. Assertions can be selectively enable for any unnamed package in any named directory.
Resposta:

a b 5 d e f

By default assertions are disabled at run-time. Assertions can be selectively enabled for any named class. Assertions can be selectively enabled for any named package. If assertions are selectively enabled for any named package then assertions are automatically enabled for the subpackages. Assertions can be selectively enable for the unnamed package in the current working directory.

Question 6
Which of the following is thrown to indicate that an assertion has failed?
a. AssertError b. AssertException

c. AssertionError d. AssertionException e. None of the above


Resposta:

An AssertionError is thrown to indicate that an 6 c AssertionError assertion has failed. Don't be fooled by the name AssertionException.

Question 7
class A { void m1(int i) { int j = i % 3; switch (j) { case 0: System.out.print("0"); break; case 1: System.out.print("1"); break; default: assert j == 2; System.out.print(j); }} public static void main (String[] args) { A a = new A(); for (int i=5; i >= -1; i--) {a.m1(i);} }}

Which statements are true?


a. With assertions enabled it prints 210210-1 followed by an AssertionError message. b. With assertions enabled it prints 210210 followed by an AssertionError message. c. With assertions enabled it prints only 210210. d. With assertions enabled it prints nothing. e. With assertions disabled it prints 210210-1 f. With assertions disabled it prints only 210210 g. Assertions should not be used within the default case of a switch statement.
Resposta:

With assertions enabled it b prints 210210followed by 7 e an AssertionErrormessage. With assertions disabled it prints210210-1

If, under normal operating circumstances, the default label of a switch statement should not be reached, then an assert statement can be placed after the default label to verify that an unexpected condition has not not occurred.

Question 8
class B { private static int x1; public void setX(int x) {x1 = x;} public int getX() {return x1;} public static void main(String[] args) { int i1 = 0, j1 = 0; do { System.out.print(j1++); assert (i1 = j1 + x1) < 6; } while (i1 < 3); }}

Assuming that the setX method is never invoked, which statements are true?
a. With assertions enabled it prints 012345 followed by an AssertionError message. b. With assertions enabled it prints 012. c. With assertions disabled it prints: 012345 d. With assertions disabled it prints: 012 e. With assertions disabled it attempts to print an infinite sequence of numbers. f. With assertions disabled the variable i1 is incremented with each pass through the loop. g. As a rule, the boolean expression of an assert statement should not be used to perform actions that are required for normal operation of the program.
Resposta:

An assert statement should not be used as demonstrated in the program. The With assertions enabled it boolean expression of the do-loop prints 012. With assertions disabled it depends on the value of the local variable attempts to print an infinite sequence of b i1. The value of i1 is set within the numbers. As a rule, the boolean 8 e boolean expression of the assert expression of an assert statement g statement. If assertions are disabled, then should not be used to perform actions the boolean expression of the assert that are required for normal operation statement is not processed and the value of the program. of i1 is not updated with each iteration of the loop; so the loop runs indefinitely.

Question 9
Which statements are true?
a. Assertions should not be used to validate arguments passed to public methods.

b. Assertions should not be used to validate arguments passed to nonpublic methods. c. Assertions should not be used within the default case of a switch statement. d. Assertions should not be used to perform processing that is required for the normal operation of the application.
Resposta:

Assertions should not be used to validate arguments passed to public a methods. Asserti ons should not 9 d be used to perform processing that is required for the normal operation of the application.

Assertions may be enabled or disabled at run time. Since assertions are not always enabled, they should not be used to validate the parameters of public methods. Parameter checking is typically published in the API specification of a method and must be enforced even when assertions are not enabled. Rather than use an assertion, an appropriate runtime exception should be thrown such as IllegalArgumentException, IndexOutOfBoundsE xception, orNullPointerException. However, an assertion may be used to validate the parameters of a nonpublic method. Since assertions are not always enabled, an assertion should not be used to perform operations that are required for the normal operation of the program. For example, the boolean expression of an assertion should not be used to produce the side effect of incrementing a variable that controls a loop statement. If assertions are disabled then the loop is unlikely to function as intended. Section 14.20 of the Java Language Specification defines "unreachable" statements. If an assert statement is "unreachable" as defined by the JLS, then a compile-time error is generated. In contrast, a programmer may believe that some points in the code will not be reached as a result of design assumptions. For example, a programmer may believe that the default case of a switch statement will never be reached. An assertion can be placed in the default case to verify the behavior of the switch statement.

Question 10
Which statements are true?
a. Assertions should never be placed at any point in the code that should not be reached under normal circumstances. b. The compiler will generate an error if an assert statement is "unreachable" as defined by the Java Language Specification. c. A catch clause should not be used to catch an AssertionError. d. AssertionError is a checked exception.
Resposta:

10

b The compiler will generate an error if Section 14.20 of the Java Language c an assert statement is "unreachable" as Specification defines "unreachable"

defined by the Java Language Specification. A catch clause should not be used to catch anAssertionError.

statements. If an assert statement is "unreachable" as defined by the JLS, then a compile-time error is generated. In contrast, a programmer may believe that some points in the code will not be reached as a result of design assumptions. For example, a programmer may believe that the default case of a switch statement will never be reached. An assertion can be placed in the default case to verify the behavior of the switch statement. While the exception handling mechanisms of Java have been designed to allow for recovery from Exceptions, the assertion mechanisms have been designed to discourage recovery attempts. An assertion is used to verify that the program has not strayed beyond the bounds of expected behavior. For example, suppose that you go to bed one night, and your pet dog is sleeping on the floor next to your bed. Before going to sleep, you make the assertion that your dog will still be there in the morning. When you wake up, you find that a different dog is sleeping in place of your pet. How do you recover from the failure of your assertion? Since you probably did not expect your dog to be mysteriously replaced during the night, it is unlikely that you have already developed an effective recovery routine. However, if you had planned for a dog swapping exception, then the recovery should be handled by the exception handling mechanism rather than the assertion mechanism.

Question 11
class C { String m1(int i) { switch (i) { case 0: return case 1: return case 2: return default: throw }} public static void C c = new C();

"A"; "B"; "C"; new AssertionError(); main(String[] args) {

for (int i = 0; i < 4; i++) { System.out.print(c.m1(i)); }}}

Which statements are true?


a. b. c. d. With assertions enabled it prints ABC followed by an AssertionError message. With assertions disabled it prints ABC followed by an AssertionError message. Assertions should not be used within the default case of a switch statement. In this code example an assert statement could not be used in place of the "throw" statement.

Resposta:

If the default label of a switch statement should not be reached under normal operating circumstances, then the default label might be a good location for an assert With assertions enabled it prints ABCfollowed by statement. If a method is an AssertionErrormessage. With assertions declared with a non-void a return type and if no return disabled it printsABC followed by 11 b statement appears after the an AssertionError message. In this code d switch statement, then each example an assert statement could not be used case of the switch must have a in place of the "throw" statement. return statement or a throw statement. The throw statement is used rather than an assert, because the compiler knows that the assert statement is not functional when assertions are disabled.

Question 12
class C { String m1(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } return "E"; } public static void main(String[] args) { C c = new C(); for (int i = 0; i < 4; i++) { System.out.print(c.m1(i));

}}}

Which statements are true?


a. With assertions enabled it prints ABC followed by an AssertionError message. b. With assertions enabled it prints ABCE followed by an AssertionError message. c. With assertions disabled it prints ABC d. With assertions disabled it prints ABCE e. Assertions should not be used within the default case of a switch statement.
Resposta:

With assertions enabled it prints ABCfollowed a 12 by an AssertionErrormessage. With d assertions disabled it printsABCE

If the default label of a switch statement should not be reached under normal operating circumstances, then the default label might be a good candidate for the use of an assert statement.

Question 13
class C { String m1(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } } public static void main(String[] args) { C c = new C(); for (int i = 0; i < 4; i++) { System.out.print(c.m1(i)); }}}

Which statements are true?


With assertions enabled it prints ABC followed by an AssertionError message. With assertions disabled it prints ABC followed by an AssertionError message. Assertions should not be used within the default case of a switch statement. In this code example a throw statement must be used in place of the assert statement. e. Compile-time error a. b. c. d.
Resposta:

In this code example a throw statement must be used in d 13 place of e the assertstatement. Compile-time error

If the default label of a switch statement should not be reached under normal operating circumstances, then the default case becomes a good candidate for the use of an assert statement. If a method is declared with a non-void return type and if no return statement appears after the switch statement, then each case of the switch must have a return statement or a throw statement. The throw statement is used rather than an assert, because the compiler knows that the assert statement is not functional when assertions are disabled.

Question 14
class D { private boolean b1, b2; public void setB1(boolean b) {b1 = b;} public void setB2(boolean b) {b2 = b;} public void m1 () { if (!b2 & !b1) {System.out.print("A"); } else if (!b2 & b1) {System.out.print("B"); } else if (b2 & !b1) {System.out.print("C"); } else {assert false;} } public static void main (String[] args) { D d = new D(); d.setB1(true); d.setB2(true); d.m1(); }}

Which statements are true?


With assertions enabled it prints an AssertionError message. With assertions enabled it prints nothing. With assertions disabled it prints an AssertionError message. With assertions disabled it prints nothing. An assertion should not be placed at any location that the programmer believes will never be reached under normal operating conditions. f. The assert statement is being used to check a control-flow invariant to verify that the control flow never reaches a point in the program. a. b. c. d. e.
Resposta:

a With assertions enabled it prints 14 d anAssertionError message. With assertions f disabled it prints nothing. The assert statement is

The assert statement indicates that the programmer believes that

being used to check a control-flow invariant to verify b1 and b2 will never be that the control flow never reaches a point in the true simultaneously, and program. the assert statement should not be reached under normal operating conditions.

Question 15
class A { private void m1 (int i) { assert i < 10 : i; System.out.print(i); } public void m2 (int i) { assert i < 10 : i; System.out.print(i); } public static void main (String[] args) { A a = new A(); a.m1(11); a.m2(12); }}

Which statements are true?


a. b. c. d. e. f. If assertions are enabled at run time it prints an error message. With assertions enabled it prints nothing. With assertions disabled it prints an error message. With assertions disabled it prints 1112. With assertions disabled it prints nothing. The assert statements are being used to check a precondition--something that must be true when the method is invoked. g. Method m1 is an example of an improper use of an assert statement: an assert statement should not be used for argument checking in a non-public method. h. Method m2 is an example of an improper use of an assert statement: an assert statement should not be used for argument checking in a public method.
Resposta:

a 1 5 d f h

If assertions are enabled at run time it prints an error message. With assertions disabled it prints 1112. The assert statements are being used to check a

Assertions may be enabled or disabled at run time. Since assertions are not always enabled, they should not be used to validate the parameters of public methods. Parameter checking is typically published in the API specification of a method and must be enforced even when assertions are not enabled. Rather than use an assertion, an appropriate runtime exception should be thrown such as IllegalArgumentException, IndexOutOfBoundsE xception, orNullPointerException. However, an assertion may be used to validate the parameters of a nonpublic method.

precondition-something that must be true when the method is invoked. Meth od m2 is an example of an improper use of an assert statement: an assert statement should not be used for argument checking in a public method.

Question 16
class B { int a, b, c; private void setA(int i) {a = i;} private void setB(int i) {b = i;} private int m1 (int i) { c = a + b + i; assert c < 200 : c; return c; } public static void main (String[] args) { B b = new B(); b.setA(50); b.setB(100); b.m1(50); }}

Which statements are true?


a. b. c. d. e. If assertions are not enabled at run time it prints an error message. If assertions are not enabled at run time it prints nothing. With assertions enabled it prints an error message. With assertions enabled it prints nothing. The assert statement is being used to check a postcondition--something that must be true when the method completes successfully.

Resposta:

If assertions are not enabled at run time it prints b nothing. With assertions enabled it prints an error 16 c message. The assert statement is being used to check a e postcondition--something that must be true when the method completes successfully.

Variable c equals 200 when the assertion is checked.

Question 17
class C { int a, b, c; public void setA(int i) {a = i; assert validateC() : c;} public void setB(int i) {b = i; assert validateC() : c;} private boolean validateC() { return c > a + 2 * b; } public int m1(int i) { c = a + b + i; assert validateC() : c; return c; } public C(int i) { c = i; assert validateC() : c; } public static void main(String[] args) { C c = new C(251); c.setA(50); c.setB(100); }}

Which statements are true?


a. b. c. d. e. If assertions are not enabled at run time it prints an error message. If assertions are not enabled at run time it prints nothing. With assertions enabled it prints an error message. With assertions enabled it prints nothing. The assert statement is being used to check a class invariant--something that must be true about each instance of the class. f. The assert statements are being used to check a precondition--something that must be true when the method is invoked.
Resposta:

If assertions are not enabled at run time it prints nothing. With assertions enabled it prints b nothing. The assert statement is 17 d being used to check a class e invariant--something that must be true about each instance of the class.

This question is an example of using assertions to check a class invariant-something that must be true about each instance of the class. Although a class invariant must be true before and after the execution of each public method, the invariant is typically only checked at the end of each method and constructor.

Question 18
class E { private boolean b1, b2, b3; public void setB1(boolean b) {b1 = b;} public void setB2(boolean b) {b2 = b;}

public void setB3(boolean b) {b3 = b;} public void m1 (int i) { b2 = i % 2 == 0; if (!b3 & !b2 & !b1) {System.out.print("A"); } else if (!b3 & !b2 & b1) {System.out.print("B"); } else if (!b3 & b2 & !b1) {System.out.print("C"); } else { // Only b3 is true. assert b3 & !b2 & !b1; } System.out.print(b1 + "," + b2 + "," + b3); b1 = b2 = b3 = false; } public static void main (String[] args) { E e = new E(); e.setB1(true); e.m1(2); }}

Which statements are true?


a. b. c. d. e. f. With assertions enabled it prints an error message. With assertions enabled it prints: true,true,false With assertions disabled it prints an error message. With assertions disabled it prints: true,true,false With assertions disabled it prints nothing. The combination of the if/else statements and the assert statement indicate that the programmer expects no more than one boolean, b1, b2 or b3, to be true. g. The assert statement is being used to check a precondition--something that must be true when the method begins. h. The assert statement is being used to check an internal invariant--something that the programmer assumes to be true at a particular point in the program.
Resposta:

a d 18 f h

Method m1 has a series of if/else statements. The first if statement is processed if none of the booleans are true. The second is processed if only b1 With assertions enabled it prints an is true. The third is processed if only b2 error message. With assertions is true. A set of three booleans can exist disabled it prints: true,true,false The is eight states. The three if statements combination of the if/else statements account for three of those states; so five and the assert statement indicate that more states remain. The assert statement the programmer expects no more than indicates that the programmer assumes one boolean, b1, b2 or b3, to be that only one of those five remaining true. The assert statement is being used states is valid--that is the state where to check an internal invariant-only b3 is true. The combination of the something that the programmer assumes to be true at a particular point three if statements and the assert statement indicate that the programmer in the program. believes that no more than one of the booleans will be true at that point in the program. That assumption is called an internal invariant.

Question 19
class F { private boolean b1, b2, b3; public void setB1(boolean b) {b1 = b;} public void setB2(boolean b) {b2 = b;} public void setB3(boolean b) {b3 = b;} public String m1 (int i) { b2 = i % 2 == 0; if (!b3 & !b2 & !b1) {return "None are true."; } else if (!b3 & !b2 & b1) {return "Only b1 is true."; } else if (!b3 & b2 & !b1) {return "Only b2 is true."; } else if (b3 & !b2 & !b1) {return "Only b3 is true."; } else {throw new AssertionError();} } public static void main (String[] args) { F f = new F(); f.setB1(true); System.out.println(f.m1(5)); System.out.println(f.m1(6)); }}

Which statements are true?


a. Prints "Only b1 is true" followed by an error message. b. An assertion should not be placed at any location that the programmer believes will never be reached under normal operating conditions. c. The combination of the if/else statements and the assert statement indicate that the programmer expects no more than one boolean, b1, b2, or b3, to be true. d. The assert statement is being used to check a precondition--something that must be true when the method begins. e. The assert statement is being used to check a control-flow invariant to verify that the control flow never reaches a point in the program. f. The throw statement could be replaced by an assert statement.
Resposta:

Method m1 has a series of if/else statements. Prints "Only b1 is true" followed The first if statement is processed if none of the booleans are true. The second is processed by an error message. The if only b1 is true. The third is processed if combination of the if/else statements and the assert statement only b2 is true. The fourth is processed if only b3 is true. A set of three booleans can a indicate that the programmer 19 c expects no more than one boolean, exist in one of eight states. The first four if statements account for four of those e b1, b2, or b3, to be true. The states; so four more states remain. The assert statement is being used to check a control-flow invariant to combination of the three if statements and verify that the control flow never the fact that an AssertionError is reaches a point in the program. thrown from the lastelse block indicates that the programmer believes that no more

than one of the booleans will be true when method m1 is being processed. An assumption concerning the state of a set of variables is called an internal invariant. In this case, however, the assertion was tested by verifying that control never reached a particular point in the program. Based on the testing technique, we would say that the assertion tests a control-flow invariant. A throw statement is used in place of an assert statement, because the throw statement can not be disabled. As a result, the method is certain to generate an error once control passes beyond all of the return statements. The declared return type of method m1 is String. No return statement appears after the sequence of if statements; therefore, every if statement must either return a String or throw an exception. Assertions can be disabled at run time, so an assert statement in the final if block is no guarantee that an exception will be thrown. For that reason, an assert can not replace the throw statement.

Question 20
An assert statement can be used to check a control-flow invariant to verify which of the following?
a. b. c. d. e. f. A particular assumption is true when the flow of control enters a method. The flow of control does not reach a particular point in the program. The normal flow of control has reached a particular point in the program. The normal flow of control has reached the end of a method. The default case of a switch statement is not reached. The else block of an if/else statement is not reached.

Resposta:

The flow of control does not reach a b particular point in the program. The 20 e default case of a switch statement is f not reached. The else block of an if/else statement is not reached.

A control-flow invariant is placed at a point in the program that the programmer assumes will never be reached. Two examples are the default case of a switch statement or the else block of an if/else statement. It makes no sense to use an assert statement to verify that the flow of control does reach a particular point in the

program, because it is unlikely that an assertion error is helpful when the program is found to be functioning correctly. An assert statement placed at the beginning of a method is generally used to check a precondition. An assert statement that is placed at the end of a method to check the state of some variables is generally said to be checking a post condition. However, it is also possible that an assert statement placed at the end of a method might also be checking a control-flow invariant. The correct term depends on the usage.

You might also like