Skip to content

Instantly share code, notes, and snippets.

@RupGautam
Created December 10, 2017 06:07
Show Gist options
  • Select an option

  • Save RupGautam/a906a28ed2183170482a0c4ac3871208 to your computer and use it in GitHub Desktop.

Select an option

Save RupGautam/a906a28ed2183170482a0c4ac3871208 to your computer and use it in GitHub Desktop.

10.1 Which of the following statements are true about an immutable object?

A. The contents of an immutable object cannot be modified. B. All properties of an immutable object must be private. C. All properties of an immutable object must be of primitive types. D. An object type property in an immutable object must also be immutable. E. An immutable object contains no mutator methods.

Section 10.3 Scope of Variables 10.2 What is the printout for the first statement in the main method? public class Foo { static int i = 0; static int j = 0;

public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); }

k = i + j;
System.out.println("k is " + k);
System.out.println("j is " + j);

} }

A. i + j is 5 B. i + j is 6 C. i + j is 22 D. i + j is 23

10.3 What will be displayed from the statement System.out.println("k is " + k) in the main method? public class Foo { static int i = 0; static int j = 0;

public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); }

k = i + j;
System.out.println("k is " + k);
System.out.println("j is " + j);

} }

A. k is 0 B. k is 1 C. k is 2 D. k is 3

10.4 What will be displayed from the statement System.out.println("j is " + j) in the main method? public class Foo { static int i = 0; static int j = 0;

public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); }

k = i + j;
System.out.println("k is " + k);
System.out.println("j is " + j);

} }

A. j is 0 B. j is 1 C. j is 2 D. j is 3

10.5 You can declare two variables with the same name in __________.

A. a method one as a formal parameter and the other as a local variable B. a block C. two nested blocks in a method (two nested blocks means one being inside the other) D. different methods in a class

Section 10.4 The this Keyword 10.6 Analyze the following code:

class Circle { private double radius;

public Circle(double radius) { radius = radius; } }

A. The program has a compilation error because it does not have a main method. B. The program will compile, but you cannot create an object of Circle with a specified radius. The object will always have radius 0. C. The program has a compilation error because you cannot assign radius to radius. D. The program does not compile because Circle does not have a default constructor.

10.7 Analyze the following code:

class Test { private double i;

public Test(double i) { this.t(); this.i = i; }

public Test() { System.out.println("Default constructor"); this(1); }

public void t() { System.out.println("Invoking t"); } }

A. this.t() may be replaced by t(). B. this.i may be replaced by i. C. this(1) must be called before System.out.println("Default constructor"). D. this(1) must be replaced by this(1.0).

10.8 Which of the following can be placed in the blank line in the following code? public class Test { private int id;

public void m1() { _____.id = 45; } }

A. this B. Test

10.9 Analyze the following code: public class Test { public static void main(String[] args) { String firstName = "John"; Name name = new Name(firstName, 'F', "Smith"); firstName = "Peter"; name.lastName = "Pan"; System.out.println(name.firstName + " " + name.lastName); } }

class Name { String firstName; char mi; String lastName;

public Name(String firstName, char mi, String lastName) { this.firstName = firstName; this.mi = mi; this.lastName = lastName; } }

A. The program displays Peter Pan. B. The program displays John Pan. C. The program displays Peter Smith. D. The program displays John Smith.

10.10 Analyze the following code: public class Test { public static void main(String[] args) { MyDate birthDate = new MyDate(1990, 5, 6); Name name = new Name("John", 'F', "Smith", birthDate); birthDate = new MyDate(1991, 1, 1); birthDate.year = 1992; System.out.println(name.birthDate.year); } }

class MyDate { int year; int month; int day;

public MyDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } }

class Name { String firstName; char mi; String lastName; MyDate birthDate;

public Name(String firstName, char mi, String lastName, MyDate birthDate) { this.firstName = firstName; this.mi = mi; this.lastName = lastName; this.birthDate = birthDate; } }

A. The program displays 1990. B. The program displays 1991. C. The program displays 1992. D. The program displays no thing.

Section 10.7 Object Composition 10.11 ___________ is attached to the class of the composing class to denote the aggregation relationship with the composed object.

A. An empty diamond B. A solid diamond C. An empty oval D. A solid oval

10.12 An aggregation relationship is usually represented as __________ in ___________.

A. a data field/the aggregating class B. a data field/the aggregated class C. a method/the aggregating class D. a method/the aggregated class

Section 10.11 Class Design Guidelines 10.13 Which of the following statements are true?

A. A class should describe a single entity and all the class operations should logically fit together to support a coherent purpose. B. A class should always contain a no-arg constructor. C. The constructors must always be public. D. The constructors may be protected.

10.14 Which of the following is poor design?

A. A data field is derived from other data fields in the same class. B. A method must be invoked after/before invoking another method in the same class. C. A method is an instance method, but it does not reference any instance data fields or invoke instance methods. D. A parameter is passed from a constructor to initialize a static data field.

Section 10.12 Processing Primitive Data Type Values as Objects 10.15 Which of the following statements will convert a string s into i of int type?

A. i = Integer.parseInt(s); B. i = (new Integer(s)).intValue(); C. i = Integer.valueOf(s).intValue(); D. i = Integer.valueOf(s); E. i = (int)(Double.parseDouble(s));

10.16 Which of the following statements will convert a string s into a double value d?

A. d = Double.parseDouble(s); B. d = (new Double(s)).doubleValue(); C. d = Double.valueOf(s).doubleValue(); D. All of the above.

10.17 Which of the following statements convert a double value d into a string s?

A. s = (new Double(d)).toString(); B. s = (Double.valueOf(s)).toString(); C. s = new Double(d).stringOf(); D. s = String.stringOf(d);

10.18 Which of the following statements is correct?

A. Integer.parseInt("12", 2); B. Integer.parseInt(100); C. Integer.parseInt("100"); D. Integer.parseInt(100, 16); E. Integer.parseInt("345", 8);

10.19 What is the output of Integer.parseInt("10", 2)?

A. 1; B. 2; C. 10; D. Invalid statement;

Section 10.13 Automatic Conversion Between Primitive Types and Wrapper Class Types 10.20 In JDK 1.5, you may directly assign a primitive data type value to a wrapper object. This is called ______________.

A. auto boxing B. auto unboxing C. auto conversion D. auto casting

10.21 In JDK 1.5, analyze the following code.

Line 1: Integer[] intArray = {1, 2, 3}; Line 2: int i = intArray[0] + intArray[1]; Line 3: int j = i + intArray[2]; Line 4: double d = intArray[0];

A. It is OK to assign 1, 2, 3 to an array of Integer objects in JDK 1.5. B. It is OK to automatically convert an Integer object to an int value in Line 2. C. It is OK to mix an int value with an Integer object in an expression in Line 3. D. Line 4 is OK. An int value from intArray[0] object is assigned to a double variable d.

Section 10.14 The BigInteger and BigDecimal Classes 10.22 To create an instance of BigInteger for 454, use

A. BigInteger(454); B. new BigInteger(454); C. BigInteger("454"); D. new BigInteger("454");

10.23 To create an instance of BigDecimal for 454.45, use

A. BigInteger(454.45); B. new BigInteger(454.45); C. BigInteger("454.45"); D. new BigDecimal("454.45");

10.24 BigInteger and BigDecimal are immutable

A. true B. false

10.25 To add BigInteger b1 to b2, you write _________.

A. b1.add(b2); B. b2.add(b1); C. b2 = b1.add(b2); D. b2 = b2.add(b1); E. b1 = b2.add(b1);

10.26 What is the output of the following code?

public class Test { public static void main(String[] args) { java.math.BigInteger x = new java.math.BigInteger("3"); java.math.BigInteger y = new java.math.BigInteger("7"); x.add(y); System.out.println(x); } }

A. 3 B. 4 C. 10 D. 11

10.27 To divide BigDecimal b1 by b2 and assign the result to b1, you write _________.

A. b1.divide(b2); B. b2.divide(b1); C. b1 = b1.divide(b2); D. b1 = b2.divide(b1); E. b1 = b2.divide(b1);

10.28 Which of the following classes are immutable?

A. Integer B. Double C. BigInteger D. BigDecimal E. String

10.29 Which of the following statements are correct? A. new java.math.BigInteger("343"); B. new java.math.BigDecimal("343.445"); C. new java.math.BigInteger(343); D. new java.math.BigDecimal(343.445);

11.1 Object-oriented programming allows you to derive new classes from existing classes. This is called ____________.

A. encapsulation B. inheritance C. abstraction D. generalization

11.2 Which of the following statements are true?

A. A subclass is a subset of a superclass. B. A subclass is usually extended to contain more functions and more detailed information than its superclass. C. "class A extends B" means A is a subclass of B. D. "class A extends B" means B is a subclass of A.

11.3 What is the output of the following code? public class Test1 { public static void main(String[] args) { ChildClass c = new ChildClass(); c.print(); } }

class ParentClass { int id = 1; void print() { System.out.println(id); } }

class ChildClass extends ParentClass { int id = 2; }

A. 0 B. 1 C. 2 D. Nothing

Section 11.3 Using the super KeywordSection 11.3.1 Calling Superclass Constructors 11.4 Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code:

class Square extends GeometricObject { double length;

Square(double length) { GeometricObject(length); } }

A. The program compiles fine, but you cannot create an instance of Square because the constructor does not specify the length of the Square. B. The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally. C. The program compiles fine, but it has a runtime error because of invoking the Square class's constructor illegally.

11.5 Analyze the following code:

public class A extends B { }

class B { public B(String s) { } }

A. The program has a compilation error because A does not have a default constructor. B. The program has a compilation error because the default constructor of A invokes the default constructor of B, but B does not have a default constructor. C. The program would compile fine if you add the following constructor into A: A(String s) { } D. The program would compile fine if you add the following constructor into A: A(String s) { super(s); }

11.6 Analyze the following code:

public class Test extends A { public static void main(String[] args) { Test t = new Test(); t.print(); } }

class A { String s;

A(String s) { this.s = s; }

public void print() { System.out.println(s); } }

A. The program does not compile because Test does not have a default constructor Test(). B. The program has an implicit default constructor Test(), but it cannot be compiled, because its super class does not have a default constructor. The program would compile if the constructor in the class A were removed. C. The program would compile if a default constructor A(){ } is added to class A explicitly. D. The program compiles, but it has a runtime error due to the conflict on the method name print.

Section 11.3.2 Constructor Chaining 11.7 What is the output of running class C?

class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

class B extends A { public B() { System.out.println( "The default constructor of B is invoked"); } }

public class C { public static void main(String[] args) { B b = new B(); } }

A. Nothing displayed B. "The default constructor of B is invoked" C. "The default constructor of A is invoked""The default constructor of B is invoked" D. "The default constructor of B is invoked""The default constructor of A is invoked" E. "The default constructor of A is invoked"

11.8 Which of the following is incorrect?

A. A constructor may be static. B. A constructor may be private. C. A constructor may invoke a static method. D. A constructor may invoke an overloaded constructor. E. A constructor invokes its superclass no-arg constructor by default if a constructor does not invoke an overloaded constructor or its superclass?s constructor.

Section 11.3.3 Calling Superclass Methods 11.9 Which of the statements regarding the super keyword is incorrect?

A. You can use super to invoke a super class constructor. B. You can use super to invoke a super class method. C. You can use super.super.p to invoke a method in superclass's parent class. D. You cannot invoke a method in superclass's parent class.

Section 11.4 Overriding Methods 11.10 Analyze the following code:

public class Test { public static void main(String[] args) { B b = new B(); b.m(5); System.out.println("i is " + b.i); } }

class A { int i;

public void m(int i) { this.i = i; } }

class B extends A { public void m(String s) { } }

A. The program has a compilation error, because m is overridden with a different signature in B. B. The program has a compilation error, because b.m(5) cannot be invoked since the method m(int) is hidden in B. C. The program has a runtime error on b.i, because i is not accessible from b. D. The method m is not overridden in B. B inherits the method m from A and defines an overloaded method m in B.

11.11 The getValue() method is overridden in two ways. Which one is correct?

I: public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a.getValue()); } }

class B { public String getValue() { return "Any object"; } }

class A extends B { public Object getValue() { return "A string"; } }

II: public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a.getValue()); } }

class B { public Object getValue() { return "Any object"; } }

class A extends B { public String getValue() { return "A string"; } }

A. I B. II C. Both I and II D. Neither

Section 11.5 Overriding vs. Overloading 11.12 Which of the following statements are true?

A. To override a method, the method must be defined in the subclass using the same signature and compatible return type as in its superclass. B. Overloading a method is to provide more than one method with the same name but with different signatures to distinguish them. C. It is a compilation error if two methods differ only in return type in the same class. D. A private method cannot be overridden. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. E. A static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.

11.13 Which of the following statements are true?

A. A method can be overloaded in the same class. B. A method can be overridden in the same class. C. If a method overloads another method, these two methods must have the same signature. D. If a method overrides another method, these two methods must have the same signature. E. A method in a subclass can overload a method in the superclass.

11.14 Analyze the following code:

public class Test { public static void main(String[] args) { new B(); } }

class A { int i = 7;

public A() { System.out.println("i from A is " + i); }

public void setI(int i) { this.i = 2 * i; } }

class B extends A { public B() { setI(20); // System.out.println("i from B is " + i); }

public void setI(int i) { this.i = 3 * i; } }

A. The constructor of class A is not called. B. The constructor of class A is called and it displays "i from A is 7". C. The constructor of class A is called and it displays "i from A is 40". D. The constructor of class A is called and it displays "i from A is 60".

11.15 Analyze the following code:

public class Test { public static void main(String[] args) { new B(); } }

class A { int i = 7;

public A() { setI(20); System.out.println("i from A is " + i); }

public void setI(int i) { this.i = 2 * i; } }

class B extends A { public B() { // System.out.println("i from B is " + i); }

public void setI(int i) { this.i = 3 * i; } }

A. The constructor of class A is not called. B. The constructor of class A is called and it displays "i from A is 7". C. The constructor of class A is called and it displays "i from A is 40". D. The constructor of class A is called and it displays "i from A is 60".

Section 11.6 The Object Class and Its toString() Method 11.16 Analyze the following code:

public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new Object(); System.out.println(a1); System.out.println(a2); } }

class A { int x;

public String toString() { return "A's x is " + x; } }

A. The program cannot be compiled, because System.out.println(a1) is wrong and it should be replaced by System.out.println(a1.toString()); B. When executing System.out.println(a1), the toString() method in the Object class is invoked. C. When executing System.out.println(a2), the toString() method in the Object class is invoked. D. When executing System.out.println(a1), the toString() method in the A class is invoked.

Sections 11.7-11.8 11.17 Which of the following statements are true?

A. You can always pass an instance of a subclass to a parameter of its superclass type. This feature is known as polymorphism. B. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. C. A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime. D. Dynamic binding can apply to static methods. E. Dynamic binding can apply to instance methods.

11.18 Given the following code, find the compile error?

public class Test { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); }

public static void m(Student x) { System.out.println(x.toString()); } }

class GraduateStudent extends Student { }

class Student extends Person { public String toString() { return "Student"; } }

class Person extends Object { public String toString() { return "Person"; } }

A. m(new GraduateStudent()) causes an error B. m(new Student()) causes an error C. m(new Person()) causes an error D. m(new Object()) causes an error

11.19 What is the output of the following code?

public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } }

class Student extends Person { public String getInfo() { return "Student"; } }

class Person { public String getInfo() { return "Person"; }

public void printPerson() { System.out.println(getInfo()); } }

A. Person Person B. Person Student C. Student Student D. Student Person

11.20 What is the output of the following code?

public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } }

class Student extends Person { private String getInfo() { return "Student"; } }

class Person { private String getInfo() { return "Person"; }

public void printPerson() { System.out.println(getInfo()); } }

A. Person Person B. Person Student C. Student Student D. Student Person

Section 11.9 Casting Objects and the instanceof Operator 11.21 Which of the following are Java keywords?

A. instanceOf B. instanceof C. cast D. casting

11.22 Analyze the following code:

Cylinder cy = new Cylinder(1, 1); Circle c = cy;

A. The code has a compile error. B. The code has a runtime error. C. The code is fine.

11.23 Analyze the following code:

Circle c = new Circle (5); Cylinder c = cy;

