Cs3230

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What does the follow code print? public class Junk { private static int x; private static int y; private static int z; static { x = 100; y = 10; z = x / y; } public Junk() { System.out.println(z); } public Junk(int x) { this(); System.out.println(x); } static { x = z; y = 2 * z; z *= 5; } public static void main(String[] args) { new Junk(5); } static { x *= 2; y++; z = x * y; } }

420 5

Assuming that args is the name of the formal argument for the main method in a Java class named Foo and that the resulting program is executed from the command line as C:\>java Foo see the quick red fox What is the value of args.length?

5

A Java program contains the following code fragments, which compiles and runs: public int square(int s) { s = s * s; return s; } What does the following code print out? int length = 5; int area = square(length); System.out.println(length + " " + area);

5 25

What does the following code fragment print? StringTokenizer st = new StringTokenizer("AxByCzD","xyz"); while (st.hasMoreTokens()) System.out.print(st.nextToken() + " ");

A B C D

What does the following code fragment print? String[] output = "AxByCzD".split("[xyz]"); for (String s : output) System.out.print(s + " ");

A B C D

A StringTokenizer class can solve a couple of problems that the String split method cannot. For example, the StrngTokenizer provides an overloaded method, nextToken(String delim) that allows a programmer to dynamically change the delimiters during the parsing process, which the String split method cannot do. Briefly describe the other problem that the StringTokenizer class can solve but that the String split method cannot. (Hint: focus on the three-argument StringTokenizer constructor.)

A stringtokenizer is able to return the delimiter characters if we set returnDelims to true, while the string split method cannot return the delimiters.

What does the following code fragment print? StringTokenizer st = new StringTokenizer("AxByCzD", "xyz", true); while (st.hasMoreTokens()) System.out.print(st.nextToken() + " ");

A x B y C z D

What gets printed out by the Java code listed below the classes (i.e., below the line; note that the line numbers are not part of the code)? class Alpha { public String whoAreYou() { return "Alpha";} } class Beta extends Alpha { public String whoAreYou() { return "Beta";} } class Gamma extends Beta { public String whoAreYou() { return "Gamma";} } -------------------------------------------------- 1. Alpha a = new Beta(); 2. Beta b = new Gamma(); 3. Alpha c = new Gamma(); 4. System.out.println(a.whoAreYou()); 5. System.out.println(b.whoAreYou()); 6. System.out.println(c.whoAreYou());

Beta, Gamma, Gamma

Based on established Java style, what kind of element is JungleJim?

Class

A programmer wishes to use the binarySeach method to search for specific objects contained in a LinkedList. Which method should the programmer use?

Collections.binarySearch

A programmer wishes to sort an array of objects. The objects are instances of a class that defines several instance fields. Different situations may require ordering the array by different fields (i.e., the program may require several sort orders). Which ordering technique should the programmer use?

Comparator interface

What happens with the following code fragment (assume all necessary constructors and note that the line numbers are not part of the code)? 1. public class Foo 2. { 3. private int part1; 4. private int part2; 5. 6. public Foo(int part1, int part2) 7. { 8. this.part1 = part1; 9. this.part2 = part2; 10. } 11. 12. public Foo bar(Foo f) 13. { 14. return new Foo(part1 * f.part1, part2 * f.part2); 15. } 16.} ----------------------------------------------- 17. Foo f1 = new Foo(2, 3); 18. Foo f2 = new Foo(3, 4); 19. f1.bar(f2);

Compiles and runs without error

For which situation are exceptions best used?

Dealing with errors at a point in the program other than where they are detected

A program contains the following definitions and statements: public class Employee { private String name; public Employee(String name) { this.name = name; } public String toString() { return name; } public static void change(Employee temp) { temp = new Employee("Wally"); } } ----------------------------------- Employee e = new Employee("Dilbert"); Employee.change(e); System.out.println(e); What is printed?

Dilbert

Which of the following is NOT a defining feature of the object-oriented model?

Early binding

