Algorithms (Solved Questions &
Answers)
1. What is the output for the Java code segment below?
StringBuilder B1 = new StringBuilder("Fun");
StringBuilder B2 = B1;
B1.append(" Trace");
B2.append(" Code"); System.out.println(B1.toString()
+ " and " + B2.toString());
a.) Fun and Code
b.) Fun Trace and Code
c.) Fun Trace and Fun Code
d.) Fun Trace and Fun Trace Code
e.) Fun Trace Code and Fun Trace Code
f.) [Error -- the code will cause an exception] -
ANSWER ✔ e.) Fun Trace Code and Fun Trace Code
,2. Consider Java classes Foo and SubFoo, where
SubFoo is a subclass of Foo. Which of the following
Java statements are legal?
a.) Foo F = new Foo();
b.) SubFoo S = new SubFoo();
c.) Foo F = new SubFoo();
d.) SubFoo S = new Foo(); - ANSWER ✔ a.) Foo F =
new Foo();
b.) SubFoo S = new SubFoo();
c.) Foo F = new SubFoo();
3. Which of the following are true with respect to Java
interfaces? Indicate ALL true statements.
a.) Regular instance methods are all abstract
b.) Can have instance variables
c.) Can instantiate objects of an interface type
d.) A class may implement multiple interfaces -
ANSWER ✔ a.) Regular instance methods are all
abstract
d.) A class may implement multiple interfaces
,4. What is different in a method to sort an array of
String and a method to sort an array of Integer?
a.) Nothing is different about them
b.) The data is compared differently in an array of
String than it is in an array of Integer
c.) The fundamental approach to sorting is different in
the two types - ANSWER ✔ b.) The data is compared
differently in an array of String than it is in an array of
Integer
5. Consider two Java classes, Foo and SubFoo, where
SubFoo is a subclass of Foo. Also consider the
following Java statements:
ArrayList<Foo> L1 = new ArrayList<Foo>();
ArrayList<Foo> L2;
Indicate which of the statements below are legal.
Indicate all legal statements.
a.) L1.add(new Foo());
b.) L1.add(new SubFoo());
c.) L1.add(new String("Hello"));
, d.) L2 = new ArrayList<SubFoo>(); - ANSWER ✔ a.)
L1.add(new Foo());
b.) L1.add(new SubFoo());
6. Which of the following are not legal in Java?
a.) static constants in an interface
b.) instance data in an interface
c.) A class extending more than one superclass
d.) A class implementing more than one interface -
ANSWER ✔ b.) instance data in an interface
c.) A class extending more than once superclass
7. Consider the Java interface
Comparable<T>
What does T represent in this interface?
a.) The type of the object from which compareTo() will
be called
b.) The type of the object passed in to compareTo() [i.e.
the argument type]