A. The code has a compile error. B. The code has a runtime error. C. The code is fine.

11.24 Given the following classes and their objects:

class C1 {}; class C2 extends C1 {}; class C3 extends C1 {};

C2 c2 = new C2(); C3 c3 = new C3();

Analyze the following statement:

c2 = (C2)((C1)c3);

A. c3 is cast into c2 successfully. B. You will get a runtime error because you cannot cast objects from sibling classes. C. You will get a runtime error because the Java runtime system cannot perform multiple casting in nested form. D. The statement is correct.

11.25 Given the following code:

class C1 {} class C2 extends C1 { } class C3 extends C2 { } class C4 extends C1 {}

C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4();

Which of the following expressions evaluates to false?

A. c1 instanceof C1 B. c2 instanceof C1 C. c3 instanceof C1 D. c4 instanceof C2

11.26 Analyze the following code:

public class Test { public static void main(String[] args) { String s = new String("Welcome to Java"); Object o = s; String d = (String)o; } }

A. When assigning s to o in Object o = s, a new object is created. B. When casting o to s in String d = (String)o, a new object is created. C. When casting o to s in String d = (String)o, the contents of o is changed. D. s, o, and d reference the same String object.

11.27 You can assign _________ to a variable of Object[] type.

A. new char[100] B. new int[100] C. new double[100] D. new String[100] E. new java.util.Date[100]

Section 11.10 The Object?s equals() Method 11.28 The equals method is defined in the Object class. Which of the following is correct to override it in the String class?

A. public boolean equals(String other) B. public boolean equals(Object other) C. public static boolean equals(String other) D. public static boolean equals(Object other)

11.29 Which of the following statements are true?

A. Override the toString method defined in the Object class whenever possible. B. Override the equals method defined in the Object class whenever possible. C. A public default no-arg constructor is assumed if no constructors are defined explicitly. D. You should follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods.

11.30 What is the output of the following code:

public class Test { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); System.out.print((o1 == o2) + " " + (o1.equals(o2))); } }

A. false false B. true true C. false true D. true false

11.31 What is the output of the following code:

public class Test { public static void main(String[] args) { String s1 = new String("Java"); String s2 = new String("Java"); System.out.print((s1 == s2) + " " + (s1.equals(s2))); } }

A. false false B. true true C. false true D. true false

11.32 Given two reference variables t1 and t2, if t1 == t2 is true, t1.equals(t2) must be ___________.

A. false B. true

11.33 Given two reference variables t1 and t2, if t1.equals(t2) is true, t1 == t2 ___________.

A. is always false B. is always true C. may be true or false

11.34 Analyze the following code.

// Program 1: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } }

class A { int x;

public boolean equals(Object a) { return this.x == ((A)a).x; } }

// Program 2: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } }

class A { int x;

public boolean equals(A a) { return this.x == a.x; } }

A. Program 1 displays true and Program 2 displays true B. Program 1 displays false and Program 2 displays true C. Program 1 displays true and Program 2 displays false D. Program 1 displays false and Program 2 displays false

11.35 Analyze the following code.

// Program 1: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } }

class A { int x;

public boolean equals(A a) { return this.x == a.x; } }

// Program 2: public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); } }

class A { int x;

public boolean equals(A a) { return this.x == a.x; } }

A. Program 1 displays true and Program 2 displays true B. Program 1 displays false and Program 2 displays true C. Program 1 displays true and Program 2 displays false D. Program 1 displays false and Program 2 displays false

11.36 Analyze the following code.

// Program 1 public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(((A)a1).equals((A)a2)); } }

class A { int x;

public boolean equals(A a) { return this.x == a.x; } }

// Program 2 public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); } }

class A { int x;

public boolean equals(A a) { return this.x == a.x; } }

A. Program 1 displays true and Program 2 displays true B. Program 1 displays false and Program 2 displays true C. Program 1 displays true and Program 2 displays false D. Program 1 displays false and Program 2 displays false

Section 11.11 The ArrayList Class 11.37 You can create an ArrayList using _________.

A. new ArrayList[] B. new ArrayList[100] C. new ArrayList() D. ArrayList()

11.38 Invoking _________ removes all elements in an ArrayList x.

A. x.remove() B. x.clean() C. x.delete() D. x.empty() E. x.clear()

11.39 Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following methods will cause the list to become [Beijing, Chicago, Singapore]?

A. x.add("Chicago") B. x.add(0, "Chicago") C. x.add(1, "Chicago") D. x.add(2, "Chicago")

11.40 Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following method will cause the list to become [Beijing]?

A. x.remove("Singapore") B. x.remove(0) C. x.remove(1) D. x.remove(2)

11.41 Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following method will cause runtime errors?

A. x.get(1) B. x.set(2, "New York"); C. x.get(2) D. x.remove(2) E. x.size()

11.42 Invoking _________ returns the first element in an ArrayList x.

A. x.first() B. x.get(0) C. x.get(1) D. x.get()

11.43 Invoking _________ returns the number of the elements in an ArrayList x.

A. x.getSize() B. x.getLength(0) C. x.length(1) D. x.size()

11.44 Analyze the following code:

ArrayList list = new ArrayList(); list.add("Beijing"); list.add("Tokyo"); list.add("Shanghai"); list.set(3, "Hong Kong");

A. The last line in the code causes a runtime error because there is no element at index 3 in the array list. B. The last line in the code has a compile error because there is no element at index 3 in the array list. C. If you replace the last line by list.add(3, "Hong Kong"), the code will compile and run fine. D. If you replace the last line by list.add(4, "Hong Kong"), the code will compile and run fine.

11.45 What is output of the following code:

ArrayList<java.util.Date> list = new ArrayList<java.util.Date>();
java.util.Date d = new java.util.Date();
list.add(d);
list.add(d);
System.out.println((list.get(0) == list.get(1)) + " " + (list.get(0)).equals(list.get(1)));

A. true false B. false true C. true true D. false false

11.46 What is output of the following code:

ArrayList<String> list = new ArrayList<String>();
String s1 = new String("Java");
String s2 = new String("Java");
list.add(s1);
list.add(s2);
System.out.println((list.get(0) == list.get(1)) + " " + (list.get(0)).equals(list.get(1)));

A. true false B. false true C. true true D. false false

11.47 Suppose an ArrayList list contains {"red", "green", "red", "green"}. What is list after the following code?

list.remove("red");

A. {"red", "green", "red", "green"} B. {"green", "red", "green"} C. {"green", "green"} D. {"red", "green", "green"}

11.48 Suppose an ArrayList list contains {"red", "red", "green"}. What is list after the following code?

String element = "red";
for (int i = 0; i < list.size(); i++)
  if (list.get(i).equals(element))
    list.remove(element);

A. {"red", "red", "green"} B. {"red", "green"} C. {"green"} D. {}

11.49 Suppose an ArrayList list contains {"red", "red", "green"}. What is list after the following code?

String element = "red";
for (int i = 0; i < list.size(); i++)
  if (list.get(i).equals(element)) {
    list.remove(element);
    i--;
  }

A. {"red", "red", "green"} B. {"red", "green"} C. {"green"} D. {}

11.50 Suppose an ArrayList list contains {"red", "red", "green"}. What is list after the following code?

String element = "red";
for (int i = list.size() - 1; i >= 0; i--)
  if (list.get(i).equals(element))
    list.remove(element);

A. {"red", "red", "green"} B. {"red", "green"} C. {"green"} D. {}

11.51 The output from the following code is __________.

java.util.ArrayList list = new java.util.ArrayList(); list.add("New York"); java.util.ArrayList list1 = list; list.add("Atlanta"); list1.add("Dallas"); System.out.println(list1);

A. [New York] B. [New York, Atlanta] C. [New York, Atlanta, Dallas] D. [New York, Dallas]

11.52 Which of the following code is corrcet?

A. ArrayList list = new ArrayList<>(); list.add(3.4); B. ArrayList list = new ArrayList<>(); list.add(3.4); C. ArrayList list = new ArrayList<>(); list.add(3); D. ArrayList list = new ArrayList<>(); list.add(3);

Section 11.13 The protected Data and Methods 11.53 What modifier should you use on a class so that a class in the same package can access it but a class in a different package cannot access it?

A. public B. private C. protected D. Use the default modifier.

11.54 What modifier should you use on the members of a class so that they are not accessible to another class in a different package, but are accessible to any subclasses in any package?

A. public B. private C. protected D. Use the default modifier.

11.55 The visibility of these modifiers increases in this order:

A. private, protected, none (if no modifier is used), and public. B. private, none (if no modifier is used), protected, and public. C. none (if no modifier is used), private, protected, and public. D. none (if no modifier is used), protected, private, and public.

11.56 A class design requires that a particular member variable must be accessible by any subclasses of this class, but otherwise not by classes which are not members of the same package. What should be done to achieve this?

A. The variable should be marked public. B. The variable should be marked private. C. The variable should be marked protected. D. The variable should have no special access modifier. E. The variable should be marked private and an accessor method provided.

11.57 Which of the following statements is false?

A. A public class can be accessed by a class from a different package. B. A private method cannot be accessed by a class in a different package. C. A protected method can be accessed by a subclass in a different package. D. A method with no visibility modifier can be accessed by a class in a different package.

11.58 Which statements are most accurate regarding the following classes?

class A { private int i; protected int j;

public int getI() { return i; }

public int getJ() { return j; } }

class B extends A { private int k; protected int m;

public int getK() { return k; }

public int getM() { return m; } }

A. An object of B contains data fields i, j, k, m. B. An object of B contains data fields j, k, m. C. An object of B contains data fields j, m. D. An object of B contains data fields k, m.

11.59 Which statements are most accurate regarding the following classes?

class A { private int i; protected int j; }

class B extends A { private int k; protected int m;

// some methods omitted }

A. In the class B, an instance method can only access i, j, k, m. B. In the class B, an instance method can only access j, k, m. C. In the class B, an instance method can only access j, m. D. In the class B, an instance method can only access k, m.

Section 11.14 Preventing Extending and Overriding 11.60 Which of the following classes cannot be extended?

A. class A { } B. class A { private A();} C. final class A { } D. class A { protected A();}

Section Comprehensive 11.61 Polymorphism means ______________.

A. that data fields should be declared private. B. that a class can extend another class. C. that a variable of supertype can refer to a subtype object. D. that a class can contain another class.

11.62 Encapsulation means ______________.

A. that data fields should be declared private. B. that a class can extend another class. C. that a variable of supertype can refer to a subtype object. D. that a class can contain another class.

11.63 Inheritance means ______________.

A. that data fields should be declared private. B. that a class can extend another class. C. that a variable of supertype can refer to a subtype object. D. that a class can contain another class.

11.64 Composition means ______________. A. that data fields should be declared private. B. that a class extends another class. C. that a variable of supertype refers to a subtype object. D. that a class contains a data field that references another object.

14.1 A Java exception is an instance of __________.

A. RuntimeException B. Exception C. Error D. Throwable E. NumberFormatException

14.2 An instance of _________ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

A. RuntimeException B. Exception C. Error D. Throwable E. NumberFormatException

14.3 An instance of _________ describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program.

A. RuntimeException B. Exception C. Error D. Throwable E. NumberFormatException

14.4 An instance of _________ describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors..

A. RuntimeException B. Exception C. Error D. Throwable E. NumberFormatException

14.5 The following code causes Java to throw _________. int number = Integer.MAX_VALUE + 1;

A. RuntimeException B. Exception C. Error D. Throwable E. no exceptions

14.6 An instance of _________ are unchecked exceptions.

A. RuntimeException B. Exception C. Error D. Throwable E. NumberFormatException

14.7 What exception type does the following program throw? public class Test { public static void main(String[] args) { System.out.println(1 / 0); } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. ClassCastException E. No exception

14.8 What exception type does the following program throw? public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. ClassCastException E. No exception

14.9 What exception type does the following program throw? public class Test { public static void main(String[] args) { String s = "abc"; System.out.println(s.charAt(3)); } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. ClassCastException E. No exception

14.10 What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. ClassCastException E. No exception

14.11 What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. ClassCastException E. NullPointerException

14.12 What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); } }

A. ArithmeticException B. ArrayIndexOutOfBoundsException C. StringIndexOutOfBoundsException D. No exception E. NullPointerException

Section 14.4 More on Exception Handling 14.13 A method must declare to throw ________.

A. unchecked exceptions B. checked exceptions C. Error D. RuntimeException

14.14 Which of the following statements are true?

A. You use the keyword throws to declare exceptions in the method heading. B. A method may declare to throw multiple exceptions. C. To throw an exception, use the key word throw. D. If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method.

14.15 Analyze the following code:

class Test { public static void main(String[] args) throws MyException { System.out.println("Welcome to Java"); } }

class MyException extends Error { }

A. You should not declare a class that extends Error, because Error raises a fatal error that terminates the program. B. You cannot declare an exception in the main method. C. You declared an exception in the main method, but you did not throw it. D. The program has a compilation error.

14.16 Analyze the following code:

class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException

  int i = 0;
  int y = 2 / i;
}
catch (Exception ex) {
  System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
  System.out.println("RuntimeException");
}

} }

A. The program displays NumberFormatException. B. The program displays RuntimeException. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compilation error.

14.17 Analyze the following program.

class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException

  int i = 0;
  int y = 2 / i;
  System.out.println("Welcome to Java");
}
catch (Exception ex) {
  System.out.println(ex);
}

} }

A. An exception is raised due to Integer.parseInt(s); B. An exception is raised due to 2 / i; C. The program has a compilation error. D. The program compiles and runs without exceptions.

14.18 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } }

static void method() { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException

int i = 0;
int y = 2 / i;
System.out.println("Welcome to Java");

} }

A. The program displays NumberFormatException. B. The program displays NumberFormatException followed by After the method call. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compilation error. E. The program displays RuntimeException.

14.19 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } }

static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException

  int i = 0;
  int y = 2 / i;
  System.out.println("Welcome to Java");
}
catch (RuntimeException ex) {
  System.out.println("RuntimeException");
}
catch (Exception ex) {
  System.out.println("Exception");
}

} }

A. The program displays RuntimeException twice. B. The program displays Exception twice. C. The program displays RuntimeException followed by After the method call. D. The program displays Exception followed by RuntimeException. E. The program has a compilation error.

Section 14.5 The finally Clause 14.20 What is wrong in the following program?

class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } }

A. You cannot have a try block without a catch block. B. You cannot have a try block without a catch block or a finally block. C. A method call that does not declare exceptions cannot be placed inside a try block. D. Nothing is wrong.

14.21 What is displayed on the console when running the following program?

class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } finally { System.out.println("The finally clause is executed"); } } }

A. Welcome to Java B. Welcome to Java followed by The finally clause is executed in the next line C. The finally clause is executed D. None of the above

14.22 What is displayed on the console when running the following program?

class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); return; } finally { System.out.println("The finally clause is executed"); } } }

A. Welcome to Java B. Welcome to Java followed by The finally clause is executed in the next line C. The finally clause is executed D. None of the above

14.23 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

A. Welcome to Java, then an error message. B. Welcome to Java followed by The finally clause is executed in the next line, then an error message. C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed, then an error message. D. None of the above.

14.24 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; double y = 2.0 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

A. Welcome to Java. B. Welcome to Java followed by The finally clause is executed in the next line. C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed. D. None of the above.

14.25 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } }

A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java three times. D. The program displays Welcome to Java two times.

14.26 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); }

System.out.println("End of the block");

} }

A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java two times followed by End of the block two times. D. You cannot catch RuntimeException errors.

14.27 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); }

System.out.println("End of the block");

} }

A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java two times followed by End of the block two times. D. The program displays Welcome to Java and End of the block, and then terminates because of an unhandled exception.

Section 14.6 When to Use Exceptions 14.28 Which of the following is not an advantage of Java exception handling?

A. Java separates exception handling from normal processing tasks. B. Exception handling improves performance. C. Exception handling makes it possible for the caller's caller to handle the exception. D. Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block.

14.29 Analyze the following code:

class Test { public static void main(String[] args) { try { int zero = 0; int y = 2/zero; try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException } catch(Exception e) { } } catch(RuntimeException e) { System.out.println(e); } } }

A. A try-catch block cannot be embedded inside another try-catch block. B. A good programming practice is to avoid nesting try-catch blocks, because nesting makes programs difficult to read. You can rewrite the program using only one try-catch block. C. The program has a compilation error because Exception appears before RuntimeException. D. None of the above.