(6 pts) The following fragment of code is from a Java program that successfully compiles. String name = JOptionPane.showInputDialog(null, "Please enter your name", "Data Input", JOptionPane.QUESTION_MESSAGE); int count = name.length(); Briefly describe the potential problem that might arise when this code executes (assume that the program is not run in a headless environment).

If nothing is entered into the text box, or we cancel it, we can get a null pointer exception.

Upon which class relationship does object casting rely?

Inheritance

A Java program contains the expression data.length data is an

array

Which audience do Java assertions generally target?

Software developers

Which class relationship(s) is/are bidirectional? (Mark all that apply.)

association

Examine the following code fragment: logger.setLevel(Level.INFO); . . . logger.config("Error accessing the widget"); If logger is an instance of Logger and is fully initialized and configured, will the "widget" message be added to the log file?

b

Given int i1 = ...;int i2 = ...;What is the best way to test the two variables for equality?

i1 == i2

If MalformedURLException extends IOException and IOException extends Exception, in what order (top to bottom) should the catch blocks appear if a programmer wishes to individually and distinctly catch MalformedURLException, IOException, Exception, and Throwable exceptions? a. The order does not matter: all listed exceptions will be caught if thrown. b. MalformedURLException, IOException, Exception, and Throwable c. Throwable, Exception, IOException, MalformedURLException d. Exception, Throwable, MalformedURLException, IOException e. Throwable, Exception, MalformedURLException, IOException

b

Given Integer i1 = ...; Integer i2 = ...;

i1.equals(i2)

Based on established Java style, what kind of program element is tinyTim

Variable or Method

A program contains the following definitions and statements: public class Employee { private String name; public Employee(String name) { this.name = name; } public String toString() { return name; } public static void change(Employee temp) { temp.name = "Wally"; } } ----------------------------------- Employee e = new Employee("Dilbert"); Employee.change(e); System.out.println(e); What is printed?

Wally

A programmer wishes to create a HashMap to support the mapping demonstrated by the put operation: map.put('N', '\u5317'); Which statement creates the best HashMap for this mapping? a. HashMap<Character, Character> map = new HashMap<>(); b. HashMap<Character, String> map = new HashMap<>(); c. HashMap<String, Character> map = new HashMap<>(); d. HashMap<String, String> map = new HashMap<>();

a

An abstract class may have final methods. Choose the most accurate, relevant, and complete response to this assertion. a. The statement is correct; an abstract class may have concrete methods, which may be final, and which are inheritable. b. The statement is correct; an abstract class may have concrete methods because the final keyword takes precedence over the abstract keyword. c. The statement is INcorrect; abstract classes may not have final methods because final methods may not be overridden. d. The statement is INcorrect; abstract classes may not have final methods because abstract classes may not be instantiated. e. The statement is INcorrect; abstract classes may not have final methods because its methods must be overridden in a subclass. f. The statement is INcorrect; abstract classes may not have final methods because the abstract and final keywords are incompatible.

a

Given that polymorphism allows a programmer to call many of the methods of a subclass that has been upcast, why is it necessary, as a part of overriding the equals method, to down cast the argument? Choose the most correct and the most complete answer: a. Polymorphism applies only to methods and not to data. b. The statement is incorrect: a down-cast is not necessary. c. The down-cast is necessary to insure that both objects are instances of the same class. d. The down-cast is necessary to insure that one object is not null. 4

a

Which statement about Java assertions is the most accurate? a. Assertions must be switched on before they are evaluated. If assertions are not switched on, they are stripped from the byte code by the class loader. b. Once placed in the source code, assertions must be switched off by defining NDEBUG in the code or at the time of compilation. c. Assertions only produce output if the assertion succeeds. d. Assertions are often used to report errors to users. e. Feedback provided by assertions is most useful to end users.

a

Examine the following interface, class, and object instantiation. public interface Foo { public void method(); } public class Bar implements Foo { public void method() { . . . } public void someStuff() { . . . } } ------------------------------------ Foo f = new Bar(); Check all valid method calls. a. f.method(); b. f.someStuff();

a Although f refers to an instance of Bar, the reference variable 'f' only "knows" about features defined in the Foo interface.