Section 14.7 Rethrowing Exceptions 14.30 What is displayed on the console when running the following program?

class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } }

static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException

  int i = 0;
  int y = 2 / i;
  System.out.println("Welcome to Java");
}
catch (NumberFormatException ex) {
  System.out.println("NumberFormatException");
  throw ex;
}
catch (RuntimeException ex) {
  System.out.println("RuntimeException");
}

} }

A. The program displays NumberFormatException twice. B. The program displays NumberFormatException followed by After the method call. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compilation error.

Section 14.10 The File Class 14.31 What are the reasons to create an instance of the File class?

A. To determine whether the file exists. B. To obtain the properties of the file such as whether the file can be read, written, or is hidden. C. To rename the file. D. To delete the file. E. To read/write data from/to a file

14.32 Which of the following returns the path separator character?

A. File.pathSeparator B. File.pathSeparatorChar C. File.separator D. File.separatorChar E. None of the above.

14.33 Which of the following statements creates an instance of File on Window for the file c:\temp.txt?

A. new File("c:\temp.txt") B. new File("c:\temp.txt") C. new File("c:/temp.txt") D. new File("c://temp.txt")

14.34 Which of the following statements are true?

A. If a file (e.g., c:\temp.txt) does not exist, new File("c:\temp.txt") returns null. B. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") returns null. C. If a file (e.g., c:\temp.txt) does not exist, new File("c:\temp.txt") creates a new file named c:\temp.txt. D. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang. E. None of the above.

Section 14.11 Text I/O 14.35 Which class contains the method for checking whether a file exists?

A. File B. PrintWriter C. Scanner D. System

14.36 Which class do you use to write data into a text file?

A. File B. PrintWriter C. Scanner D. System

14.37 Which class do you use to read data from a text file?

A. File B. PrintWriter C. Scanner D. System

14.38 Which method can be used to write data?

A. close B. print C. exist D. rename

14.39 Which method can be used to read a whole line from the file?

A. next B. nextLine C. nextInt D. nextDouble

14.40 Which method can be used to create an input object for file temp.txt?

A. new Scanner("temp.txt") B. new Scanner(temp.txt) C. new Scanner(new File("temp.txt")) D. new Scanner(File("temp.txt"))

14.41 Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); int v1 = input.nextInt(); int v2 = input.nextInt(); String line = input.nextLine();

A. After the last statement is executed, v1 is 34. B. The program has a runtime error because 34.3 is not an integer. C. After the last statement is executed, line contains characters '7', '8', '9', '\n'. D. After the last statement is executed, line contains characters '7', '8', '9'.

14.42 Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); double v1 = input.nextDouble(); double v2 = input.nextDouble(); String line = input.nextLine();

A. After the last statement is executed, line contains characters '7', '8', '9'. B. After the last statement is executed, line contains characters '7', '8', '9', '\n'. C. After the last statement is executed, line contains characters ' ', '7', '8', '9', '\n'. D. After the last statement is executed, line contains characters ' ', '7', '8', '9'.

14.43 Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key. Analyze the following code. 1 Scanner input = new Scanner(System.in); 2 double v1 = input.nextDouble(); 3 double v2 = input.nextDouble(); 4 String line = input.nextLine();

A. After line 2 is executed, v1 is 34.3. B. After line 3 is executed, v2 is 57.8. C. After line 4 is executed, line contains an empty string. D. After line 4 is executed, line is null. E. After line 4 is executed, line contains character "\n".

14.44 Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, abc, the Enter key. Analyze the following code. 1 Scanner input = new Scanner(System.in); 2 double v1 = input.nextDouble(); 3 double v2 = input.nextDouble(); 4 String line = input.nextLine();

A. After line 2 is executed, v1 is 34.3. B. After line 3 is executed, v2 is 57.8. C. After line 4 is executed, line contains an empty string. D. After line 4 is executed, line is null. E. After line 4 is executed, line contains character "abc".

14.45 Which method can be used to create an output object for file temp.txt?

A. new PrintWriter("temp.txt") B. new PrintWriter(temp.txt) C. new PrintWriter(new File("temp.txt")) D. new PrintWriter(File("temp.txt"))

Section 14.13 Reading Data from the Web 14.46 To create an InputStream to read from a file on a Web server, you use the method __________ in the URL class. A. getInputStream(); B. obtainInputStream(); C. openStream(); D. connectStream();

20.1 Which of the following statements are true?

A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case. D. Every recursive method must have a return value. E. A recursive method is invoked differently from a non-recursive method.

20.2 Fill in the code to complete the following method for computing factorial.

/** Return the factorial for a specified index */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return _____________; // Recursive call }

A. n * (n - 1) B. n C. n * factorial(n - 1) D. factorial(n - 1) * n

20.3 What are the base cases in the following recursive method?

public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } }

A. n > 0 B. n <= 0 C. no base cases D. n < 0

20.4 Analyze the following recursive method.

public static long factorial(int n) { return n * factorial(n - 1); }

A. Invoking factorial(0) returns 0. B. Invoking factorial(1) returns 1. C. Invoking factorial(2) returns 2. D. Invoking factorial(3) returns 6. E. The method runs infinitely and causes a StackOverflowError.

20.5 How many times is the factorial method in Listing 20.1 invoked for factorial(5)?

A. 3 B. 4 C. 5 D. 6

Section 20.3 Example: Fibonacci Numbers 20.6 Which of the following statements are true?

A. The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series. B. The Fibonacci series begins with 1 and 1, and each subsequent number is the sum of the preceding two numbers in the series. C. The Fibonacci series begins with 1 and 2, and each subsequent number is the sum of the preceding two numbers in the series. D. The Fibonacci series begins with 2 and 3, and each subsequent number is the sum of the preceding two numbers in the series.

20.7 How many times is the fib method in Listing 20.2 invoked for fib(5)?

A. 14 B. 15 C. 25 D. 31 E. 32

20.8 Fill in the code to complete the following method for computing a Fibonacci number.

public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return __________________; }

A. fib(index - 1) B. fib(index - 2) C. fib(index - 1) + fib(index - 2) D. fib(index - 2) + fib(index - 1)

Section 20.4 Problem Solving Using Recursion 20.9 In the following method, what is the base case?

static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

A. n is 1. B. n is greater than 1. C. n is less than 1. D. no base case.

20.10 What is the return value for xMethod(4) after calling the following method?

static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); }

A. 12 B. 11 C. 10 D. 9

20.11 Fill in the code to complete the following method for checking whether a string is a palindrome.

public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if _____________________________ return false; else return isPalindrome(s.substring(1, s.length() - 1)); }

A. (s.charAt(0) != s.charAt(s.length() - 1)) // Base case B. (s.charAt(0) != s.charAt(s.length())) // Base case C. (s.charAt(1) != s.charAt(s.length() - 1)) // Base case D. (s.charAt(1) != s.charAt(s.length())) // Base case

20.12 Analyze the following code:

public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); }

public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1); } }

A. The program displays 1 2 3 4 6. B. The program displays 1 2 3 4 5 and then raises an ArrayIndexOutOfBoundsException. C. The program displays 5 4 3 2 1. D. The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException.

Section 20.5 Recursive Helper Methods 20.13 Fill in the code to complete the following method for checking whether a string is a palindrome.

public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); }

public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return _______________________________; }

A. isPalindrome(s) B. isPalindrome(s, low, high) C. isPalindrome(s, low + 1, high) D. isPalindrome(s, low, high - 1) E. isPalindrome(s, low + 1, high - 1)

20.14 Fill in the code to complete the following method for sorting a list.

public static void sort(double[] list) { ___________________________; }

public static void sort(double[] list, int high) { if (high > 1) { // Find the largest number and its index int indexOfMax = 0; double max = list[0]; for (int i = 1; i <= high; i++) { if (list[i] > max) { max = list[i]; indexOfMax = i; } }

// Swap the largest with the last number in the list
list[indexOfMax] = list[high];
list[high] = max;

// Sort the remaining list
sort(list, high - 1);

} }

A. sort(list) B. sort(list, list.length) C. sort(list, list.length - 1) D. sort(list, list.length - 2)

20.15 Fill in the code to complete the following method for binary search.

public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return __________________________; }

public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; // Return -insertion point - 1

int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }

A. recursiveBinarySearch(list, key) B. recursiveBinarySearch(list, key, low + 1, high - 1) C. recursiveBinarySearch(list, key, low - 1, high + 1) D. recursiveBinarySearch(list, key, low, high)

Section 20.7 Tower of Hanoi 20.16 How many times is the recursive moveDisks method invoked for 3 disks?

A. 3 B. 7 C. 10 D. 14

20.17 How many times is the recursive moveDisks method invoked for 4 disks?

A. 5 B. 10 C. 15 D. 20

20.18 Analyze the following two programs:

A:

public class Test { public static void main(String[] args) { xMethod(5); }

public static void xMethod(int length) { if (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } }

B: public class Test { public static void main(String[] args) { xMethod(5); }

public static void xMethod(int length) { while (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } }

A. The two programs produce the same output 5 4 3 2 1. B. The two programs produce the same output 1 2 3 4 5. C. The two programs produce the same output 4 3 2 1. D. The two programs produce the same output 1 2 3 4. E. Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely.

Section 20.8 Fractals 20.19 The following program draws squares recursively. Fill in the missing code.

import javax.swing.; import java.awt.;

public class Test extends JApplet { public Test() { add(new SquarePanel()); }

static class SquarePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g);

  int width = (int)(Math.min(getWidth(), getHeight()) * 0.4);
  int centerx = getWidth() / 2;
  int centery = getHeight() / 2;

  displaySquares(g, width, centerx, centery);
}

private static void displaySquares(Graphics g, int width,
    int centerx, int centery) {
  if (width >= 20) {
    g.drawRect(centerx - width, centery - width, 2* width, 2 * width);
    displaySquares(_________, width - 20, centerx, centery);
  }
}

} }

A. getGraphics() B. newGraphics() C. null D. g

Section 20.9 Recursion versus Iteration 20.20 Which of the following statements are true?

A. Recursive methods run faster than non-recursive methods. B. Recursive methods usually take more memory space than non-recursive methods. C. A recursive method can always be replaced by a non-recursive method. D. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve.

Section 20.10 Tail Recursion 20.21 Analyze the following functions;

public class Test1 { public static void main(String[] args) { System.out.println(f1(3)); System.out.println(f2(3, 0)); }

public static int f1(int n) { if (n == 0) return 0; else { return n + f1(n - 1); } }

public static int f2(int n, int result) { if (n == 0) return result; else return f2(n - 1, n + result); } }

A. f1 is tail recursion, but f2 is not B. f2 is tail recursion, but f1 is not C. f1 and f2 are both tail recursive D. Neither f1 nor f2 is tail recursive

20.22 Show the output of the following code

public class Test1 { public static void main(String[] args) { System.out.println(f2(2, 0)); }

public static int f2(int n, int result) { if (n == 0) return 0; else return f2(n - 1, n + result); } }

A. 0 B. 1 C. 2 D. 3

2.1 Suppose a Scanner object is created as follows:

Scanner input = new Scanner(System.in);

What method do you use to read an int value?

A. input.nextInt(); B. input.nextInteger(); C. input.int(); D. input.integer();

2.2 The following code fragment reads in two numbers:

Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble();

What are the correct ways to enter these two numbers?

A. Enter an integer, a space, a double value, and then the Enter key. B. Enter an integer, two spaces, a double value, and then the Enter key. C. Enter an integer, an Enter key, a double value, and then the Enter key. D. Enter a numeric value with a decimal point, a space, an integer, and then the Enter key.

2.3 _______ is the code with natural language mixed with Java code.

A. Java program B. A Java statement C. Pseudocode D. A flowchart diagram

2.4 If you enter 1 2 3, when you run this program, what will be the output?

import java.util.Scanner;

public class Test1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter three numbers: "); double number1 = input.nextDouble(); double number2 = input.nextDouble(); double number3 = input.nextDouble();

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display result
System.out.println(average);

} }

A. 1.0 B. 2.0 C. 3.0 D. 4.0

2.5 What is the exact output of the following code?

double area = 3.5; System.out.print("area"); System.out.print(area);

A. 3.53.5 B. 3.5 3.5 C. area3.5 D. area 3.5

Section 2.4 Identifiers 2.6 Every letter in a Java keyword is in lowercase?

A. true B. false

2.7 Which of the following is a valid identifier?

A. $343 B. class C. 9X D. 8+9 E. radius

Section 2.5 Variables 2.8 Which of the following are correct names for variables according to Java naming conventions?

A. radius B. Radius C. RADIUS D. findArea E. FindArea

2.9 Which of the following are correct ways to declare variables?

A. int length; int width; B. int length, width; C. int length; width; D. int length, int width;

Section 2.6 Assignment Statements and Assignment Expressions 2.10 ____________ is the Java assignment operator.

A. == B. := C. = D. =:

2.11 To assign a value 1 to variable x, you write

A. 1 = x; B. x = 1; C. x := 1; D. 1 := x; E. x == 1;

2.12 Which of the following assignment statements is incorrect?

A. i = j = k = 1; B. i = 1; j = 1; k = 1; C. i = 1 = j = 1 = k = 1; D. i == j == k == 1;

Section 2.7 Named Constants 2.13 To declare a constant MAX_LENGTH inside a method with value 99.98, you write

A. final MAX_LENGTH = 99.98; B. final float MAX_LENGTH = 99.98; C. double MAX_LENGTH = 99.98; D. final double MAX_LENGTH = 99.98;

2.14 Which of the following is a constant, according to Java naming conventions?

A. MAX_VALUE B. Test C. read D. ReadInt E. COUNT

2.15 To improve readability and maintainability, you should declare _________ instead of using literal values such as 3.14159.

A. variables B. methods C. constants D. classes

Section 2.8 Naming Conventions 2.16 According to Java naming convention, which of the following names can be variables?

A. FindArea B. findArea C. totalLength D. TOTAL_LENGTH E. class

Section 2.9 Numeric Data Types and Operations 2.17 Which of these data types requires the most amount of memory?

A. long B. int C. short D. byte

2.18 If a number is too large to be stored in a variable of the float type, it _____________.

A. causes overflow B. causes underflow C. causes no error D. cannot happen in Java

2.19 Analyze the following code:

public class Test { public static void main(String[] args) { int n = 10000 * 10000 * 10000; System.out.println("n is " + n); } }

A. The program displays n is 1000000000000 B. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an overflow and the program is aborted. C. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an overflow and the program continues to execute because Java does not report errors on overflow. D. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an underflow and the program is aborted. E. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an underflow and the program continues to execute because Java does not report errors on underflow.

2.20 What is the result of 45 / 4?

A. 10 B. 11 C. 11.25 D. 12

2.21 Which of the following expression results in a value 1?

A. 2 % 1 B. 15 % 4 C. 25 % 5 D. 37 % 6

2.22 25 % 1 is _____

A. 1 B. 2 C. 3 D. 4 E. 0

2.23 -25 % 5 is _____

A. 1 B. 2 C. 3 D. 4 E. 0

2.24 24 % 5 is _____

A. 1 B. 2 C. 3 D. 4 E. 0

2.25 -24 % 5 is _____

A. -1 B. -2 C. -3 D. -4 E. 0

2.26 -24 % -5 is _____

A. 3 B. -3 C. 4 D. -4 E. 0

2.27 Math.pow(2, 3) returns __________.

A. 9 B. 8 C. 9.0 D. 8.0

2.28 Math.pow(4, 1 / 2) returns __________.

A. 2 B. 2.0 C. 0 D. 1.0 E. 1

2.29 Math.pow(4, 1.0 / 2) returns __________.

A. 2 B. 2.0 C. 0 D. 1.0 E. 1

2.30 The __________ method returns a raised to the power of b.

A. Math.power(a, b) B. Math.exponent(a, b) C. Math.pow(a, b) D. Math.pow(b, a)

Section 2.10 Numeric Literals 2.31 To declare an int variable number with initial value 2, you write

A. int number = 2L; B. int number = 2l; C. int number = 2; D. int number = 2.0;

2.32 Analyze the following code.

public class Test { public static void main(String[] args) { int month = 09; System.out.println("month is " + month); } }

A. The program displays month is 09 B. The program displays month is 9 C. The program displays month is 9.0 D. The program has a syntax error, because 09 is an incorrect literal value.

2.33 Which of the following are the same as 1545.534?

A. 1.545534e+3 B. 0.1545534e+4 C. 1545534.0e-3 D. 154553.4e-2

Section 2.11 Evaluating Expressions and Operator Precedence 2.34 The expression 4 + 20 / (3 - 1) * 2 is evaluated to

A. 4 B. 20 C. 24 D. 9 E. 25

Section 2.13 Augmented Assignment Operators 2.35 To add a value 1 to variable x, you write

A. 1 + x = x; B. x += 1; C. x := 1; D. x = x + 1; E. x = 1 + x;

2.36 To add number to sum, you write (Note: Java is case-sensitive)

A. number += sum; B. number = sum + number; C. sum = Number + sum; D. sum += number; E. sum = sum + number;

2.37 Suppose x is 1. What is x after x += 2?

A. 0 B. 1 C. 2 D. 3 E. 4

2.38 Suppose x is 1. What is x after x -= 1?

A. 0 B. 1 C. 2 D. -1 E. -2

2.39 What is x after the following statements?

int x = 2; int y = 1; x *= y + 1;

A. x is 1. B. x is 2. C. x is 3. D. x is 4.

2.40 What is x after the following statements?

int x = 1; x *= x + 1;

A. x is 1. B. x is 2. C. x is 3. D. x is 4.

2.41 Which of the following statements are the same?

(A) x -= x + 4 (B) x = x + 4 - x (C) x = x - (x + 4)

A. (A) and (B) are the same B. (A) and (C) are the same C. (B) and (C) are the same D. (A), (B), and (C) are the same

Section 2.14 Increment and Decrement Operators 2.42 Are the following four statements equivalent? number += 1; number = number + 1; number++; ++number;

A. Yes B. No

2.43 What is the value of i printed? public class Test { public static void main(String[] args) { int j = 0; int i = ++j + j * 5;

System.out.println("What is i? " + i);

} }

A. 0 B. 1 C. 5 D. 6

2.44 What is the value of i printed in the following code?

public class Test { public static void main(String[] args) { int j = 0; int i = j++ + j * 5;

System.out.println("What is i? " + i);

} }

A. 0 B. 1 C. 5 D. 6

2.45 What is y displayed in the following code?

public class Test { public static void main(String[] args) { int x = 1; int y = x++ + x; System.out.println("y is " + y); } }

A. y is 1. B. y is 2. C. y is 3. D. y is 4.

2.46 What is y displayed?

public class Test { public static void main(String[] args) { int x = 1; int y = x + x++; System.out.println("y is " + y); } }

A. y is 1. B. y is 2. C. y is 3. D. y is 4.

Section 2.15 Numeric Type Conversions 2.47 To assign a double variable d to a float variable x, you write

A. x = (long)d B. x = (int)d; C. x = d; D. x = (float)d;

2.48 Which of the following expressions will yield 0.5?

A. 1 / 2 B. 1.0 / 2 C. (double) (1 / 2) D. (double) 1 / 2 E. 1 / 2.0

2.49 What will be displayed by the following code?

double x = 5.5; int y = (int)x; System.out.println("x is " + x + " and y is " + y);

A. x is 5 and y is 6 B. x is 6.0 and y is 6.0 C. x is 6 and y is 6 D. x is 5.5 and y is 5 E. x is 5.5 and y is 5.0

2.50 Which of the following assignment statements is illegal?

A. float f = -34; B. int t = 23; C. short s = 10; D. int t = (int)false; E. int t = 4.5;

2.51 What is the value of (double)5/2?

A. 2 B. 2.5 C. 3 D. 2.0 E. 3.0

2.52 What is the value of (double)(5/2)?

A. 2 B. 2.5 C. 3 D. 2.0 E. 3.0

2.53 Which of the following expression results in 45.37?

A. (int)(45.378 * 100) / 100 B. (int)(45.378 * 100) / 100.0 C. (int)(45.378 * 100 / 100) D. (int)(45.378) * 100 / 100.0

2.54 The expression (int)(76.0252175 * 100) / 100 evaluates to _________.

A. 76.02 B. 76 C. 76.0252175 D. 76.03

2.55 If you attempt to add an int, a byte, a long, and a double, the result will be a __________ value.

A. byte B. int C. long D. double

Section 2.16 Software Life Cycle 2.56 _____________ is a formal process that seeks to understand the problem and document in detail what the software system needs to do.

A. Requirements specification B. Analysis C. Design D. Implementation E. Testing

2.57 _____________ seeks to analyze the data flow and to identify the system's input and output.

A. Requirements specification B. System analysis C. Design D. Implementation E. Testing

Section 2.17 Character Data Type and Operations 2.58 Which of the following is the correct expression of character 4?

A. 4 B. "4" C. '\0004' D. '4'

2.59 A Java character is stored in __________.

A. one byte B. two bytes C. three bytes D. four bytes

2.60 Suppose x is a char variable with a value 'b'. What will be displayed by the statement System.out.println(++x)?

A. a B. b C. c D. d

2.61 Which of the following statement prints smith\exam1\test.txt?

A. System.out.println("smith\exam1\test.txt"); B. System.out.println("smith\exam1\test.txt"); C. System.out.println("smith"exam1"test.txt"); D. System.out.println("smith"\exam1"\test.txt");

2.62 Suppose i is an int type variable. Which of the following statements display the character whose Unicode is stored in variable i?

A. System.out.println(i); B. System.out.println((char)i); C. System.out.println((int)i); D. System.out.println(i + " ");

2.63 The Unicode of 'a' is 97. What is the Unicode for 'c'?

A. 96 B. 97 C. 98 D. 99

2.64 Will System.out.println((char)4) display 4?

A. Yes B. No

2.65 What will be displayed by System.out.println('z' - 'a')?

A. 25 B. 26 C. a D. z

2.66 An int variable can hold __________.

A. 'x' B. 120 C. 120.0 D. "x" E. "120"

2.67 Which of the following assignment statements is correct?

A. char c = 'd'; B. char c = 100; C. char c = "d"; D. char c = "100";

2.68 '3' - '2' + 'm' / 'n' is ______.

A. 0 B. 1 C. 2 D. 3

Section 2.18 The String Type 2.69 The expression "Java " + 1 + 2 + 3 evaluates to ________.

A. Java123 B. Java6 C. Java 123 D. java 123 E. Illegal expression

2.70 Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to ________.

A. 66 B. B C. A1 D. Illegal expression

2.71 Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to ________.

A. 66 B. B C. A1 D. Illegal expression

2.72 The System.currentTimeMillis() returns ________________ .

A. the current time. B. the current time in milliseconds. C. the current time in milliseconds since midnight. D. the current time in milliseconds since midnight, January 1, 1970. E. the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).

Section 2.19 Getting Input from Input Dialogs 2.73 The __________ method displays an input dialog for reading a string.

A. String string = JOptionPane.showMessageDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); B. String string = JOptionPane.showInputDialog(null, "Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); C. String string = JOptionPane.showInputDialog("Enter a string", "Input Demo", JOptionPane.QUESTION_MESSAGE); D. String string = JOptionPane.showInputDialog(null, "Enter a string"); E. String string = JOptionPane.showInputDialog("Enter a string");

2.74 The __________ method parses a string s to an int value.

A. integer.parseInt(s); B. Integer.parseInt(s); C. integer.parseInteger(s); D. Integer.parseInteger(s);

2.75 The __________ method parses a string s to a double value.

A. double.parseDouble(s); B. Double.parsedouble(s); C. double.parse(s); D. Double.parseDouble(s);

2.76 Analyze the following code.

import javax.swing.*;

public class ShowErrors { public static void main(String[] args) { int i; int j; String s = JOptionPane.showInputDialog(null, "Enter an integer", "Input", JOptionPane.QUESTION_MESSAGE); j = Integer.parseInt(s);

i = (i + 4);

} } A. The program cannot compile because j is not initialized. B. The program cannot compile because i does not have an initial value when it is used in i = i + 4; C. The program compiles but has a runtime error because i does not have an initial value when it is used in i = i + 4; D. The program compiles and runs fine.

3.1 The "less than or equal to" comparison operator in Java is __________.

A. < B. <= C. =< D. << E. !=

3.2 The equal comparison operator in Java is __________.

A. <> B. != C. == D. ^=

3.3 What is 1 + 1 + 1 + 1 + 1 == 5?

A. true B. false C. There is no guarantee that 1 + 1 + 1 + 1 + 1 == 5 is true.

3.4 What is 1.0 + 1.0 + 1.0 + 1.0 + 1.0 == 5.0?

A. true B. false C. There is no guarantee that 1.0 + 1.0 + 1.0 + 1.0 + 1.0 == 5.0 is true.

3.5 In Java, the word true is ________.

A. a Java keyword B. a Boolean literal C. same as value 1 D. same as value 0

Sections 3.3-3.10 3.6 Which of the following code displays the area of a circle if the radius is positive.

A. if (radius != 0) System.out.println(radius * radius * 3.14159); B. if (radius >= 0) System.out.println(radius * radius * 3.14159); C. if (radius > 0) System.out.println(radius * radius * 3.14159); D. if (radius <= 0) System.out.println(radius * radius * 3.14159);

3.7 Suppose x = 1, y = -1, and z = 1. What will be displayed by the following statement? (Please indent the statement correctly first.)

if (x > 0) if (y > 0) System.out.println("x > 0 and y > 0"); else if (z > 0) System.out.println("x < 0 and z > 0");

A. x > 0 and y > 0 B. x < 0 and z > 0 C. x < 0 and z < 0 D. none

3.8 Analyze the following code:

boolean even = false; if (even = true) { System.out.println("It is even!"); }

A. The program has a compile error. B. The program has a runtime error. C. The program runs, but displays nothing. D. The program runs and displays It is even!.

3.9 Suppose isPrime is a boolean variable, which of the following is the correct and best statement for testing if isPrime is true.

A. if (isPrime = true) B. if (isPrime == true) C. if (isPrime) D. if (!isPrime = false) E. if (!isPrime == false)

3.10 What is the output of the following code?

int x = 0; if (x < 4) { x = x + 1; } System.out.println("x is " + x);

A. x is 0 B. x is 1 C. x is 2 D. x is 3 E. x is 4

3.11 Analyze the following code.

boolean even = false; if (even) { System.out.println("It is even!"); }

A. The code displays It is even! B. The code displays nothing. C. The code is wrong. You should replace if (even) with if (even == true) D. The code is wrong. You should replace if (even) with if (even = true)

3.12 The following code displays ___________.

double temperature = 50;

if (temperature >= 100) System.out.println("too hot"); else if (temperature <= 40) System.out.println("too cold"); else System.out.println("just right");

A. too hot B. too cold C. just right D. too hot too cold just right

3.13 Analyze the following code:

Code 1:

int number = 45; boolean even;

if (number % 2 == 0) even = true; else even = false;

Code 2:

int number = 45; boolean even = (number % 2 == 0);

A. Code 1 has compile errors. B. Code 2 has compile errors. C. Both Code 1 and Code 2 have compile errors. D. Both Code 1 and Code 2 are correct, but Code 2 is better.

3.14 Suppose income is 4001, what is the output of the following code:

if (income > 3000) { System.out.println("Income is greater than 3000"); } else if (income > 4000) { System.out.println("Income is greater than 4000"); }

A. no output B. Income is greater than 3000 C. Income is greater than 3000 followed by Income is greater than 4000 D. Income is greater than 4000 E. Income is greater than 4000 followed by Income is greater than 3000

3.15 The __________ method immediately terminates the program.

A. System.terminate(0); B. System.halt(0); C. System.exit(0); D. System.quit(0); E. System.stop(0);

3.16 Suppose you write the code to display "Cannot get a driver's license" if age is less than 16 and "Can get a driver's license" if age is greater than or equal to 16. Which of the following code is correct?

I: if (age < 16) System.out.println("Cannot get a driver's license"); if (age >= 16) System.out.println("Can get a driver's license");

II: if (age < 16) System.out.println("Cannot get a driver's license"); else System.out.println("Can get a driver's license");

III: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age >= 16) System.out.println("Can get a driver's license");

IV: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age > 16) System.out.println("Can get a driver's license"); else if (age == 16) System.out.println("Can get a driver's license");

A. I B. II C. III D. IV

3.17 Suppose you write the code to display "Cannot get a driver's license" if age is less than 16 and "Can get a driver's license" if age is greater than or equal to 16. Which of the following code is the best?

I: if (age < 16) System.out.println("Cannot get a driver's license"); if (age >= 16) System.out.println("Can get a driver's license");

II: if (age < 16) System.out.println("Cannot get a driver's license"); else System.out.println("Can get a driver's license");

III: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age >= 16) System.out.println("Can get a driver's license");

IV: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age > 16) System.out.println("Can get a driver's license"); else if (age == 16) System.out.println("Can get a driver's license");

A. I B. II C. III D. IV

Sections 3.11-3.13 3.18 Which of the Boolean expressions below is incorrect?

A. (true) && (3 => 4) B. !(x > 0) && (x > 0) C. (x > 0) || (x < 0) D. (x != 0) || (x = 0) E. (-10 < x < 0)

3.19 Which of the following is the correct expression that evaluates to true if the number x is between 1 and 100 or the number is negative?

A. 1 < x < 100 && x < 0 B. ((x < 100) && (x > 1)) || (x < 0) C. ((x < 100) && (x > 1)) && (x < 0) D. (1 > x > 100) || (x < 0)

3.20 Assume x = 4 and y = 5, Which of the following is true?

A. x < 5 && y < 5 B. x < 5 || y < 5 C. x > 5 && y > 5 D. x > 5 || y > 5

3.21 Assume x = 4, Which of the following is true?

A. !(x == 4) B. x != 4 C. x == 5 D. x != 5

3.22 Assume x = 4 and y = 5, Which of the following is true?

A. !(x == y) B. x != y C. x == y D. x >= y

3.23 Which of the following is equivalent to x != y?

A. ! (x == y) B. x > y && x < y C. x > y || x < y D. x >= y || x <= y

3.24 Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x-- > 10)?

A. 9 B. 10 C. 11

3.25 Suppose x=10 and y=10 what is x after evaluating the expression (y > 10) && (x++ > 10).

A. 9 B. 10 C. 11

3.26 Suppose x=10 and y=10 what is x after evaluating the expression (y >= 10) || (x-- > 10).

A. 9 B. 10 C. 11

3.27 Suppose x=10 and y=10 what is x after evaluating the expression (y >= 10) || (x++ > 10).

A. 9 B. 10 C. 11

3.28 To check whether a char variable ch is an uppercase letter, you write ___________.

A. (ch >= 'A' && ch >= 'Z') B. (ch >= 'A' && ch <= 'Z') C. (ch >= 'A' || ch <= 'Z') D. ('A' <= ch <= 'Z')

3.29 Analyze the following code:

if (x < 100) && (x > 10) System.out.println("x is between 10 and 100");

A. The statement has compile errors because (x<100) & (x > 10) must be enclosed inside parentheses. B. The statement has compile errors because (x<100) & (x > 10) must be enclosed inside parentheses and the println(?) statement must be put inside a block. C. The statement compiles fine. D. The statement compiles fine, but has a runtime error.

3.30 What is the output of the following code?

char ch = 'F'; if (ch >= 'A' && ch <= 'Z') System.out.println(ch);

A. F B. f C. nothing D. F f

Section 3.14 switch Statements 3.31 What is y after the following switch statement is executed?

int x = 3; int y = 4; switch (x + 3) { case 6: y = 0; case 7: y = 1; default: y += 1; }

A. 1 B. 2 C. 3 D. 4 E. 0

3.32 What will be displayed by the following switch statement?

char ch = 'a';

switch (ch) {
  case 'a':
  case 'A':
    System.out.print(ch); break;
  case 'b':
  case 'B':
    System.out.print(ch); break;
  case 'c':
  case 'C':
    System.out.print(ch); break;
  case 'd':
  case 'D':
    System.out.print(ch);
}

A. abcd B. a C. aa D. ab E. abc

3.33 What will be displayed by the following switch statement?

char ch = 'b';

switch (ch) {
  case 'a':
    System.out.print(ch);
  case 'b':
    System.out.print(ch);
  case 'c':
    System.out.print(ch);
  case 'd':
    System.out.print(ch);
}