The following two classes are defined in a Java program. Choose the best sequence of statements to complete the SalesEmployee constructor. public class Employee { private String name; private float salary; public Employee(String name, float salary) { this.name = name; this.salary = salary; } public float calcPay() { return salary / 24; } } // Employee public class SalesEmployee extends Employee { private float commission; private float totalSales; public SalesEmployee (String name, float salary, float commission, float totalSales) { ______________________; } public float calcPay() { return____________________; } } // SalesEmployee a. super(name, salary); this.commission = commission; this.totalSales = totalSales; b. this.commission = commission; this.totalSales = totalSales; super(name, salary); c. super.name = name; super.salary = salary; this.commission = commission; this.totalSales = totalSales; d. this.name = name; this.salary = salary; this.commission = commission; this.totalSales = totalSales; e. The argument names must be changed so that they are not the same as the instance variable names before the program will compile.

a name and salary are private instance variables of class Employee so they may not be accessed directly (this rules out c. and d.). The this keyword operates within a class and does not access the super class (this also rules out d.). name and salary must be initialized by the Employee constructor, which is called as super(name, salary) in Sales, but this call must be the first statement in the Employee constructor (this rules out b.). By using the this keyword, instance and local variables may have the same name (this rules out e.).

(Bonus) Examine the two classes and the object instantiation below. abstract public class Stuff { abstract public void firstMethod(); public void secondMethod() { . . . } public void thirdMethod() { . . . } } public class MoreStuff extends Stuff { public void firstMethod() { . . . } public void secondMethod() { . . . } public void lastMethod() { . . . } } --------------------------------------------------------------------------- Stuff more = new MoreStuff(); Check all valid method calls: a. more.firstMethod(); b. more.secondMethod(); c. more.thirdMethod(); d. more.lastMethod();

a b c The compiler locates instance variables and method names in the symbol table based on the type of the reference variable (i.e., Stuff more); it locates method bodies (i.e., instructions) polymorphically (that is based on the type of the instantiated object, MoreStuff). a. class Stuff defines an abstract method named firstMethod and although it does not have a body, its name is in the Stuff symbol table and polymorphism locates the overridden body defined in class MoreStuff. b. class Stuff defines a method named secondMethod and polymorphism locates the overridden body defined in class MoreStuff. c. MoreStuff inherits method thirdMethod from Stuff, which is called here. d. Stuff does not have a method named lastMethod, which is required for polymorphism - this statement will not compile let alone run.

Examine the following class definitions: class Beta { public void irradiate(int howHard) { ... } } class Gamma extends Beta { public int irradiate(int howHard) { ... } } Method irradiate is

an erroneously overridden method

Which statement about C/C++ assertions is the most accurate? a. Assertions must be switched on before they are evaluated. If assertions are not switched on, they are excluded from the program by the preprocessor. b. Once placed in the source code, assertions must be switched off by defining NDEBUG in the code or at the time of compilation. c. Assertions only produce output if the assertion succeeds. d. Assertions are often used to report errors to users. e. Feedback provided by assertions is most useful to end users.

b

Given the mapping of the previous question, if "g" is an instance of the Graphics class and "key" is a variable compatible with the HashMap get method, which statement will correctly draw as a String the value returned by get? a. g.drawString(map.get(key), 10, 5); b. g.drawString(map.get(key) + "", 10, 5); c. g.drawString(Character.toString(map.get(key), 10, 5));

b c

Which of the following is generally the best way to create an ArrayList that can store instances of the String class? a. ArrayList list = new ArrayList(); b. ArrayList<String> list = new ArrayList<>(); c. ArrayList<String> list = new ArrayList<String>(); d. ArrayList<> list = new ArrayList<String>();

b or c

Which of the following collections can store values of type int (caution: tricky)? a. ArrayList list = new ArrayList(); b. ArrayList<int> list = new ArrayList<>(); c. ArrayList<Integer> list = new ArrayList<>();

c

The following two classes are defined in a Java program. Choose the best sequence of statements to complete the SalesEmployee calcPay method if the sales employee should be paid a salary plus a commission (commission times total sales). public class Employee { private String name; private float salary; public Employee(String name, float salary) { this.name = name; this.salary = salary; } public float calcPay() { return salary / 24; } } // Employee public class SalesEmployee extends Employee { private float commission; private float totalSales; public SalesEmployee (String name, float salary, float commission, float totalSales) { ______________________; } public float calcPay() { return____________________; } } // SalesEmployee a. salary / 24 + commission * totalSales b. calcPay() + commission * totalSales c. super.calcPay() + commission * totalSales d. The SalesEmployee class cannot have a separate calcPay method as a method with that name is already defined in the super class.

c salary is private in the Employee class and so may not be accessed directly in the SalesEmployee class. The super key word is needed to call the Employee calcPay from the SalesEmployee calcPay method to avoid a recursive call to SalesEmployee calcPay.

Examine the following code fragments and determine the relationship between the two classes. class Foo { ... }; class Bar { private final Foo myFoo; .. };

composition

Which class relationship(s) is/are strong or tight? (Mark all that apply.)

composition, inheritance

What is the relationship between class A and class C? Dotted line from a to C

dependency

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { Integer o1 = new Integer(10); Integer o2 = new Integer(10); if (o1.equals(o2)) System.out.println("equals"); else System.out.println("! equals"); } }

equals

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { String o1 = "Hello"; String o2 = "Hel"; o2 += "lo"; if (o1.equals(o2)) System.out.println("equals"); else System.out.println("! equals"); } }

equals

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { String o1 = "Hello"; String o2 = "Hello"; if (o1.equals(o2)) System.out.println("equals"); else System.out.println("! equals"); } }

equals

Foo is the name of a class but no additional details about the class are known. f1 and f2 are two Foo reference variables. What is the best way to check if the two variables refer or point to the same object?

f1 == f2

Foo is the name of a class but no additional details about the class are known. f1 is a Foo reference variable. What is the best way to check if f1 is null?

f1 == null

(2 pts) "names" is a fully filled array of Strings. Write a for-each loop that prints every element of the array to the console in order. (Do not write a complete program.)

for (String s : names) { System.out.print(s); }

(2 pts) "names" is a sparsely filled array of Strings: some array elements contain Strings but others are null - the filled and empty elements are mixed. Write a loop that prints the Strings to the console but skips the null elements. (Do not write a complete program.)

for(int i = 0; i < names.length; i++) { if (names[i] != (null)) System.out.print(names[i]); }

2 pts) "names" is a partially filled array of Strings: the first elements contain Strings but the last elements are null. Write a loop that prints the Strings to the console but stops at the first null. (Do not write a complete program.)

for(int i = 0; i < names.length; i++) { if (names[i] == (null)) break; System.out.print(names[i]); }

A Java program contains the expression data.length() data is an

instance of String

Examine the classes and the object instantiation below. public class Alpha { public int counter; } public class Beta extends Alpha { public int total; } public class Gamma extends Beta { public int max; } -------------------------------------------- Beta myBeta = new Gamma(); Which of the following statements are valid? Check all that represent a valid instance variable access (note that all instance variables are public):

myBeta.counter = 0; myBeta.total = 100;

The following code fragments establish a relationship between two classes: public class Foo { . . . } public class Bar extends Foo { . . . } Note the argument type in the method definition below: myMethod(Foo f) { . . . } Finally, examine the object that is instantiated and passed in the method call: myMethod(new Bar()); Based on the code fragments above, choose the statement below that is the most accurate and the most complete:

myMethod(new Bar()); causes an object up-cast.

Given the following method definition: public void foo(void) throws Bar { ... } If class Bar extends class RuntimeException, must a method calling foo either catch or claim (with the throws keyword) exception Bar?

no

public class BadException extends Exception { . . . } public class MyException extends BadException { . . . } ... try { // code that could throw either a BadException // or a MyException } catch (BadException be) { System.err.println("Bad Exception caught"); } catch (MyException me) { System.err.println("My Exception caught"); } Will "My Exception caught" ever print?

no

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { String o1 = "Hello"; String o2 = "Hel"; o2 += "lo"; if (o1 == o2) System.out.println("o1 == o2"); else System.out.println("o1 != o2"); } }