A. abcd B. bcd C. b D. bb E. bbb

3.34 Analyze the following program fragment:

int x; double d = 1.5;

switch (d) { case 1.0: x = 1; case 1.5: x = 2; case 2.0: x = 3; }

A. The program has a compile error because the required break statement is missing in the switch statement. B. The program has a compile error because the required default case is missing in the switch statement. C. The switch control variable cannot be double. D. No errors.

Section 3.15 Conditional Expressions 3.35 What is y after the following statement is executed?

x = 0; y = (x > 0) ? 10 : -10;

A. -10 B. 0 C. 10 D. 20 E. Illegal expression

3.36 Analyze the following code fragments that assign a boolean value to the variable even.

Code 1: if (number % 2 == 0) even = true; else even = false;

Code 2: even = (number % 2 == 0) ? true: false;

Code 3: even = number % 2 == 0;

A. Code 2 has a compile error, because you cannot have true and false literals in the conditional expression. B. Code 3 has a compile error, because you attempt to assign number to even. C. All three are correct, but Code 1 is preferred. D. All three are correct, but Code 2 is preferred. E. All three are correct, but Code 3 is preferred.

3.37 What is the output of the following code?

boolean even = false; System.out.println((even ? "true" : "false"));

A. true B. false C. nothing D. true false

Section 3.16 Formatting Console Output and Strings 3.38 Which of the following are valid specifiers for the printf statement?

A. %4c B. %10b C. %6d D. %8.2d E. %10.2e

3.39 The statement System.out.printf("%3.1f", 1234.56) outputs ___________.

A. 123.4 B. 123.5 C. 1234.5 D. 1234.56 E. 1234.6

3.40 The statement System.out.printf("%3.1e", 1234.56) outputs ___________.

A. 0.1e+04 B. 0.123456e+04 C. 0.123e+04 D. 1.2e+03 E. 1.23+03

3.41 The statement System.out.printf("%5d", 123456) outputs ___________.

A. 12345 B. 23456 C. 123456 D. 12345.6

3.42 The statement System.out.printf("%10s", "123456") outputs ___________. (Note: * represents a space)

A. 123456**** B. 23456***** C. 12345***** D. ****123456

3.43 Suppse number contains integer value 4, which of the following statement is correct?

A. System.out.printf("%3d %4d", number, Math.pow(number, 1.5)); B. System.out.printf("%3d %4.2d", number, Math.pow(number, 1.5)); C. System.out.printf("%3d %4.2f", number, Math.pow(number, 1.5)); D. System.out.printf("%3f %4.2d", number, Math.pow(number, 1.5)); E. System.out.printf("%3f %4.2f", number, Math.pow(number, 1.5));

3.44 Analyze the following code:

int i = 3434; double d = 3434; System.out.printf("%5.1f %5.1f", i, d);

A. The code compiles and runs fine to display 3434.0 3434.0. B. The code compiles and runs fine to display 3434 3434.0. C. i is an integer, but the format specifier %5.1f specifies a format for double value. The code has an error.

Section 3.17 Operator Precedence and Associativity 3.45 The order of the precedence (from high to low) of the operators binary +, *, &&, || is:

A. &&, ||, *, + B. *, +, &&, || C. *, +, ||, && D. ||, &&, *, +

3.46 What is y displayed in the following code?

public class Test1 { public static void main(String[] args) { int x = 1; int y = x = x + 1; System.out.println("y is " + y); } }

A. y is 0. B. y is 1 because x is assigned to y first. C. y is 2 because x + 1 is assigned to x and then x is assigned to y. D. The program has a compile error since x is redeclared in the statement int y = x = x + 1.

3.47 Which of the following operators are right-associative.

A. * B. + (binary +) C. % D. && E. =

3.48 What is the value of the following expression? true || true && false

A. true B. false

3.49 Which of the following statements are true? A. (x > 0 && x < 10) is same as ((x > 0) && (x < 10)) B. (x > 0 || x < 10) is same as ((x > 0) || (x < 10)) C. (x > 0 || x < 10 && y < 0) is same as (x > 0 || (x < 10 && y < 0)) D. (x > 0 || x < 10 && y < 0) is same as ((x > 0 || x < 10) && y < 0)

4.1 How many times will the following code print "Welcome to Java"?

int count = 0; while (count < 10) { System.out.println("Welcome to Java"); count++; }

A. 8 B. 9 C. 10 D. 11 E. 0

4.2 What is the output of the following code?

int x = 0; while (x < 4) { x = x + 1; } System.out.println("x is " + x);

A. x is 0 B. x is 1 C. x is 2 D. x is 3 E. x is 4

4.3 Analyze the following code.

int count = 0; while (count < 100) { // Point A System.out.println("Welcome to Java!"); count++; // Point B }

// Point C

A. count < 100 is always true at Point A B. count < 100 is always true at Point B C. count < 100 is always false at Point B D. count < 100 is always true at Point C E. count < 100 is always false at Point C

4.4 How many times will the following code print "Welcome to Java"?

int count = 0; while (count++ < 10) { System.out.println("Welcome to Java"); }

A. 8 B. 9 C. 10 D. 11 E. 0

4.5 What will be displayed when the following code is executed?

int number = 6;
while (number > 0) {
  number -= 3;
  System.out.print(number + " ");
}

A. 6 3 0 B. 6 3 C. 3 0 D. 3 0 -3 E. 0 -3

Section 4.3 The do-while Loop 4.6 How many times will the following code print "Welcome to Java"?

int count = 0; do { System.out.println("Welcome to Java"); count++; } while (count < 10);

A. 8 B. 9 C. 10 D. 11 E. 0

4.7 How many times will the following code print "Welcome to Java"?

int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 10);

A. 8 B. 9 C. 10 D. 11 E. 0

4.8 How many times will the following code print "Welcome to Java"?

int count = 0; do { System.out.println("Welcome to Java"); } while (++count < 10);

A. 8 B. 9 C. 10 D. 11 E. 0

4.9 What is the value in count after the following loop is executed?

int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 9); System.out.println(count);

A. 8 B. 9 C. 10 D. 11 E. 0

Section 4.4 The for Loop 4.10 Analyze the following statement:

double sum = 0; for (double d = 0; d < 10;) { d += 0.1; sum += sum + d; }

A. The program has a compile error because the adjustment is missing in the for loop. B. The program has a compile error because the control variable in the for loop cannot be of the double type. C. The program runs in an infinite loop because d<10 would always be true. D. The program compiles and runs fine.

4.11 Which of the following loops prints "Welcome to Java" 10 times?

A: for (int count = 1; count <= 10; count++) { System.out.println("Welcome to Java"); }

B: for (int count = 0; count < 10; count++) { System.out.println("Welcome to Java"); }

C: for (int count = 1; count < 10; count++) { System.out.println("Welcome to Java"); }

D: for (int count = 0; count <= 10; count++) { System.out.println("Welcome to Java"); }

A. BD B. ABC C. AC D. BC E. AB

4.12 Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?

A: double sum = 0; for (int i = 1; i <= 99; i++) { sum = i / (i + 1); } System.out.println("Sum is " + sum);

B: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1); } System.out.println("Sum is " + sum);

C: double sum = 0; for (int i = 1; i <= 99; i++) { sum += 1.0 * i / (i + 1); } System.out.println("Sum is " + sum);

D: double sum = 0; for (int i = 1; i <= 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum);

E: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum);

A. BCD B. ABCD C. B D. CDE E. CD

4.13 The following loop displays _______________.

for (int i = 1; i <= 10; i++) { System.out.print(i + " "); i++; }

A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 D. 1 3 5 7 9 E. 2 4 6 8 10

4.14 Do the following two statements in (I) and (II) result in the same value in sum?

(I): for (int i = 0; i<10; ++i) { sum += i; }

(II): for (int i = 0; i<10; i++) { sum += i; }

A. Yes B. No

4.15 What is the output for y?

int y = 0; for (int i = 0; i<10; ++i) { y += i; } System.out.println(y);

A. 10 B. 11 C. 12 D. 13 E. 45

4.16 What is i after the following for loop?

int y = 0; for (int i = 0; i<10; ++i) { y += i; }

A. 9 B. 10 C. 11 D. undefined

4.17 Is the following loop correct?

for (; ; );

A. Yes B. No

4.18 Given the following four patterns,

Pattern A Pattern B Pattern C Pattern D 1 1 2 3 4 5 6 1 1 2 3 4 5 6 1 2 1 2 3 4 5 2 1 1 2 3 4 5 1 2 3 1 2 3 4 3 2 1 1 2 3 4 1 2 3 4 1 2 3 4 3 2 1 1 2 3 1 2 3 4 5 1 2 5 4 3 2 1 1 2 1 2 3 4 5 6 1 6 5 4 3 2 1 1

Which of the pattern is produced by the following code? for (int i = 1; i <= 6; i++) { for (int j = 6; j >= 1; j--) System.out.print(j <= i ? j + " " : " " + " "); System.out.println(); }

A. Pattern A B. Pattern B C. Pattern C D. Pattern D

Section 4.5 Which Loop to Use? 4.19 Analyze the following fragment:

double sum = 0; double d = 0; while (d != 10.0) { d += 0.1; sum += sum + d; }

A. The program does not compile because sum and d are declared double, but assigned with integer value 0. B. The program never stops because d is always 0.1 inside the loop. C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers. D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9

4.20 Analyze the following code:

public class Test {
public static void main (String args[]) { int i = 0; for (i = 0; i < 10; i++); System.out.println(i + 4); } }

A. The program has a compile error because of the semicolon (;) on the for loop line. B. The program compiles despite the semicolon (;) on the for loop line, and displays 4. C. The program compiles despite the semicolon (;) on the for loop line, and displays 14. D. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4);

Section 4.6 Nested Loops 4.21 How many times is the println statement executed?

for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) System.out.println(i * j);

A. 100 B. 20 C. 10 D. 45

4.22 How many times is the println statement executed?

for (int i = 0; i < 10; i++) for (int j = 0; j < i; j++) System.out.println(i * j);

A. 100 B. 20 C. 10 D. 45

Section 4.7 Minimizing Numerical Errors 4.23 To add 0.01 + 0.02 + ... + 1.00, what order should you use to add the numbers to get better accuracy?

A. add 0.01, 0.02, ..., 1.00 in this order to a sum variable whose initial value is 0. B. add 1.00, 0.99, 0.98, ..., 0.02, 0.01 in this order to a sum variable whose initial value is 0.

Section 4.9 Keywords break and continue 4.24 Will the following program terminate?

int balance = 10;

while (true) { if (balance < 9) break; balance = balance - 9; }

A. Yes B. No

4.25 What is sum after the following loop terminates?

int sum = 0; int item = 0; do { item++; sum += item; if (sum > 4) break; } while (item < 5);

A. 5 B. 6 C. 7 D. 8

4.26 What will be displayed after the following loop terminates?

int number = 25; int i;

boolean isPrime = true; for (i = 2; i < number && isPrime; i++) { if (number % i == 0) { isPrime = false; } }

System.out.println("i is " + i + " isPrime is " + isPrime);

A. i is 5 isPrime is true B. i is 5 isPrime is false C. i is 6 isPrime is true D. i is 6 isPrime is false

4.27 What will be displayed after the following loop terminates?

int number = 25; int i;

boolean isPrime = true; for (i = 2; i < number; i++) { if (number % i == 0) { isPrime = false; break; } }

System.out.println("i is " + i + " isPrime is " + isPrime);

A. i is 5 isPrime is true B. i is 5 isPrime is false C. i is 6 isPrime is true D. i is 6 isPrime is false

4.28 What is sum after the following loop terminates?

int sum = 0; int item = 0; do { item++; sum += item; if (sum >= 4) continue; } while (item < 5);

A. 15 B. 16 C. 17 D. 18

4.29 Will the following program terminate?

int balance = 10;

while (true) { if (balance < 9) continue; balance = balance - 9; }

A. Yes B. No

4.30 What is the number of iterations in the following loop:

for (int i = 1; i < n; i++) { // iteration }

A. 2*n B. n C. n - 1 D. n + 1

4.31 What is the number of iterations in the following loop:

for (int i = 1; i <= n; i++) { // iteration }

A. 2*n B. n C. n - 1 D. n + 1

4.32 Suppose the input for number is 9. What is the output from running the following program?

import java.util.Scanner;

public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int number = input.nextInt();

int i;

boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
  if (number % i == 0) {
    isPrime = false;
  }
}

System.out.println("i is " + i);

if (isPrime)
  System.out.println(number + " is prime");
else
  System.out.println(number + " is not prime");

} }

A. i is 3 followed by 9 is prime B. i is 3 followed by 9 is not prime C. i is 4 followed by 9 is prime D. i is 4 followed by 9 is not prime

4.33 Analyze the following code:

import java.util.Scanner;

public class Test { public static void main(String[] args) { int sum = 0; for (int i = 0; i < 100000; i++) { Scanner input = new Scanner(System.in); sum += input.nextInt(); } } }

A. The program does not compile because the Scanner input = new Scanner(System.in); statement is inside the loop. B. The program compiles, but does not run because the Scanner input = new Scanner(System.in); statement is inside the loop. C. The program compiles and runs, but it is not effient and unnecessary to execute the Scanner input = new Scanner(System.in); statement inside the loop. You should move the statement before the loop. D. The program compiles, but does not run because there is not prompting message for entering the input.

5.1 Suppose your method does not return any value, which of the following keywords can be used as a return type?

A. void B. int C. double D. public E. None of the above

5.2 The signature of a method consists of ____________.

A. method name B. method name and parameter list C. return type, method name, and parameter list D. parameter list

5.3 All Java applications must have a method __________.

A. public static Main(String[] args) B. public static Main(String args[]) C. public static void main(String[] args) D. public void main(String[] args) E. public static main(String[] args)

Sections 5.3 Calling a Method 5.4 Arguments to methods always appear within __________.

A. brackets B. parentheses C. curly braces D. quotation marks

5.5 Does the return statement in the following method cause compile errors?

public static void main(String[] args) { int max = 0; if (max != 0) System.out.println(max); else return; }

A. Yes B. No

5.6 Does the method call in the following method cause compile errors?

public static void main(String[] args) { Math.pow(2, 4); }

A. Yes B. No

5.7 Each time a method is invoked, the system stores parameters and local variables in an area of memory, known as _______, which stores elements in last-in first-out fashion.

A. a heap B. storage area C. a stack D. an array

Sections 5.4 void Method Example 5.8 Which of the following should be defined as a void method?

A. Write a method that prints integers from 1 to 100. B. Write a method that returns a random integer from 1 to 100. C. Write a method that checks whether current second is an integer from 1 to 100. D. Write a method that converts an uppercase letter to lowercase.

5.9 You should fill in the blank in the following code with ______________.

public class Test { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5);

System.out.print("The grade is ");
printGrade(59.5);

}

public static __________ printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } }

A. int B. double C. boolean D. char E. void

5.10 You should fill in the blank in the following code with ______________.

public class Test { public static void main(String[] args) { System.out.print("The grade is " + getGrade(78.5)); System.out.print("\nThe grade is " + getGrade(59.5)); }

public static _________ getGrade(double score) { if (score >= 90.0) return 'A'; else if (score >= 80.0) return 'B'; else if (score >= 70.0) return 'C'; else if (score >= 60.0) return 'D'; else return 'F'; } }

A. int B. double C. boolean D. char E. void

5.11 Consider the following incomplete code:

public class Test { public static void main(String[] args) { System.out.println(f(5)); }

public static int f(int number) { // Missing body } }

The missing method body should be ________.

A. return "number"; B. System.out.println(number); C. System.out.println("number"); D. return number;

Sections 5.5 Passing Parameters by Values 5.12 When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as _________.

A. method invocation B. pass by value C. pass by reference D. pass by name

5.13 Given the following method

static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } }

What will be displayed by the call nPrint('a', 4)?

A. aaaaa B. aaaa C. aaa D. invalid call

5.14 Given the following method

static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } }

What is k after invoking nPrint("A message", k)?

int k = 2; nPrint("A message", k);

A. 0 B. 1 C. 2 D. 3

Section 5.8 Overloading Methods 5.15 Analyze the following code:

public class Test { public static void main(String[] args) { System.out.println(xMethod(5, 500L)); }

public static int xMethod(int n, long l) { System.out.println("int, long"); return n; }

public static long xMethod(long n, long l) { System.out.println("long, long"); return n; } }

A. The program displays int, long followed by 5. B. The program displays long, long followed by 5. C. The program runs fine but displays things other than 5. D. The program does not compile because the compiler cannot distinguish which xmethod to invoke.

5.16 Analyze the following code:

class Test { public static void main(String[] args) { System.out.println(xmethod(5)); }

public static int xmethod(int n, long t) { System.out.println("int"); return n; }

public static long xmethod(long n) { System.out.println("long"); return n; } }

A. The program displays int followed by 5. B. The program displays long followed by 5. C. The program runs fine but displays things other than 5. D. The program does not compile because the compiler cannot distinguish which xmethod to invoke.

5.17 Analyze the following code.

public class Test { public static void main(String[] args) { System.out.println(max(1, 2)); }

public static double max(int num1, double num2) { System.out.println("max(int, double) is invoked");

if (num1 > num2)
  return num1;
else
  return num2;

}

public static double max(double num1, int num2) { System.out.println("max(double, int) is invoked");

if (num1 > num2)
  return num1;
else
  return num2;

} }

A. The program cannot compile because you cannot have the print statement in a non-void method. B. The program cannot compile because the compiler cannot determine which max method should be invoked. C. The program runs and prints 2 followed by "max(int, double)" is invoked. D. The program runs and prints 2 followed by "max(double, int)" is invoked. E. The program runs and prints "max(int, double) is invoked" followed by 2.

5.18 Analyze the following code.

public class Test { public static void main(String[] args) { System.out.println(m(2)); }

public static int m(int num) { return num; }

public static void m(int num) { System.out.println(num); } }

A. The program has a compile error because the two methods m have the same signature. B. The program has a compile error because the second m method is defined, but not invoked in the main method. C. The program runs and prints 2 once. D. The program runs and prints 2 twice.

Section 5.9 The Scope of Variables 5.19 A variable defined inside a method is referred to as __________.

A. a global variable B. a method variable C. a block variable D. a local variable

5.20 What is k after the following block executes? { int k = 2; nPrint("A message", k); } System.out.println(k);

A. 0 B. 1 C. 2 D. k is not defined outside the block. So, the program has a compile error

Section 5.10 The Math Class 5.21 The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated in the method and hidden from the client who invokes the method. This is known as __________.

A. information hiding B. encapsulation C. method hiding D. simplifying method

5.22 Which of the following is a possible output from invoking Math.random()?

A. 3.43 B. 0.5 C. 0.0 D. 1.0

5.23 What is Math.round(3.6)?

A. 3.0 B. 3 C. 4 D. 4.0

5.24 What is Math.rint(3.6)?

A. 3.0 B. 3 C. 4.0 D. 5.0

5.25 What is Math.rint(3.5)?

A. 3.0 B. 3 C. 4 D. 4.0 E. 5.0

5.26 What is Math.ceil(3.6)?

A. 3.0 B. 3 C. 4.0 D. 5.0

5.27 What is Math.floor(3.6)?

A. 3.0 B. 3 C. 4 D. 5.0

5.28 What is Math.sqrt(4.0)?

A. 2 B. 2.5 C. 1 D. 3.0 E. 2.0

5.29 What is Math.max(Math.min(3, 6), 2)?

A. 2 B. 3 C. 4 D. 2.0 E. 3.0

5.30 What is Math.sin(Math.PI / 2)?

A. 1 B. 0.5 C. 0.4 D. 1.5 E. 1.0

5.31 What is Math.sin(Math.PI / 6)?

A. 1 B. 0.5 C. 0.4 D. 1.5

5.32 What is Math.asin(0.5)?

A. 90 B. 30 C. Math.PI / 6 D. Math.PI / 2

Section 5.11 Case Study: Generating Random Characters 5.33 (int)(Math.random() * (65535 + 1)) returns a random number __________.

A. between 1 and 65536 B. between 1 and 65535 C. between 0 and 65535 D. between 0 and 65536

5.34 (int)('a' + Math.random() * ('z' - 'a' + 1)) returns a random number __________.

A. between 0 and (int)'z' B. between (int)'a' and (int)'z' C. between 'a' and 'z' D. between 'a' and 'y'

5.35 (char)('a' + Math.random() * ('z' - 'a' + 1)) returns a random character __________.

A. between 'a' and 'z' B. between 'a' and 'y' C. between 'b' and 'z' D. between 'b' and 'y'

5.36 Which of the following is the best for generating random integer 0 or 1?

A. (int)Math.random() B. (int)Math.random() + 1 C. (int)(Math.random() + 0.5) D. (int)(Math.random() + 0.2) E. (int)(Math.random() + 0.8)

Section 5.12 Method Abstraction and Stepwise Refinement 5.37 __________ is to implement one method in the structure chart at a time from the top to the bottom.

A. Bottom-up approach B. Top-down approach C. Bottom-up and top-down approach D. Stepwise refinement

5.38 __________ is a simple but incomplete version of a method. A. A stub B. A main method C. A non-main method D. A method developed using top-down approach

6.1 What is the representation of the third element in an array called a?

A. a[2] B. a(2) C. a[3] D. a(3)

6.2 If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is ________.

A. 3.4 B. 2.0 C. 3.5 D. 5.5 E. undefined

6.3 Which of the following is incorrect?

A. int[] a = new int[2]; B. int a[] = new int[2]; C. int[] a = new int(2); D. int a = new int[2]; E. int a() = new int[2];

6.4 If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, the highest index in array list is __________.

A. 0 B. 1 C. 2 D. 3 E. 4

6.5 How many elements are in array double[] list = new double[5]?

A. 4 B. 5 C. 6 D. 0

6.6 What is the correct term for numbers[99]?

A. index B. index variable C. indexed variable D. array variable E. array

6.7 Suppose int i = 5, which of the following can be used as an index for array double[] t = new double[100]?

A. i B. (int)(Math.random() * 100)) C. i + 10 D. i + 6.5 E. Math.random() * 100

6.8 Analyze the following code.

public class Test { public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } }

A. The program has a compile error because the size of the array wasn't specified when declaring the array. B. The program has a runtime error because the array elements are not initialized. C. The program runs fine and displays x[0] is 0. D. The program has a runtime error because the array element x[0] is not defined.

6.9 Which of the following statements is valid?

A. int i = new int(30); B. double d[] = new double[30]; C. int[] i = {3, 4, 3, 2}; D. char[] c = new char(); E. char[] c = new char[4]{'a', 'b', 'c', 'd'};

6.10 How can you initialize an array of two characters to 'a' and 'b'?

A. char[] charArray = new char[2]; charArray = {'a', 'b'}; B. char[2] charArray = {'a', 'b'}; C. char[] charArray = {'a', 'b'}; D. char[] charArray = new char[]{'a', 'b'};

6.11 What would be the result of attempting to compile and run the following code?

public class Test { public static void main(String[] args) { double[] x = new double[]{1, 2, 3}; System.out.println("Value is " + x[1]); } }

A. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by {1, 2, 3}. B. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by new double[3]{1, 2, 3}; C. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by new double[]{1.0, 2.0, 3.0}; D. The program compiles and runs fine and the output "Value is 1.0" is printed. E. The program compiles and runs fine and the output "Value is 2.0" is printed.

6.12 Assume int[] t = {1, 2, 3, 4}. What is t.length?

A. 0 B. 3 C. 4 D. 5

6.13 What is the output of the following code?

double[] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax);

A. 0 B. 1 C. 2 D. 3 E. 4

6.14 Analyze the following code:

public class Test { public static void main(String[] args) { int[] x = new int[5]; int i; for (i = 0; i < x.length; i++) x[i] = i; System.out.println(x[i]); } }

A. The program displays 0 1 2 3 4. B. The program displays 4. C. The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException. D. The program has a compile error because i is not defined in the last statement in the main method.

6.15 (for-each loop) Analyze the following code:

public class Test { public static void main(String[] args) { double[] x = {2.5, 3, 4}; for (double value: x) System.out.print(value + " "); } }

A. The program displays 2.5, 3, 4 B. The program displays 2.5 3 4 C. The program displays 2.5 3.0 4.0 D. The program displays 2.5, 3.0 4.0 E. The program has a syntax error because value is undefined.

6.16 What is the output of the following code?

 int[] myList = {1, 2, 3, 4, 5, 6};

 for (int i = myList.length - 2; i >= 0; i--) {
   myList[i + 1] = myList[i];
 }

 for (int e: myList)
   System.out.print(e + " ");

A. 1 2 3 4 5 6 B. 6 1 2 3 4 5 C. 6 2 3 4 5 1 D. 1 1 2 3 4 5 E. 2 3 4 5 6 1

6.17 (Tricky) What is output of the following code:

public class Test { public static void main(String[] args) { int[] x = {120, 200, 016}; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } }

A. 120 200 16 B. 120 200 14 C. 120 200 20 D. 016 is a compile error. It should be written as 16.

6.18 What is output of the following code:

public class Test { public static void main(String[] args) { int list[] = {1, 2, 3, 4, 5, 6};

for (int i = 1; i < list.length; i++)
  list[i] = list[i - 1];

for (int i = 0; i < list.length; i++)
  System.out.print(list[i] + " ");

} }

A. 1 2 3 4 5 6 B. 2 3 4 5 6 6 C. 2 3 4 5 6 1 D. 1 1 1 1 1 1

Section 6.5 Copying Arrays 6.19 What will be displayed by the following code?

class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2;

for (int i = 0; i < list2.length; i++)
  System.out.print(list2[i] + " ");

} }

A. 1 2 3 B. 1 1 1 C. 0 1 2 D. 0 1 3

6.20 What will be displayed by the following code?

class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2;

for (int i = 0; i < list1.length; i++)
  System.out.print(list1[i] + " ");

} }

A. 1 2 3 B. 1 1 1 C. 0 1 2 D. 0 1 3

6.21 Analyze the following code:

public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x;

x = new int[2];

for (int i = 0; i < y.length; i++)
  System.out.print(y[i] + " ");

} }

A. The program displays 1 2 3 4 B. The program displays 0 0 C. The program displays 0 0 3 4 D. The program displays 0 0 0 0

6.22 Analyze the following code:

public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x;

x = new int[2];

for (int i = 0; i < x.length; i++)
  System.out.print(x[i] + " ");

} }

A. The program displays 1 2 3 4 B. The program displays 0 0 C. The program displays 0 0 3 4 D. The program displays 0 0 0 0

6.23 Analyze the following code:

public class Test { public static void main(String[] args) { final int[] x = {1, 2, 3, 4}; int[] y = x;

x = new int[2];

for (int i = 0; i < y.length; i++)
  System.out.print(y[i] + " ");

} }

A. The program displays 1 2 3 4 B. The program displays 0 0 C. The program has a compile error on the statement x = new int[2], because x is final and cannot be changed. D. The elements in the array x cannot be changed, because x is final.

6.24 Analyze the following code.

int[] list = new int[5]; list = new int[6];

A. The code has compile errors because the variable list cannot be changed once it is assigned. B. The code has runtime errors because the variable list cannot be changed once it is assigned. C. The code can compile and run fine. The second line assigns a new array to list. D. The code has compile errors because you cannot assign a different size array to list.

6.25 Analyze the following code:

public class Test { public static void main(String[] args) { int[] a = new int[4]; a[1] = 1; a = new int[2]; System.out.println("a[1] is " + a[1]); } }

A. The program has a compile error because new int[2] is assigned to a. B. The program has a runtime error because a[1] is not initialized. C. The program displays a[1] is 0. D. The program displays a[1] is 1.

6.26 The __________ method copies the sourceArray to the targetArray.

A. System.copyArrays(sourceArray, 0, targetArray, 0, sourceArray.length); B. System.copyarrays(sourceArray, 0, targetArray, 0, sourceArray.length); C. System.arrayCopy(sourceArray, 0, targetArray, 0, sourceArray.length); D. System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Section 6.6 Passing Arrays to Methods 6.27 When you pass an array to a method, the method receives __________.

A. a copy of the array B. a copy of the first element C. the reference of the array D. the length of the array

6.28 Show the output of the following code:

public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; increase(x);

int[] y = {1, 2, 3, 4, 5};
increase(y[0]);

System.out.println(x[0] + " " + y[0]);

}

public static void increase(int[] x) { for (int i = 0; i < x.length; i++) x[i]++; }

public static void increase(int y) { y++; } }

A. 0 0 B. 1 1 C. 2 2 D. 2 1 E. 1 2

6.29 Do the following two programs produce the same result?

Program I: public class Test { public static void main(String[] args) { int[] list = {1, 2, 3, 4, 5}; reverse(list); for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); }

public static void reverse(int[] list) { int[] newList = new int[list.length];

for (int i = 0; i < list.length; i++)
  newList[i] = list[list.length - 1 - i];

list = newList;

} }

Program II: public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); }

public static void reverse(int[] list) { int[] newList = new int[list.length];

for (int i = 0; i < list.length; i++)
  newList[i] = list[list.length - 1 - i];

list = newList;

} }

A. Yes B. No

6.30 Analyze the following code:

public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); }

public static void reverse(int[] list) { int[] newList = new int[list.length];

for (int i = 0; i < list.length; i++)
  newList[i] = list[list.length - 1 - i];

list = newList;

} } A. The program displays 1 2 3 4 5. B. The program displays 1 2 3 4 5 and then raises an ArrayIndexOutOfBoundsException. C. The program displays 5 4 3 2 1. D. The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException.

6.31 Analyze the following code:

public class Test1 { public static void main(String[] args) { xMethod(new double[]{3, 3}); xMethod(new double[5]); xMethod(new double[3]{1, 2, 3}); }

public static void xMethod(double[] a) { System.out.println(a.length); } }

A. The program has a compile error because xMethod(new double[]{3, 3}) is incorrect. B. The program has a compile error because xMethod(new double[5]) is incorrect. C. The program has a compile error because xMethod(new double[3]{1, 2, 3}) is incorrect. D. The program has a runtime error because a is null.

6.32 The JVM stores the array in an area of memory, called _______, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

A. stack B. heap C. memory block D. dynamic memory

Section 6.7 Returning an Array from a Method 6.33 When you return an array from a method, the method returns __________.

A. a copy of the array B. a copy of the first element C. the reference of the array D. the length of the array

6.34 Suppose a method p has the following heading:

public static int[] p()

What return statement may be used in p()?

A. return 1; B. return {1, 2, 3}; C. return int[]{1, 2, 3}; D. return new int[]{1, 2, 3};

6.35 The reverse method is defined in the textbook. What is list1 after executing the following statements?

int[] list1 = {1, 2, 3, 4, 5, 6}; list1 = reverse(list1);

A. list1 is 1 2 3 4 5 6 B. list1 is 6 5 4 3 2 1 C. list1 is 0 0 0 0 0 0 D. list1 is 6 6 6 6 6 6

6.36 The reverse method is defined in this section. What is list1 after executing the following statements?

int[] list1 = {1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1);

A. list1 is 1 2 3 4 5 6 B. list1 is 6 5 4 3 2 1 C. list1 is 0 0 0 0 0 0 D. list1 is 6 6 6 6 6 6

Section 6.9 Variable-Length Argument Lists 6.37 Which of the following declarations are correct?

A. public static void print(String... strings, double... numbers) B. public static void print(double... numbers, String name) C. public static double... print(double d1, double d2) D. public static void print(double... numbers) E. public static void print(int n, double... numbers)

6.38 Which of the following statements are correct to invoke the printMax method in Listing 6.5 in the textbook?

A. printMax(1, 2, 2, 1, 4); B. printMax(new double[]{1, 2, 3}); C. printMax(1.0, 2.0, 2.0, 1.0, 4.0); D. printMax(new int[]{1, 2, 3});

Section 6.10 Searching Arrays 6.39 For the binarySearch method in Section 6.9.2, what is low and high after the first iteration of the while loop when invoking binarySearch(new int[]{1, 4, 6, 8, 10, 15, 20}, 11)?

A. low is 0 and high is 6 B. low is 0 and high is 3 C. low is 3 and high is 6 D. low is 4 and high is 6 E. low is 0 and high is 5

6.40 If a key is not in the list, the binarySearch method returns _________.