o1 != 02 Strings are immutable (i.e., they cannot be modified. So, the += operator creates a new string object. The new object is distinct from the "Hello" string created by the previous statement, so the two strings have different addresses.

public class EqDemo { public static void main(String[] args) { Integer o1 = new Integer(10); Integer o2 = new Integer(10); if (o1 == o2) System.out.println("o1 == o2"); else System.out.println("o1 != o2"); } }

o1 != o2

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { Integer o1 = new Integer(10); Integer o2 = o1; if (o1 == o2) System.out.println("o1 == o2"); else System.out.println("o1 != o2"); } }

o1 == o2

The following code is executed on a Windows-based JVM. What does the code print? public class EqDemo { public static void main(String[] args) { String o1 = "Hello"; String o2 = "Hello"; if (o1 == o2) System.out.println("o1 == o2"); else System.out.println("o1 != o2"); } }

o1 == o2 String literals are created using the double-quotation marks. Most JVM's use a string literal pool - a collection of string literals. Whenever a string literal appears in a Java program, the JVM checks to see if it's already in the pool. If the string is already in the pool, a reference to it is returned and a new string is not created; if it's not in the pool, a new string is created and placed in the pool. So, in this problem, o2 is not a new string: it points to the string created by o1. The two strings have the same address.

A programmer is overriding the toString method for a class named Foo. Choose the correct signature for the method. (Covered in the chap 4 videos, but chap 5 of the text.)

public String toString()

(10 pts) You are developing a new game in which different kinds of disks are played in pairs on a game board as indicated by a method named canPlay. Two disks can be played when they meet the following criteria: 1. Both disks are the same kind (i.e., they are instances of the same class) a. Also verify that the argument disk is not null b. For efficiency, also check for the case of comparing a disk to itself, which should return false (a disk cannot be played against itself) 2. Spotted disks have the same number of spots 3. Sided disks have the same number of sides 4. Colored disks are the same color Write the four "canPlay" methods (do not write complete classes) indicated in the accompanying UML class diagram. Following good object-oriented class design, push each test as high in the inheritance hierarchy as is possible and have the canPlay methdod in the subclasses call the canPlay in the super classes. Note that the UML diagram is not complete - it just presents the information relevant to this problem. The typical Java equals method is similar to the canPlay method, but note the argument type in the UML class diagram. Follow the Horstmann "recipe for writing the perfect equals method." Disk +canPlay(Disk d) : boolean spotted and fancy both white arrow to disk SpottedDisk ‐spots : int +canPlay(Disk d) : boolean FancyDisk sided/colored both white arrow to fancy SidedDisk ‐sides : int +canPlay(Disk d) : boolean ColoredDisk ‐color : String +canPlay(Disk d) : boolean

public boolean canPlay(Disk d) { //disk if (this == d) return true; if(d == null) return false; if(getClass() != d.getClass()) return false; Disk other = (Disk)d; return other == d; } public boolean canPlay(Disk d) { //spotted disk super.canPlay(d); if (this == d) return true; if(d == null) return false; if(getClass() != d.getClass()) return false; if(super.canPlay(d)) return true; SpottedDisk other = (SpottedDisk)d; return spots == other.spots; } public boolean canPlay(Disk d) { //sided disk super.canPlay(d); if (this == d) return true; if(d == null) return false; if(getClass() != d.getClass()) return false; if(super.canPlay(d)) return true; SidedDisk other = (SidedDisk)d; return sides == other.sides; } public boolean canPlay(Disk d) { //colored disk if (this == d) return true; if(d == null) return false; if(getClass() != d.getClass()) return false; if(super.canPlay(d)) return true; ColoredDisk other = (ColoredDisk)d; return color == other.color; }

Foo is the name of a class that overrides the equals method. What is the correct signature for the Foo equals method?

public boolean equals(Object arg)

A programmer is overriding the equals method for a class named Foo. Choose the correct signature for the method. (Covered in the chap 4 videos, but chap 5 of the text.)

public boolean equals(Object otherObject)

Person ‐name : String +Person(name : String, street : String, city : String) diamond going from address to person Address ‐street : String +Address(street : String, city : String) ‐city : String

public class Address { private String street; private String city; public Address(String street, String city) { this.street = street; this.city = city; } } public class Person { private String name; private Address addr; public Person(String name, String street, String city) { this.name = name; addr = new Address(street, city); } }

Convert the UML diagram into a Java class. With the exception of the constructor and the accessor (getter) method, you may leave the method bodies empty. Foo ‐count : int +Foo(count : int, name : String) +running : boolean ‐myHelper(arg : int) : char ‐name : String +getName() : String #bar() : void

public class Foo private int count; private name String; public boolean running; public Foo(int count, String name) { this.count = count; this.name = name; } public String getName() { return name; } protected void bar() { } private char myHelper(int arg) { } }