A. insertion point B. insertion point - 1 C. -(insertion point + 1) D. -insertion point

Section 6.11 Sorting Arrays 6.41 Use the selectionSort method presented in this section to answer this question. Assume list is {3.1, 3.1, 2.5, 6.4, 2.1}, what is the content of list after the first iteration of the outer loop in the method?

A. 3.1, 3.1, 2.5, 6.4, 2.1 B. 2.5, 3.1, 3.1, 6.4, 2.1 C. 2.1, 2.5, 3.1, 3.1, 6.4 D. 3.1, 3.1, 2.5, 2.1, 6.4 E. 2.1, 3.1, 2.5, 6.4, 3.1

6.42 Use the selectionSort method presented in this section to answer this question. What is list1 after executing the following statements?

double[] list1 = {3.1, 3.1, 2.5, 6.4}; selectionSort(list1);

A. list1 is 3.1, 3.1, 2.5, 6.4 B. list1 is 2.5 3.1, 3.1, 6.4 C. list1 is 6.4, 3.1, 3.1, 2.5 D. list1 is 3.1, 2.5, 3.1, 6.4

Section 6.12 The Arrays Class 6.43 The __________ method sorts the array scores of the double[] type.

A. java.util.Arrays(scores) B. java.util.Arrays.sorts(scores) C. java.util.Arrays.sort(scores) D. Njava.util.Arrays.sortArray(scores)

6.44 Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 30) return?

A. 0 B. -1 C. 1 D. 2 E. -2

6.45 Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 3) return?

A. 0 B. -1 C. 1 D. 2 E. -2

6.46 Assume int[] list1 = {3, 4, 1, 9, 13}, int[] list2 = {3, 4, 1, 9, 13}, and int[] list3 = {4, 3, 1, 9, 13}, what is

System.out.println(java.util.Arrays.equals(list1, list2)
  + " " + java.util.Arrays.equals(list1, list3));

A. true true B. true false C. false true D. false fasle

6.47 Assume int[] scores = {3, 4, 1, 9, 13}, which of the following statement displays all the element values in the array? A. System.out.println(scores); B. System.out.println(scores.toString()); C. System.out.println(java.util.Arrays.toString(scores)); D. System.out.println(scores[0]);

7.1 Which of the following statements are correct?

A. char[][] charArray = {'a', 'b'}; B. char[2][2] charArray = {{'a', 'b'}, {'c', 'd'}}; C. char[2][] charArray = {{'a', 'b'}, {'c', 'd'}}; D. char[][] charArray = {{'a', 'b'}, {'c', 'd'}};

7.2 Assume double[][] x = new double[4][5], what are x.length and x[2].length?

A. 4 and 4 B. 4 and 5 C. 5 and 4 D. 5 and 5

7.3 What is the index variable for the element at the first row and first column in array a?

A. a[0][0] B. a[1][1] C. a[0][1] D. a[1][0]

7.4 When you create an array using the following statement, the element values are automatically initialized to 0.

int[][] matrix = new int[5][5];

A. True B. False

7.5 How many elements are array matrix (int[][] matrix = new int[5][5])?

A. 14 B. 20 C. 25 D. 30

7.6 Analyze the following code:

public class Test { public static void main(String[] args) { boolean[][] x = new boolean[3][]; x[0] = new boolean[1]; x[1] = new boolean[2]; x[2] = new boolean[3];

System.out.println("x[2][2] is " + x[2][2]);

} }

A. The program has a compile error because new boolean[3][] is wrong. B. The program has a runtime error because x[2][2] is null. C. The program runs and displays x[2][2] is null. D. The program runs and displays x[2][2] is true. E. The program runs and displays x[2][2] is false.

7.7 Assume int[][] x = {{1, 2}, {3, 4}, {5, 6}}, what are x.length are x[0].length?

A. 2 and 1 B. 2 and 2 C. 3 and 2 D. 2 and 3 E. 3 and 3

7.8 Assume int[][] x = {{1, 2}, {3, 4, 5}, {5, 6, 5, 9}}, what are x[0].length, x[1].length, and x[2].length?

A. 2, 3, and 3 B. 2, 3, and 4 C. 3, 3, and 3 D. 3, 3, and 4 E. 2, 2, and 2

Section 7.3 Processing Two-Dimensional Arrays 7.9 What will be displayed by the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};

int v = values[0][0];
for (int row = 0; row < values.length; row++)
  for (int column = 0; column < values[row].length; column++)
    if (v < values[row][column])
      v = values[row][column];

System.out.print(v);

} }

A. 1 B. 3 C. 5 D. 6 E. 33

7.10 What will be displayed by the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};

int v = values[0][0];
for (int[] list : values)
  for (int element : list)
    if (v > element)
      v = element;

System.out.print(v);

} }

A. 1 B. 3 C. 5 D. 6 E. 33

7.11 What will be displayed by the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1 }, {33, 6, 1, 2}};

for (int row = 0; row < values.length; row++) {
  java.util.Arrays.sort(values[row]);
  for (int column = 0; column < values[row].length; column++)
    System.out.print(values[row][column] + " ");
  System.out.println();
}

} }

A. The program prints two rows 3 4 5 1 followed by 33 6 1 2 B. The program prints on row 3 4 5 1 33 6 1 2 C. The program prints two rows 3 4 5 1 followed by 33 6 1 2 D. The program prints two rows 1 3 4 5 followed by 1 2 6 33 E. The program prints one row 1 3 4 5 1 2 6 33

7.12 What is the output of the following code?

public class Test { public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}};

for (int i = 0; i < 4; i++)
  System.out.print(matrix[i][1] + " ");

} }

A. 1 2 3 4 B. 4 5 6 7 C. 1 3 8 12 D. 2 5 9 13 E. 3 6 10 14

7.13 What is the output of the following code? public class Test5 { public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}};

for (int i = 0; i < 4; i++)
  System.out.print(matrix[1][i] + " ");

} }

A. 1 2 3 4 B. 4 5 6 7 C. 1 3 8 12 D. 2 5 9 13 E. 3 6 10 14

Section 7.4 Passing Two-Dimensional Arrays to Methods 7.14 Suppose a method p has the following heading:

public static int[][] p()

What return statement may be used in p()?

A. return 1; B. return {1, 2, 3}; C. return int[]{1, 2, 3}; D. return new int[]{1, 2, 3}; E. return new int[][]{{1, 2, 3}, {2, 4, 5}};

7.15 What will be displayed by the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};

for (int row = 0; row < values.length; row++) {
  System.out.print(m(values[row]) + " ");
}

}

public static int m(int[] list) { int v = list[0]; for (int i = 1; i < list.length; i++) if (v < list[i]) v = list[i]; return v; } }

A. 3 33 B. 1 1 C. 5 6 D. 5 33 E. 33 5

Section 7.8 Multidimensional Arrays 7.16 Assume double[][][] x = new double[4][5][6], what are x.length, x[2].length, and x[0][0].length?

A. 4, 5, and 6 B. 6, 5, and 4 C. 5, 5, and 5 D. 4, 5, and 4

7.17 Which of the following statements are correct?

A. char[][][] charArray = new char[2][2][]; B. char[2][2][] charArray = {'a', 'b'}; C. char[][][] charArray = {{'a', 'b'}, {'c', 'd'}, {'e', 'f'}}; D. char[][][] charArray = {{{'a', 'b'}, {'c', 'd'}, {'e', 'f'}}};

7.18 What will be displayed by the following code? public class Test { public static void main(String[] args) { int[][][] data = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

System.out.print(data[1][0][0]);

} }

A. 1 B. 2 C. 4 D. 5 E. 6

7.19 What will be displayed by the following code? public class Test { public static void main(String[] args) { int[][][] data = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

System.out.print(ttt(data[0]));

}

public static int ttt(int[][] m) { int v = m[0][0];

for (int i = 0; i < m.length; i++)
  for (int j = 0; j < m[i].length; j++)
    if (v < m[i][j])
      v = m[i][j];

return v;

} } A. 1 B. 2 C. 4 D. 5 E. 6

8.1 __________ represents an entity in the real world that can be distinctly identified.

A. A class B. An object C. A method D. A data field

8.2 _______ is a construct that defines objects of the same type.

A. A class B. An object C. A method D. A data field

8.3 An object is an instance of a __________.

A. program B. class C. method D. data

8.4 The keyword __________ is required to declare a class.

A. public B. private C. class D. All of the above.

Section 8.4 Constructing Objects Using Constructors 8.5 ________ is invoked to create an object.

A. A constructor B. The main method C. A method with a return type D. A method with the void return type

8.6 Which of the following statements are true?

A. A default constructor is provided automatically if no constructors are explicitly declared in the class. B. At least one constructor must always be defined explicitly. C. Every class has a default constructor. D. The default constructor is a no-arg constructor.

8.7 Which of the following statements are true?

A. Multiple constructors can be defined in a class. B. Constructors do not have a return type, not even void. C. Constructors must have the same name as the class itself. D. Constructors are invoked using the new operator when an object is created.

8.8 Analyze the following code:

public class Test { public static void main(String[] args) { A a = new A(); a.print(); } }

class A { String s;

A(String newS) { s = newS; }

void print() { System.out.println(s); } }

A. The program has a compilation error because class A is not a public class. B. The program has a compilation error because class A does not have a no-arg constructor. C. The program compiles and runs fine and prints nothing. D. The program would compile and run if you change A a = new A() to A a = new A("5").

8.9 What is wrong in the following code?

class TempClass { int i; public void TempClass(int j) { int i = j; } }

public class C { public static void main(String[] args) { TempClass temp = new TempClass(2); } }

A. The program has a compilation error because TempClass does not have a default constructor. B. The program has a compilation error because TempClass does not have a constructor with an int argument. C. The program compiles fine, but it does not run because class C is not public. D. The program compiles and runs fine.

Section 8.5 Accessing Objects via Reference Variables 8.10 Given the declaration Circle x = new Circle(), which of the following statement is most accurate.

A. x contains an int value. B. x contains an object of the Circle type. C. x contains a reference to a Circle object. D. You can assign an int value to x.

8.11 Analyze the following code.

public class Test { int x;

public Test(String t) { System.out.println("Test"); }

public static void main(String[] args) { Test test = null; System.out.println(test.x); } }

A. The program has a compile error because test is not initialized. B. The program has a compile error because x has not been initialized. C. The program has a compile error because you cannot create an object from the class that defines the object. D. The program has a compile error because Test does not have a default constructor. E. The program has a runtime NullPointerException because test is null while executing test.x.

8.12 The default value for data field of a boolean type, numeric type, object type is ___________, respectively.

A. true, 1, Null B. false, 0, null C. true, 0, null D. true, 1, null E. false, 1, null

8.13 Which of the following statements are true?

A. Local variables do not have default values. B. Data fields have default values. C. A variable of a primitive type holds a value of the primitive type. D. A variable of a reference type holds a reference to where an object is stored in the memory. E. You may assign an int value to a reference variable.

8.14 Analyze the following code:

public class Test { public static void main(String[] args) { double radius; final double PI= 3.15169; double area = radius * radius * PI; System.out.println("Area is " + area); } }

A. The program has compile errors because the variable radius is not initialized. B. The program has a compile error because a constant PI is defined inside a method. C. The program has no compile errors but will get a runtime error because radius is not initialized. D. The program compiles and runs fine.

8.15 Analyze the following code.

public class Test { int x;

public Test(String t) { System.out.println("Test"); }

public static void main(String[] args) { Test test = new Test(); System.out.println(test.x); } }

A. The program has a compile error because System.out.println method cannot be invoked from the constructor. B. The program has a compile error because x has not been initialized. C. The program has a compile error because you cannot create an object from the class that defines the object. D. The program has a compile error because Test does not have a default constructor.

8.16 Suppose TestCircle1 and Circle1 in Listing 8.1 are in two separate files named TestCircle1.java and Circle1.java, respectively. What is the outcome of compiling TestCircle.java and then Circle.java?

A. Only TestCircle1.java compiles. B. Only Circle1.java compiles. C. Both compile fine. D. Neither compiles successfully.

8.17 Which of the following statement is most accurate?

A. A reference variable is an object. B. A reference variable refers to an object. C. An object may contain other objects. D. An object may contain the references of other objects.

Section 8.6 Using Classes From the Java Library 8.18 The java.util.Date class is introduced in this section. Analyze the following code and choose the best answer:

Which of the following code in A or B, or both creates an object of the Date class:

A: public class Test { public Test() { new java.util.Date(); } }

B: public class Test { public Test() { java.util.Date date = new java.util.Date(); } }

A. A. B. B. C. Neither

8.19 Which of the following statements are correct?

A. When creating a Random object, you have to specify the seed or use the default seed. B. If two Random objects have the same seed, the sequence of the random numbers obtained from these two objects are identical. C. The nextInt() method in the Random class returns the next random int value. D. The nextDouble() method in the Random class returns the next random double value.

8.20 How many JFrame objects can you create and how many can you display?

A. one B. two C. three D. unlimited

Section 8.7 Static Variables, Constants, and Methods 8.21 Variables that are shared by every instances of a class are __________.

A. public variables B. private variables C. instance variables D. class variables

8.22 You should add the static keyword in the place of ? in Line ________ in the following code:

1 public class Test { 2 private int age; 3 4 public ? int square(int n) { 5 return n * n; 6 } 7 8 public ? int getAge() { 9 } 10}

A. in line 4 B. in line 8 C. in both line 4 and line 8 D. none

8.23 A method that is associated with an individual object is called __________.

A. a static method B. a class method C. an instance method D. an object method

8.24 To declare a constant MAX_LENGTH as a member of the class, you write

A. final static MAX_LENGTH = 99.98; B. final static float MAX_LENGTH = 99.98; C. static double MAX_LENGTH = 99.98; D. final double MAX_LENGTH = 99.98; E. final static double MAX_LENGTH = 99.98;

8.25 Analyze the following code.

public class Test { public static void main(String[] args) { int n = 2; xMethod(n);

System.out.println("n is " + n);

}

void xMethod(int n) { n++; } }

A. The code has a compile error because xMethod does not return a value. B. The code has a compile error because xMethod is not declared static. C. The code prints n is 1. D. The code prints n is 2. E. The code prints n is 3.

8.26 What will be displayed by the second println statement in the main method? public class Foo { int i; static int s;

public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); }

public Foo() { i++; s++; } }

A. f2.i is 1 f2.s is 1 B. f2.i is 1 f2.s is 2 C. f2.i is 2 f2.s is 2 D. f2.i is 2 f2.s is 1

8.27 What will be displayed by the third println statement in the main method? public class Foo { int i; static int s;

public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); }

public Foo() { i++; s++; } }

A. f3.i is 1 f3.s is 1 B. f3.i is 1 f3.s is 2 C. f3.i is 1 f3.s is 3 D. f3.i is 3 f3.s is 1 E. f3.i is 3 f3.s is 3

8.28 What code may be filled in the blank without causing syntax or runtime errors:

public class Test { java.util.Date date;

public static void main(String[] args) { Test test = new Test(); System.out.println(_________________); } }

A. test.date B. date C. test.date.toString() D. date.toString()

8.29 Suppose the xMethod() is invoked in the following constructor in a class, xMethod() is _________ in the class.

public MyClass() { xMethod(); }

A. a static method B. an instance method C. a static method or an instance method

8.30 Suppose the xMethod() is invoked from a main method in a class as follows, xMethod() is _________ in the class.

public static void main(String[] args) { xMethod(); }

A. a static method B. an instance method C. a static method or an instance method

Section 8.8 Visibility Modifiers 8.31 To prevent a class from being instantiated, _____________________

A. don't use any modifiers on the constructor. B. use the public modifier on the constructor. C. use the private modifier on the constructor. D. use the static modifier on the constructor.

8.32 Analyze the following code:

public class Test { public static void main(String args[]) { NClass nc = new NClass(); nc.t = nc.t++; } }

class NClass { int t; private NClass() { } }

A. The program has a compilation error because the NClass class has a private constructor. B. The program does not compile because the parameter list of the main method is wrong. C. The program compiles, but has a runtime error because t has no initial value. D. The program compiles and runs fine.

8.33 Analyze the following code:

public class Test { private int t;

public static void main(String[] args) { int x; System.out.println(t); } }