A programmer wishes to use the sort(T[] a) method defined in the Arrays class to sort an array of Foo objects. Choose the best definition for class Foo: a. public class Foo implements Comparator<Foo> { . . . } b. public class Foo implements Comparable<Foo> { . . . } c. public class Foo extends Comparator<Foo> { . . . } d. public class Foo extends Comparable<Foo> { . . . } e. public class Foo extends Sortable<Foo> { . . . } f. public class Foo { . . . }

public class Foo implements Comparable<Foo> { . . . }

Convert the UML class diagram into public Java classes; complete the constructors. HINT: construction begins with the MotherBoard constructor. MotherBoard ‐model : String +MotherBoard(model : String, speed : double) solid line between them CPU ‐speed : double +CPU(mb : MotherBoard, speed : double)

public class MotherBoard { private String model; private CPU cpu; public Motherboard(String model, double speed) { this.model = model; cpu = new CPU(this, speed); } } public class CPU { private double speed; private MotherBoard mb; public CPU(MotherBoard mb, double speed) { this.speed = speed; this.mb = mb; } }

Person ‐name : String +Person(name : String) white arrow from employee to person(inheritence) Employee ‐id : int +Employee(name : String, id : int)

public class Person { private String name; public Person(String name) { this.name = name; } } public class Employee extends Person { private int id; public Employee(String name, int id) { super(name); this.id = id; } }

(6 pts) A class named Part has two fields: category (int) and cost (double). Write a single Comparable compareTo method that orders Part objects by ascending categories and by ascending cost within each category. For example: . . . . 2 12.96 2 45.12 2 87.00 2 100.38 2 253.93 . . . . 10 34.12 10 34.98 10 294.23 10 3467.89 . . . .

public int compareTo(Part other) { if (other.category < category) return 1; if ( other.category > category ) return -1; if ( other.cost < cost ) return 1; if (other.cost > cost) return -1; return 0; }

Given String s1 = ...;String s2 = ...;What is the best way to test the two Strings for equality (i.e., they contain the same characters)?

s1.equals(s2)

Assuming that args is the name of the formal argument for the main method in a Java class named Foo and that the resulting program is executed from the command line as C:\>java Foo see the quick red fox What is the value of args[0]?

see

Based on established Java style, what kind of program element is HAIR_BALL

symbolic or named constant

Complete the method definition by filling in the blank: public void foo() throws Up, Fit { .... } ... public void callsFoo()______________ { try { foo(); } catch (Up u) { . . . } catch (Fit f) { . . . throw f; } }

throws fit

Older collection classes that have synchronized methods run more slowly than newer collection classes that do not have synchronized methods

true

Given the following method definition: public void foo(void) throws Bar { ... } If class Bar extends class Exception, must a method calling foo either catch or claim (with the throws keyword) exception Bar?

yes


Ensembles d'études connexes

Underwriting Basics, 4th Edition Course

View Set

Course 5: Sec 2: Search and Display Marketing

View Set

emergency and mass casualty incidents - exam 3

View Set

Criminalistics chapters 1-3 (exam 1)

View Set

U.S. History Final Exam - Immigration in America

View Set

week 1 Skills and Strategies Quiz

View Set