A. The variable t is not initialized and therefore causes errors. B. The variable t is private and therefore cannot be accessed in the main method. C. t is non-static and it cannot be referenced in a static context in the main method. D. The variable x is not initialized and therefore causes errors. E. The program compiles and runs fine.

8.34 Analyze the following code and choose the best answer:

public class Foo { private int x;

public static void main(String[] args) { Foo foo = new Foo(); System.out.println(foo.x); } }

A. Since x is private, it cannot be accessed from an object foo. B. Since x is defined in the class Foo, it can be accessed by any method inside the class without using an object. You can write the code to access x without creating an object such as foo in this code. C. Since x is an instance variable, it cannot be directly used inside a main method. However, it can be accessed through an object such as foo in this code. D. You cannot create a self-referenced object; that is, foo is created inside the class Foo.

Section 8.9 Data Field Encapsulation 8.35 Which of the following statements are true?

A. Use the private modifier to encapsulate data fields. B. Encapsulating data fields makes the program easy to maintain. C. Encapsulating data fields makes the program short. D. Encapsulating data fields helps prevent programming errors.

8.36 Suppose you wish to provide an accessor method for a boolean property finished, what signature of the method should be?

A. public void getFinished() B. public boolean getFinished() C. public boolean isFinished() D. public void isFinished()

8.37 Which is the advantage of encapsulation?

A. Only public methods are needed. B. Making the class final causes no consequential changes to other code. C. It changes the implementation without changing a class's contract and causes no consequential changes to other code. D. It changes a class's contract without changing the implementation and causes no consequential changes to other code.

Section 8.10 Passing Objects to Methods 8.38 When invoking a method with an object argument, ___________ is passed.

A. the contents of the object B. a copy of the object C. the reference of the object D. the object is copied, then the reference of the copied object

8.39 What is the value of myCount.count displayed? public class Test { public static void main(String[] args) { Count myCount = new Count(); int times = 0;

for (int i=0; i<100; i++)
  increment(myCount, times);

System.out.println(
  "myCount.count = " + myCount.count);
System.out.println("times = "+ times);

}

public static void increment(Count c, int times) { c.count++; times++; } }

class Count { int count;

Count(int c) { count = c; }

Count() { count = 1; } }

A. 101 B. 100 C. 99 D. 98

8.40 What is the value of times displayed? public class Test { public static void main(String[] args) { Count myCount = new Count(); int times = 0;

for (int i=0; i<100; i++)
  increment(myCount, times);

System.out.println(
  "myCount.count = " + myCount.count);
System.out.println("times = "+ times);

}

public static void increment(Count c, int times) { c.count++; times++; } }

class Count { int count;

Count(int c) { count = c; }

Count() { count = 1; } }

A. 101 B. 100 C. 99 D. 98 E. 0

8.41 What is the output of the following program?

import java.util.Date;

public class Test { public static void main(String[] args) { Date date = new Date(1234567); m1(date); System.out.print(date.getTime() + " ");

m2(date);
System.out.println(date.getTime());

}

public static void m1(Date date) { date = new Date(7654321); }

public static void m2(Date date) { date.setTime(7654321); } }

A. 1234567 1234567 B. 1234567 7654321 C. 7654321 1234567 D. 7654321 7654321

Section 8.11 Array of Objects 8.42 Given the declaration Circle[] x = new Circle[10], which of the following statement is most accurate?

A. x contains an array of ten int values. B. x contains an array of ten objects of the Circle type. C. x contains a reference to an array and each element in the array can hold a reference to a Circle object. D. x contains a reference to an array and each element in the array can hold a Circle object.

8.43 Assume java.util.Date[] dates = new java.util.Date[10], which of the following statements are true? A. dates is null. B. dates[0] is null. C. dates = new java.util.Date[5] is fine, which assigns a new array to dates. D. dates = new Date() is fine, which creates a new Date object and assigns to dates.

9.1 Suppose s is a string with the value "java". What will be assigned to x if you execute the following code?

char x = s.charAt(4);

A. 'a' B. 'v' C. Nothing will be assigned to x, because the execution causes the runtime error StringIndexOutofBoundsException.

9.2 Which of the following statements is preferred to create a string "Welcome to Java"?

A. String s = "Welcome to Java"; B. String s = new String("Welcome to Java"); C. String s; s = "Welcome to Java"; D. String s; s = new String("Welcome to Java");

9.3 What is the output of the following code?

public class Test {
public static void main(String[] args) { String s1 = "Welcome to Java!"; String s2 = s1;

if (s1 == s2)
  System.out.println("s1 and s2 reference to the same String object");
else
  System.out.println("s1 and s2 reference to different String objects");

} }

A. s1 and s2 reference to the same String object B. s1 and s2 reference to different String objects

9.4 What is the output of the following code?

public class Test {
public static void main(String[] args) { String s1 = "Welcome to Java!"; String s2 = "Welcome to Java!";

if (s1 == s2)
  System.out.println("s1 and s2 reference to the same String object");
else
  System.out.println("s1 and s2 reference to different String objects");

} }

A. s1 and s2 reference to the same String object B. s1 and s2 reference to different String objects

9.5 What is the output of the following code?

public class Test {
public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = new String("Welcome to Java!");

if (s1 == s2)
  System.out.println("s1 and s2 reference to the same String object");
else
  System.out.println("s1 and s2 reference to different String objects");

} }

A. s1 and s2 reference to the same String object B. s1 and s2 reference to different String objects

9.6 Suppose s1 and s2 are two strings. What is the result of the following code?

s1.equals(s2) == s2.equals(s1)

A. true B. false

9.7 What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = new String("Welcome to Java!");

if (s1.equals(s2))
  System.out.println("s1 and s2 have the same contents");
else
  System.out.println("s1 and s2 have different contents");

} }

A. s1 and s2 have the same contents B. s1 and s2 have different contents

9.8 What is the output of the following code?

public class Test {
public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = s1.toUpperCase();

if (s1 == s2)
  System.out.println("s1 and s2 reference to the same String object");
else if (s1.equals(s2))
  System.out.println("s1 and s2 have the same contents");
else
  System.out.println("s1 and s2 have different contents");

} }

A. s1 and s2 reference to the same String object B. s1 and s2 have the same contents C. s1 and s2 have different contents

9.9 What is the output of the following code?

public class Test {
public static void main(String[] args) { String s1 = new String("Welcome to Java"); String s2 = s1;

s1 += "and Welcome to HTML";

if (s1 == s2)
  System.out.println("s1 and s2 reference to the same String object");
else
  System.out.println("s1 and s2 reference to different String objects");

} }

A. s1 and s2 reference to the same String object B. s1 and s2 reference to different String objects

9.10 Suppose s1 and s2 are two strings. Which of the following statements or expressions are incorrect?

A. String s = new String("new string"); B. String s3 = s1 + s2 C. s1 >= s2 D. int i = s1.length E. s1.charAt(0) = '5'

9.11 Suppose s1 and s2 are two strings. Which of the following statements or expressions is incorrect?

A. String s3 = s1 - s2; B. boolean b = s1.compareTo(s2); C. char c = s1[0]; D. char c = s1.charAt(s1.length());

9.12 "abc".compareTo("aba") returns ___________.

A. 1 B. 2 C. -1 D. -2 E. 0

9.13 "AbA".compareToIgnoreCase("abC") returns ___________.

A. 1 B. 2 C. -1 D. -2 E. 0

9.14 ____________________ returns true.

A. "peter".compareToIgnoreCase("Peter") B. "peter".compareToIgnoreCase("peter") C. "peter".equalsIgnoreCase("Peter") D. "peter".equalsIgnoreCase("peter") E. "peter".equals("peter")

9.15 What is the output of the following code?

String s = "University"; s.replace("i", "ABC"); System.out.println(s);

A. UnABCversity B. UnABCversABCty C. UniversABCty D. University

9.16 What is the return value of "SELECT".substring(0, 5)?

A. "SELECT" B. "SELEC" C. "SELE" D. "ELECT"

9.17 What is the return value of "SELECT".substring(4, 4)?

A. an empty string B. C C. T D. E

9.18 Analyze the following code.

class Test {
public static void main(String[] args) { String s; System.out.println("s is " + s); } }

A. The program has a compilation error because s is not initialized, but it is referenced in the println statement. B. The program has a runtime error because s is not initialized, but it is referenced in the println statement. C. The program has a runtime error because s is null in the println statement. D. The program compiles and runs fine.

9.19 To check if a string s contains the prefix "Java", you may write

A. if (s.startsWith("Java")) ... B. if (s.indexOf("Java") == 0) ... C. if (s.substring(0, 4).equals("Java")) ... D. if (s.charAt(0) == 'J' && s.charAt(1) == 'a' && s.charAt(2) == 'v' && s.charAt(3) == 'a') ...

9.20 To check if a string s contains the suffix "Java", you may write

A. if (s.endsWith("Java")) ... B. if (s.lastIndexOf("Java") >= 0) ... C. if (s.substring(s.length() - 4).equals("Java")) ... D. if (s.substring(s.length() - 5).equals("Java")) ... E. if (s.charAt(s.length() - 4) == 'J' && s.charAt(s.length() - 3) == 'a' && s.charAt(s.length() - 2) == 'v' && s.charAt(s.length() - 1) == 'a') ...

9.21 Which of the following is the correct statement to return JAVA?

A. toUpperCase("Java") B. "Java".toUpperCase("Java") C. "Java".toUpperCase() D. String.toUpperCase("Java")

9.22 Which of the following is the correct statement to return a string from an array a of characters?

A. toString(a) B. new String(a) C. convertToString(a) D. String.toString(a)

9.23 Assume s is " abc ", the method __________ returns a new string "abc".

A. s.trim(s) B. trim(s) C. String.trim(s) D. s.trim()

9.24 Assume s is "ABCABC", the method __________ returns a new string "aBCaBC".

A. s.toLowerCase(s) B. s.toLowerCase() C. s.replace('A', 'a') D. s.replace('a', 'A') E. s.replace("ABCABC", "aBCaBC")

9.25 Assume s is "ABCABC", the method __________ returns an array of characters.

A. toChars(s) B. s.toCharArray() C. String.toChars() D. String.toCharArray() E. s.toChars()

9.26 __________ returns a string.

A. String.valueOf(123) B. String.valueOf(12.53) C. String.valueOf(false) D. String.valueOf(new char[]{'a', 'b', 'c'})

9.27 The following program displays __________.

public class Test {
public static void main(String[] args) { String s = "Java"; StringBuilder buffer = new StringBuilder(s); change(s); System.out.println(s); }

private static void change(String s) { s = s + " and HTML"; } }

A. Java B. Java and HTML C. and HTML D. nothing is displayed

9.28 What is displayed by the following statement? System.out.println("Java is neat".replaceAll("is", "AAA"));

A. JavaAAAneat B. JavaAAA neat C. Java AAA neat D. Java AAAneat

9.29 What is displayed by the following code? public static void main(String[] args) { String[] tokens = "Welcome to Java".split("o"); for (int i = 0; i < tokens.length; i++) { System.out.print(tokens[i] + " "); } }

A. Welcome to Java B. Welc me to Java C. Welc me t Java D. Welcome t Java

9.30 What is displayed by the following code? System.out.print("Hi, ABC, good".matches("ABC ") + " "); System.out.println("Hi, ABC, good".matches(".ABC."));

A. false fasle B. true fasle C. true true D. false true

9.31 What is displayed by the following code? System.out.print("A,B;C".replaceAll(",;", "#") + " "); System.out.println("A,B;C".replaceAll("[,;]", "#"));

A. A B C A#B#C B. A#B#C A#B#C C. A,B;C A#B#C D. A B C A B C

9.32 What is displayed by the following code?

String[] tokens = "A,B;C;D".split("[,;]");
for (int i = 0; i < tokens.length; i++)
  System.out.print(tokens[i] + " ");

A. A,B;C;D B. A B C D C. A B C;D D. A B;C;D

Section 9.5 The Character Class 9.33 Which of following is not a correct method in Character?

A. isLetterOrDigit(char) B. isLetter(char) C. isDigit() D. toLowerCase(char) E. toUpperCase()

9.34 Suppose Character x = new Character('a'), __________________ returns true.

A. x.equals(new Character('a')) B. x.compareToIgnoreCase('A') C. x.equalsIgnoreCase('A') D. x.equals('a') E. x.equals("a")

Section 9.6 The StringBuilder/StringBuffer Class 9.35 Analyze the following code.

class Test {
public static void main(String[] args) { StringBuilder strBuf = new StringBuilder(4); strBuf.append("ABCDE"); System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(5)); } }

A. The program has a compilation error because you cannot specify initial capacity in the StringBuilder constructor. B. The program has a runtime error because because the buffer's capacity is 4, but five characters "ABCDE" are appended into the buffer. C. The program has a runtime error because the length of the string in the buffer is 5 after "ABCDE" is appended into the buffer. Therefore, strBuf.charAt(5) is out of range. D. The program compiles and runs fine.

9.36 Which of the following is true?

A. You can add characters into a string buffer. B. You can delete characters into a string buffer. C. You can reverse the characters in a string buffer. D. The capacity of a string buffer can be automatically adjusted.

9.37 _________ returns the last character in a StringBuilder variable named strBuf?

A. strBuf.charAt(strBuf.length() - 1) B. strBuf.charAt(strBuf.capacity() - 1) C. StringBuilder.charAt(strBuf.length() - 1) D. StringBuilder.charAt(strBuf.capacity() - 1)

9.38 Assume StringBuilder strBuf is "ABCDEFG", after invoking _________, strBuf contains "AEFG".

A. strBuf.delete(0, 3) B. strBuf.delete(1, 3) C. strBuf.delete(1, 4) D. strBuf.delete(2, 4)

9.39 Assume StringBuilder strBuf is "ABCDEFG", after invoking _________, strBuf contains "ABCRRRRDEFG".

A. strBuf.insert(1, "RRRR") B. strBuf.insert(2, "RRRR") C. strBuf.insert(3, "RRRR") D. strBuf.insert(4, "RRRR")

9.40 Assume StringBuilder strBuf is "ABCCEFC", after invoking _________, strBuf contains "ABTTEFT".

A. strBuf.replace('C', 'T') B. strBuf.replace("C", "T") C. strBuf.replace("CC", "TT") D. strBuf.replace('C', "TT") E. strBuf.replace(2, 7, "TTEFT")

9.41 The StringBuilder methods _____________ not only change the contents of a string buffer, but also returns a reference to the string buffer.

A. delete B. append C. insert D. reverse E. replace

9.42 The following program displays __________.

public class Test {
public static void main(String[] args) { String s = "Java"; StringBuilder buffer = new StringBuilder(s); change(buffer); System.out.println(buffer); }

private static void change(StringBuilder buffer) { buffer.append(" and HTML"); } }

A. Java B. Java and HTML C. and HTML D. nothing is displayed

Section 9.7 Command-Line Arguments 9.43 How can you get the word "abc" in the main method from the following call?

java Test "+" 3 "abc" 2

A. args[0] B. args[1] C. args[2] D. args[3]

9.44 Given the following program:

public class Test { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.print(args[i] + " "); } } }

What is the output, if you run the program using

java Test 1 2 3

A. 3 B. 1 C. 1 2 3 D. 1 2

9.45 Which code fragment would correctly identify the number of arguments passed via the command line to a Java application, excluding the name of the class that is being invoked?

A. int count = args.length; B. int count = args.length - 1; C. int count = 0; while (args[count] != null) count ++; D. int count=0; while (!(args[count].equals(""))) count ++;

9.46 Which correctly creates an array of five empty Strings?

A. String[] a = new String [5]; B. String[] a = {"", "", "", "", ""}; C. String[5] a; D. String[ ] a = new String [5]; for (int i = 0; i < 5; a[i++] = null);

9.47 Identify the problems in the following code.

public class Test { public static void main(String argv[]) { System.out.println("argv.length is " + argv.length); } }

A. The program has a compile error because String argv[] is wrong and it should be replaced by String[] args. B. The program has a compile error because String args[] is wrong and it should be replaced by String args[]. C. If you run this program without passing any arguments, the program would have a runtime error because argv is null. D. If you run this program without passing any arguments, the program would display argv.length is 0.

9.48 Which of the following is the correct header of the main method? A. public static void main(String[] args) B. public static void main(String args[]) C. public static void main(String[] x) D. public static void main(String x[]) E. static void main(String[] args)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment