In this chapter, we are going to take a look at some questions on the Inner class topics we had seen in the past few chapters.
All the best!!!
Questions:
Question 1.
Which are true about a static nested class? (Choose all that apply.)
A. You must have a reference to an instance of the enclosing class in order to instantiate it
B. It does not have access to non-static members of the enclosing class
C. Its variables and methods must be static
D. If the outer class is named MyOuter, and the nested class is named MyInner, it can be instantiated using new MyOuter.MyInner();
E. It must extend the enclosing class
Question 2.
Given:
class Parent {
Parent(String s) { }
Parent() { }
}
class Child extends Parent {
Child() { }
Child(String s) {super(s);}
void dooo() {
// insert code here
}
}
Which create an anonymous inner class from within class Child? (Choose all that apply.)
A. Parent f = new Parent(24) { };
B. Parent f = new Child() { };
C. Parent f = new Parent() {String s; };
D. Child f = new Parent(String s) { };
E. Parent f = new Parent.Child(String s) { };
Question 3.
Which are true about a method-local inner class? (Choose all that apply.)
A. It must be marked final
B. It can be marked abstract
C. It can be marked public
D. It can be marked static
E. It can access private members of the enclosing class
Question 4.
Given:
1. public class TestClass {
2. public static void main(String[] args) {
3. Object o = new Object() {
4. public boolean equals(Object obj) {
5. return true;
6. }
7. }
8. System.out.println(o.equals("Rocky"));
9. }
10. }
What is the result?
A. An exception occurs at runtime
B. true
C. Rocky
D. Compilation fails because of an error on line 3
E. Compilation fails because of an error on line 4
F. Compilation fails because of an error on line 8
G. Compilation fails because of an error on a line other than 3, 4, or 8
Question 5.
Given:
1. public class CarTest {
2. public static void main(String[] args) {
3. class Car {
4. public String name;
5. public Car(String s) {
6. name = s;
7. }
8. }
9. Object obj = new Car("Ferrari");
10. System.out.println(obj.name);
11. }
12. }
What is the result?
A. An exception occurs at runtime at line 10
B. Ferrari
C. Compilation fails because of an error on line 3
D. Compilation fails because of an error on line 9
E. Compilation fails because of an error on line 10
Question 6.
Given:
public abstract class TestAbstractEx {
public int getNum() {
return 45;
}
public abstract class Child {
public int getNum() {
return 38;
}
}
public static void main(String[] args) {
TestAbstractEx t = new TestAbstractEx() {
public int getNum() {
return 22;
}
};
TestAbstractEx.Child f = t.new Child() {
public int getNum() {
return 57;
}
};
System.out.println(f.getNum() + " " + t.getNum());
}
}
What is the result?
A. 57 22
B. 45 38
C. 45 57
D. An exception occurs at runtime
E. Compilation fails
Question 7.
Given:
3. public class Test {
4. public static void main(String[] args) {
5. Outer c = new Outer();
6. // insert code here
7. s.go();
8. }
9. }
10. class Outer {
11. class Inner {
12. void go() { System.out.println("hiii"); }
13. }
14. }
Which, inserted independently at line 6, compile and produce the output “hiii”? (Choose all that apply.)
A. Inner s = c.new Inner();
B. c.Inner s = c.new Inner();
C. c.Inner s = Outer.new Inner();
D. Outer.Inner s = c.new Inner();
E. Outer.Inner s = Outer.new Inner();
Question 8.
Given:
5. class A { void m() { System.out.println("outer"); } }
6.
7. public class TestInnerClass {
8. public static void main(String[] args) {
9. new TestInnerClass().go();
10. }
11. void go() {
12. new A().m();
13. class A { void m() { System.out.println("inner"); } }
14. }
15. class A { void m() { System.out.println("middle"); } }
16. }
What is the result?
A. inner
B. outer
C. middle
D. Compilation fails
E. An exception is thrown at runtime
Question 9.
Given:
3. public class Car {
4. class Engine {
5. // insert code here
6. }
7. public static void main(String[] args) {
8. new Car().go();
9. }
10. void go() {
11. new Engine();
12. }
13. void drive() { System.out.println("hi"); }
14. }
Which, inserted independently at line 5, produce the output “hi”? (Choose all that apply.)
A. { Car.drive(); }
B. { this.drive(); }
C. { Car.this.drive(); }
D. { this.Car.this.drive(); }
E. Engine() { Car.drive(); }
F. Engine() { this.drive(); }
G. Engine() { Car.this.drive(); }
Question 10.
Given:
3. public class City {
4. class Chennai {
5. void doSomething() throws Exception { System.out.print("x "); }
6. }
7. class MarinaBeach extends Chennai {
8. void doSomething() throws Exception { }
9. }
10. public static void main(String[] args) throws Exception {
11. new City().go();
12. }
13. void go() throws Exception { new MarinaBeach().doSomething(); }
14. }
What is the result?
A. x
B. x x
C. No output is produced
D. Compilation fails due to multiple errors
E. Compilation fails due only to an error on line 4
F. Compilation fails due only to an error on line 7
G. Compilation fails due only to an error on line 10
H. Compilation fails due only to an error on line 13
Self Test Answers:
Answer 1.
B and D. B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can’t access the non-static members of the class (just as a static method can’t access non-static members of a class). D uses the correct syntax for instantiating a static nested class.
A is incorrect because static nested classes do not need (and can’t use) a reference to an instance of the enclosing class. C is incorrect because static nested classes can declare and define non-static members. E is wrong because...it just is. There’s no rule that says an inner or nested class has to extend anything.
Answer 2.
B and C. B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Child. Since Child is a subclass of Parent, it all works. C uses correct syntax for creating an instance of Parent.
A is incorrect because it passes an int to the Parent constructor, and there is no matching constructor in the Parent class. D is incorrect because it violates the rules of polymorphism; you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass doesn’t have everything the subclass has. E uses incorrect syntax.
Answer 3.
B and E. B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful). E is correct because a method-local inner class works like any other inner class—it has a special relationship to an instance of the enclosing class, thus it can access all members of the enclosing class.
A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so). C and D are incorrect because a method-local inner class cannot be made public (remember—local variables can’t be public) or static.
Answer 4.
G. This code would be legal if line 7 ended with a semicolon. Remember that line 3 is a statement that doesn’t end until line 7, and a statement needs a closing semicolon!
A, B, C, D, E, and F are incorrect based on the program logic described above. If the semicolon were added at line 7, then answer B would be correct—the program would print true, the return from the equals() method overridden by the anonymous subclass of Object.
Answer 5.
E. If you use a reference variable of type Object, you can access only those members defined in class Object.
Answer 6.
A. You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of TestAbstractEx, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Child, and the anonymous Child subclass also overrides the getNum() method (to return 57). Remember that to create a Child instance, we need an instance of the enclosing TestAbstractEx class to tie to the new Child inner class instance. TestAbstractEx can’t be instantiated because it’s abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Child subclass instance.
Answer 7.
D is correct. It is the only code that uses the correct inner class instantiation syntax.
A, B, C, and E are incorrect based on the above. (Objective 1.1)
Answer 8.
C is correct. The "inner" version of class A isn’t used because its declaration comes after the instance of class A is created in the go() method.
Answer 9.
C and G are correct. C is the correct syntax to access an inner class’s outer instance method from an initialization block, and G is the correct syntax to access it from a constructor.
Answer 10.
C is correct. The inner classes are valid, and all the methods (including main()), correctly throw an Exception, given that doSomething() throws an Exception. The doSomething() in class MarinaBeach overrides class Chennai’s doSomething() and produces no output.
Previous Chapter: Quick Review - Inner classes
Next Chapter: Chapter 56 - Threads & Multithreading
Topics Covered in the Blog - Synopsis
Showing posts with label scjp questions. Show all posts
Showing posts with label scjp questions. Show all posts
Friday, February 25, 2011
Self Test: Chapters 38 to 51
Below are some questions from the previous chapters that would help you practice for the SCJP examination.
All the best !!!
Questions:
Question 1.
Given:
public static void main(String[] args) {
// CODE HERE
for (int i = 0; i <= 10; i++) {
List < Integer > row = new ArrayList < Integer > ();
for (int j = 0; j <= 10; j++)
row.add(i * j);
table.add(row);
}
for (List < Integer > row : table)
System.out.println(row);
}
Which statements could be inserted at // CODE HERE to allow this code to compile and run? (Choose all that apply.)
A. List < List< Integer > > table = new List < List < Integer > >();
B. List < List< Integer > > table = new ArrayList < List < Integer > >();
C. List < List< Integer > > table = new ArrayList < ArrayList < Integer > >();
D. List < List, Integer > table = new List < List, Integer >();
E. List < List, Integer > table = new ArrayList < List, Integer >();
F. List < List, Integer > table = new ArrayList < ArrayList, Integer >();
G. None of the above
Question 2.
Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply.)
A. If the equals() method returns true, the hashCode() comparison == might return false
B. If the equals() method returns false, the hashCode() comparison == might return true
C. If the hashCode() comparison == returns true, the equals() method must return true
D. If the hashCode() comparison == returns true, the equals() method might return true
E. If the hashCode() comparison != returns true, the equals() method might return true
Question 3.
Given:
public static void doSomething() {
Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}
Which statements are true?
A. The doSomething() method will print 1 2
B. The doSomething() method will print 1 2 3
C. The doSomething() method will print three numbers, but the order cannot be determined
D. The doSomething() method will not compile
E. The doSomething() method will throw an exception at runtime
Question 4.
Given:
import java.util.*;
class TestMaps {
public static void main(String[] args) {
Map m = new HashMap();
Day t1 = new Day("Monday");
Day t2 = new Day("Monday");
Day t3 = new Day("Tuesday");
m.put(t1, "goToGym");
m.put(t2, "visitMom");
m.put(t3, "goShopping");
System.out.println(m.size());
}
}
class Day{
String day;
Day(String d) { day = d; }
public boolean equals(Object o) {
return ((Day)o).day == this.day;
}
// public int hashCode() { return 9; }
}
Which is correct? (Choose all that apply.)
A. As the code stands it will not compile
B. As the code stands the output will be 2
C. As the code stands the output will be 3
D. If the hashCode() method is uncommented the output will be 2
E. If the hashCode() method is uncommented the output will be 3
F. If the hashCode() method is uncommented the code will not compile
Question 5.
Given:
12. public class BankAppManager {
13. private Map allBalances = new HashMap();
14. private int corpus;
15.
16. public int calcAccBalance(String custName) {
17. Integer total = (Integer) allBalances.get(custName);
18. if (total == null)
19. total = Integer.valueOf(0);
20. return total.intValue();
21. }
23. public void updateAccBalance(String custName, int amount) {
24. allBalances.put(custName, Integer.valueOf(amount));
25. }
26. }
This class is to be updated to make use of appropriate generic types, with no changes in behavior (for better or worse). Which of these steps could be performed? (Choose three.)
A. Replace line 13 with
private Map < String, int > allBalances = new HashMap < String, int >();
B. Replace line 13 with
private Map < String, Integer > allBalances = new HashMap < String, Integer >();
C. Replace line 13 with
private Map < String< Integer > > allBalances = new HashMap < String< Integer > >();
D. Replace lines 17–20 with
int total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
E. Replace lines 17–20 with
Integer total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
F. Replace lines 17–20 with
return allBalances.get(custName);
G. Replace line 24 with
allBalances.put(custName, amount);
H. Replace line 24 with
allBalances.put(custName, amount.intValue());
Question 6.
Given:
interface Drivable< E > { void driveee(E x); }
interface Car extends Drivable< E > {}
interface Van extends Drivable< E > {}
abstract class SomethingElse {}
class Xxxxxx extends SomethingElse {}
abstract class Something {}
class SuzukiSwift extends Something implements Van {
public void driveee(SuzukiSwift x) {}
}
class VwJetta extends Something implements Car {
public void driveee(SuzukiSwift x) {}
}
Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
A. Change the Car interface to
interface Car extends Drivable< E > {}
B. Change the Van interface to
interface Van extends Drivable< E > {}
C. Change the SuzukiSwift class to
class SuzukiSwift extends Something implements Van {
public void driveee(Xxxxxx x) {}
}
D. Change the SuzukiSwift class to
class SuzukiSwift extends SomethingElse implements Car {
public void driveee(VwJetta x) {}
E. Change the VwJetta class to
class VwJetta extends Something implements Van {
public void driveee(Xxxxxx x) {}
}
F. No changes are necessary
Question 7.
Which collection class(es) allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? (Choose all that apply.)
A. java.util.HashSet
B. java.util.LinkedHashSet
C. java.util.List
D. java.util.ArrayList
E. java.util.Vector
F. java.util.PriorityQueue
Question 8.
Given a method declared as
public static < e extends Number > List < E > process(List < E > nums)
A programmer wants to use this method like this
// PUT CODE HERE
output = process(input);
Which pairs of declarations could be placed at // PUT CODE HERE to allow the code to compile? (Choose all that apply.)
A. ArrayList < Integer > input = null;
B. ArrayList < Integer > output = null;
C. ArrayList < Integer > input = null;
D. List < Integer > output = null;
E. ArrayList < Integer > input = null;
F. List < Number > output = null;
G. List < Number > input = null;
H. ArrayList < Integer > output = null;
I. List < Number > input = null;
J. List < Number > output = null;
K. List < Integer > input = null;
L. List < Integer > output = null;
M. None of the above
Question 9.
Given the proper import statement(s), and
13. PriorityQueue < String > pq = new PriorityQueue < String >();
14. pq.add("2");
15. pq.add("4");
16. System.out.print(pq.peek() + " ");
17. pq.offer("1");
18. pq.add("3");
19. pq.remove("1");
20. System.out.print(pq.poll() + " ");
21. if(pq.remove("2")) System.out.print(pq.poll() + " ");
22. System.out.println(pq.poll() + " " + pq.peek());
What is the result?
A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime
Question 10.
Given:
3. import java.util.*;
4. public class ConfuseMe {
5. public static void main(String[] args) {
6. Object o = new Object();
7. // insert code here
8. s.add("o");
9. s.add(o);
10. }
11. }
And these three fragments:
I. Set s = new HashSet();
II. TreeSet s = new TreeSet();
III. LinkedHashSet s = new LinkedHashSet();
When fragments I, II, or III are inserted, independently, at line 7, which are true? (Choose all that apply.)
A. Fragment I compiles
B. Fragment II compiles
C. Fragment III compiles
D. Fragment I executes without exception
E. Fragment II executes without exception
F. Fragment III executes without exception
Question 11.
Given:
3. import java.util.*;
4. class Dog {
5. int size;
6. public Dog(int s) { size = s; }
7. public boolean equals(Object o) { return (this.size == ((Dog)o).size); }
8. // insert code here
9. }
10. public class DogTest {
11. public static void main(String[] args) {
12. LinkedHashSet< Dog > t = new LinkedHashSet< Dog >();
13. t.add(new Dog(1)); t.add(new Dog(2)); t.add(new Dog(1));
14. System.out.println(t.size());
15. }
16. }
And these two fragments:
I. public int hashCode() { return size/5; }
II. // no hashCode method declared
If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)
A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails
Question 12.
Given the proper import statement(s), and:
13. TreeSet< String > s = new TreeSet< String >();
14. TreeSet< String > subs = new TreeSet< String >();
15. s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");
16.
17. subs = (TreeSet)s.subSet("b", true, "d", true);
18. s.add("g");
19. s.pollFirst();
20. s.pollFirst();
21. s.add("c2");
22. System.out.println(s.size() +" "+ subs.size());
Which are true? (Choose all that apply.)
A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime
Question 13.
Given:
3. import java.util.*;
4. public class TestMe {
5. public static void main(String[] args) {
6. TreeMap myMap = new TreeMap();
7. myMap.put("a", "apple"); myMap.put("d", "date");
8. myMap.put("f", "fig"); myMap.put("p", "pear");
9. System.out.println("1st after mango: " + // sop 1
10. myMap.higherKey("f"));
11. System.out.println("1st after mango: " + // sop 2
12. myMap.ceilingKey("f"));
13. System.out.println("1st after mango: " + // sop 3
14. myMap.floorKey("f"));
15. SortedMap sub = new TreeMap();
16. sub = myMap.tailMap("f");
17. System.out.println("1st after mango: " + // sop 4
18. sub.firstKey());
19. }
20. }
Which of the System.out.println statements will produce the output 1st after mango: p? (Choose all that apply.)
A. sop 1
B. sop 2
C. sop 3
D. sop 4
E. None; compilation fails
F. None; an exception is thrown at runtime
Question 14.
Given:
3. import java.util.*;
4. class Car { }
5. class Ferrari extends Car { }
6. class F550Barchetta extends Ferrari { }
7. public class DriveAround {
8. ArrayList< Ferrari > go() {
9. // insert code here
10. }
11. }
Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList < F550Barchetta >();
B. return new ArrayList < Ferrari >();
C. return new ArrayList < Object >();
D. return new ArrayList < Car >();
Question 15.
Given:
3. import java.util.*;
4. class Shoe { int size; Shoe(int s) { size = s; } }
5. public class FirstGrade {
6. public static void main(String[] args) {
7. TreeSet < Integer > i = new TreeSet < Integer >();
8. TreeSet < Shoe > d = new TreeSet < Shoe >();
9.
10. d.add(new Shoe(1)); d.add(new Shoe(2)); d.add(new Shoe(1));
11. i.add(1); i.add(2); i.add(1);
12. System.out.println(d.size() + " " + i.size());
13. }
14. }
What is the result?
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime
Answers:
Answer 1.
B is correct.
A is incorrect because List is an interface, so you can’t say new List() regardless of any generic types. D, E, and F are incorrect because List only takes one type parameter (a Map would take two, not a List). C is tempting, but incorrect. The type argument < List< Integer >> must be the same for both sides of the assignment, even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left.
Answer 2.
B and D. B is true because often two dissimilar objects can return the same hashcode value. D is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.
A, C, and E are incorrect. C is incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. A and E are a negation of the hashCode() and equals() contract.
Answer 3.
E is correct. You can’t put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they’re added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the doSomething() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.
Answer 4.
C and D are correct. If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency. If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.
Answer 5.
B, E, and G are correct.
A is wrong because you can’t use a primitive type as a type parameter. C is wrong because a Map takes two type parameters separated by a comma. D is wrong because an int can’t autobox to a null, and F is wrong because a null can’t unbox to 0. H is wrong because you can’t autobox a primitive just by trying to invoke a method with it.
Answer 6.
B is correct. The problem with the original code is that SuzukiSwift tries to implement Van and Van declares that its type parameter E can be any type that extends SomethingElse. Since a SuzukiSwift is not a SomethingElse, Van makes no sense—the type SuzukiSwift is outside the allowed range of Van’s parameter E. Only solutions that either alter the definition of a SuzukiSwift or alter the definition of Van will be able to fix this. So A, E, and F are eliminated. B works, changing the definition of an Van to allow it to eat SuzukiSwift solves the problem. C doesn’t work because an Van must have a driveee(SomethingElse) method, not driveee(Xxxxxx).
And D doesn’t work, because in D we made SuzukiSwift extend SomethingElse, now the VwJetta class breaks because its driveee(SuzukiSwift) method no longer fulfills the contract of Car.
Answer 7.
D is correct. All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.
A, B, C, E, and F are incorrect based on the logic described above; Notes: C, List is an interface, and F, PriorityQueue does not offer access by index.
Answer 8.
B, E, and F are correct.
The return type of process is definitely declared as a List, not an ArrayList, so A and D are wrong. C is wrong because the return type evaluates to List< Integer >, and that can’t be assigned to a variable of type List< Number >. Of course all these would probably cause a NullPointerException since the variables are still null—but the question only asked us to get the code to compile.
Answer 9.
B is correct. For the sake of the exam, add() and offer() both add to (in this case), naturally sorted queues. The calls to poll() both return and then remove the first item from the queue, so the if test fails.
Answer 10.
A, B, C, D, and F are all correct.
Only E is incorrect. Elements of a TreeSet must in some way implement Comparable.
Answer 11.
A and D are correct. While fragment II wouldn’t fulfill the hashCode() contract (as you can see by the results), it is legal Java. For the purpose of the exam, if you don’t override hashCode(), every object will have a unique hashcode.
Answer 12.
B and F are correct. After "g" is added, TreeSet s contains six elements and TreeSet subs contains three (b, c, d), because "g" is out of the range of subs. The first pollFirst() finds and removes only the "a". The second pollFirst() finds and removes the "b" from both TreeSets (remember they are backed). The final add() is in range of both TreeSets. The final contents are [c,c2,d,e,g] and [c,c2,d].
Answer 13.
A is correct. The ceilingKey() method’s argument is inclusive. The floorKey() method would be used to find keys before the specified key. The firstKey() method’s argument is also inclusive.
Answer 14.
B is correct.
A is incorrect because polymorphic assignments don’t apply to generic type parameters. C and D are incorrect because they don’t follow basic polymorphism rules.
Answer 15.
G is correct. Class Shoe needs to implement Comparable in order for a TreeSet (which keeps its elements sorted) to be able to contain Shoe objects.
Previous Chapter: Quick Review - Chapters 38 to 51
Next Chapter: Chapter 52 - Inner Classes
All the best !!!
Questions:
Question 1.
Given:
public static void main(String[] args) {
// CODE HERE
for (int i = 0; i <= 10; i++) {
List < Integer > row = new ArrayList < Integer > ();
for (int j = 0; j <= 10; j++)
row.add(i * j);
table.add(row);
}
for (List < Integer > row : table)
System.out.println(row);
}
Which statements could be inserted at // CODE HERE to allow this code to compile and run? (Choose all that apply.)
A. List < List< Integer > > table = new List < List < Integer > >();
B. List < List< Integer > > table = new ArrayList < List < Integer > >();
C. List < List< Integer > > table = new ArrayList < ArrayList < Integer > >();
D. List < List, Integer > table = new List < List, Integer >();
E. List < List, Integer > table = new ArrayList < List, Integer >();
F. List < List, Integer > table = new ArrayList < ArrayList, Integer >();
G. None of the above
Question 2.
Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply.)
A. If the equals() method returns true, the hashCode() comparison == might return false
B. If the equals() method returns false, the hashCode() comparison == might return true
C. If the hashCode() comparison == returns true, the equals() method must return true
D. If the hashCode() comparison == returns true, the equals() method might return true
E. If the hashCode() comparison != returns true, the equals() method might return true
Question 3.
Given:
public static void doSomething() {
Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}
Which statements are true?
A. The doSomething() method will print 1 2
B. The doSomething() method will print 1 2 3
C. The doSomething() method will print three numbers, but the order cannot be determined
D. The doSomething() method will not compile
E. The doSomething() method will throw an exception at runtime
Question 4.
Given:
import java.util.*;
class TestMaps {
public static void main(String[] args) {
Map
Day t1 = new Day("Monday");
Day t2 = new Day("Monday");
Day t3 = new Day("Tuesday");
m.put(t1, "goToGym");
m.put(t2, "visitMom");
m.put(t3, "goShopping");
System.out.println(m.size());
}
}
class Day{
String day;
Day(String d) { day = d; }
public boolean equals(Object o) {
return ((Day)o).day == this.day;
}
// public int hashCode() { return 9; }
}
Which is correct? (Choose all that apply.)
A. As the code stands it will not compile
B. As the code stands the output will be 2
C. As the code stands the output will be 3
D. If the hashCode() method is uncommented the output will be 2
E. If the hashCode() method is uncommented the output will be 3
F. If the hashCode() method is uncommented the code will not compile
Question 5.
Given:
12. public class BankAppManager {
13. private Map allBalances = new HashMap();
14. private int corpus;
15.
16. public int calcAccBalance(String custName) {
17. Integer total = (Integer) allBalances.get(custName);
18. if (total == null)
19. total = Integer.valueOf(0);
20. return total.intValue();
21. }
23. public void updateAccBalance(String custName, int amount) {
24. allBalances.put(custName, Integer.valueOf(amount));
25. }
26. }
This class is to be updated to make use of appropriate generic types, with no changes in behavior (for better or worse). Which of these steps could be performed? (Choose three.)
A. Replace line 13 with
private Map < String, int > allBalances = new HashMap < String, int >();
B. Replace line 13 with
private Map < String, Integer > allBalances = new HashMap < String, Integer >();
C. Replace line 13 with
private Map < String< Integer > > allBalances = new HashMap < String< Integer > >();
D. Replace lines 17–20 with
int total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
E. Replace lines 17–20 with
Integer total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
F. Replace lines 17–20 with
return allBalances.get(custName);
G. Replace line 24 with
allBalances.put(custName, amount);
H. Replace line 24 with
allBalances.put(custName, amount.intValue());
Question 6.
Given:
interface Drivable< E > { void driveee(E x); }
interface Car
interface Van
abstract class SomethingElse {}
class Xxxxxx extends SomethingElse {}
abstract class Something {}
class SuzukiSwift extends Something implements Van
public void driveee(SuzukiSwift x) {}
}
class VwJetta extends Something implements Car
public void driveee(SuzukiSwift x) {}
}
Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
A. Change the Car interface to
interface Car
B. Change the Van interface to
interface Van
C. Change the SuzukiSwift class to
class SuzukiSwift extends Something implements Van
public void driveee(Xxxxxx x) {}
}
D. Change the SuzukiSwift class to
class SuzukiSwift extends SomethingElse implements Car
public void driveee(VwJetta x) {}
E. Change the VwJetta class to
class VwJetta extends Something implements Van
public void driveee(Xxxxxx x) {}
}
F. No changes are necessary
Question 7.
Which collection class(es) allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? (Choose all that apply.)
A. java.util.HashSet
B. java.util.LinkedHashSet
C. java.util.List
D. java.util.ArrayList
E. java.util.Vector
F. java.util.PriorityQueue
Question 8.
Given a method declared as
public static < e extends Number > List < E > process(List < E > nums)
A programmer wants to use this method like this
// PUT CODE HERE
output = process(input);
Which pairs of declarations could be placed at // PUT CODE HERE to allow the code to compile? (Choose all that apply.)
A. ArrayList < Integer > input = null;
B. ArrayList < Integer > output = null;
C. ArrayList < Integer > input = null;
D. List < Integer > output = null;
E. ArrayList < Integer > input = null;
F. List < Number > output = null;
G. List < Number > input = null;
H. ArrayList < Integer > output = null;
I. List < Number > input = null;
J. List < Number > output = null;
K. List < Integer > input = null;
L. List < Integer > output = null;
M. None of the above
Question 9.
Given the proper import statement(s), and
13. PriorityQueue < String > pq = new PriorityQueue < String >();
14. pq.add("2");
15. pq.add("4");
16. System.out.print(pq.peek() + " ");
17. pq.offer("1");
18. pq.add("3");
19. pq.remove("1");
20. System.out.print(pq.poll() + " ");
21. if(pq.remove("2")) System.out.print(pq.poll() + " ");
22. System.out.println(pq.poll() + " " + pq.peek());
What is the result?
A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime
Question 10.
Given:
3. import java.util.*;
4. public class ConfuseMe {
5. public static void main(String[] args) {
6. Object o = new Object();
7. // insert code here
8. s.add("o");
9. s.add(o);
10. }
11. }
And these three fragments:
I. Set s = new HashSet();
II. TreeSet s = new TreeSet();
III. LinkedHashSet s = new LinkedHashSet();
When fragments I, II, or III are inserted, independently, at line 7, which are true? (Choose all that apply.)
A. Fragment I compiles
B. Fragment II compiles
C. Fragment III compiles
D. Fragment I executes without exception
E. Fragment II executes without exception
F. Fragment III executes without exception
Question 11.
Given:
3. import java.util.*;
4. class Dog {
5. int size;
6. public Dog(int s) { size = s; }
7. public boolean equals(Object o) { return (this.size == ((Dog)o).size); }
8. // insert code here
9. }
10. public class DogTest {
11. public static void main(String[] args) {
12. LinkedHashSet< Dog > t = new LinkedHashSet< Dog >();
13. t.add(new Dog(1)); t.add(new Dog(2)); t.add(new Dog(1));
14. System.out.println(t.size());
15. }
16. }
And these two fragments:
I. public int hashCode() { return size/5; }
II. // no hashCode method declared
If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)
A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails
Question 12.
Given the proper import statement(s), and:
13. TreeSet< String > s = new TreeSet< String >();
14. TreeSet< String > subs = new TreeSet< String >();
15. s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");
16.
17. subs = (TreeSet)s.subSet("b", true, "d", true);
18. s.add("g");
19. s.pollFirst();
20. s.pollFirst();
21. s.add("c2");
22. System.out.println(s.size() +" "+ subs.size());
Which are true? (Choose all that apply.)
A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime
Question 13.
Given:
3. import java.util.*;
4. public class TestMe {
5. public static void main(String[] args) {
6. TreeMap
7. myMap.put("a", "apple"); myMap.put("d", "date");
8. myMap.put("f", "fig"); myMap.put("p", "pear");
9. System.out.println("1st after mango: " + // sop 1
10. myMap.higherKey("f"));
11. System.out.println("1st after mango: " + // sop 2
12. myMap.ceilingKey("f"));
13. System.out.println("1st after mango: " + // sop 3
14. myMap.floorKey("f"));
15. SortedMap
16. sub = myMap.tailMap("f");
17. System.out.println("1st after mango: " + // sop 4
18. sub.firstKey());
19. }
20. }
Which of the System.out.println statements will produce the output 1st after mango: p? (Choose all that apply.)
A. sop 1
B. sop 2
C. sop 3
D. sop 4
E. None; compilation fails
F. None; an exception is thrown at runtime
Question 14.
Given:
3. import java.util.*;
4. class Car { }
5. class Ferrari extends Car { }
6. class F550Barchetta extends Ferrari { }
7. public class DriveAround {
8. ArrayList< Ferrari > go() {
9. // insert code here
10. }
11. }
Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList < F550Barchetta >();
B. return new ArrayList < Ferrari >();
C. return new ArrayList < Object >();
D. return new ArrayList < Car >();
Question 15.
Given:
3. import java.util.*;
4. class Shoe { int size; Shoe(int s) { size = s; } }
5. public class FirstGrade {
6. public static void main(String[] args) {
7. TreeSet < Integer > i = new TreeSet < Integer >();
8. TreeSet < Shoe > d = new TreeSet < Shoe >();
9.
10. d.add(new Shoe(1)); d.add(new Shoe(2)); d.add(new Shoe(1));
11. i.add(1); i.add(2); i.add(1);
12. System.out.println(d.size() + " " + i.size());
13. }
14. }
What is the result?
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime
Answers:
Answer 1.
B is correct.
A is incorrect because List is an interface, so you can’t say new List() regardless of any generic types. D, E, and F are incorrect because List only takes one type parameter (a Map would take two, not a List). C is tempting, but incorrect. The type argument < List< Integer >> must be the same for both sides of the assignment, even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left.
Answer 2.
B and D. B is true because often two dissimilar objects can return the same hashcode value. D is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.
A, C, and E are incorrect. C is incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. A and E are a negation of the hashCode() and equals() contract.
Answer 3.
E is correct. You can’t put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they’re added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the doSomething() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.
Answer 4.
C and D are correct. If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency. If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.
Answer 5.
B, E, and G are correct.
A is wrong because you can’t use a primitive type as a type parameter. C is wrong because a Map takes two type parameters separated by a comma. D is wrong because an int can’t autobox to a null, and F is wrong because a null can’t unbox to 0. H is wrong because you can’t autobox a primitive just by trying to invoke a method with it.
Answer 6.
B is correct. The problem with the original code is that SuzukiSwift tries to implement Van
And D doesn’t work, because in D we made SuzukiSwift extend SomethingElse, now the VwJetta class breaks because its driveee(SuzukiSwift) method no longer fulfills the contract of Car.
Answer 7.
D is correct. All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.
A, B, C, E, and F are incorrect based on the logic described above; Notes: C, List is an interface, and F, PriorityQueue does not offer access by index.
Answer 8.
B, E, and F are correct.
The return type of process is definitely declared as a List, not an ArrayList, so A and D are wrong. C is wrong because the return type evaluates to List< Integer >, and that can’t be assigned to a variable of type List< Number >. Of course all these would probably cause a NullPointerException since the variables are still null—but the question only asked us to get the code to compile.
Answer 9.
B is correct. For the sake of the exam, add() and offer() both add to (in this case), naturally sorted queues. The calls to poll() both return and then remove the first item from the queue, so the if test fails.
Answer 10.
A, B, C, D, and F are all correct.
Only E is incorrect. Elements of a TreeSet must in some way implement Comparable.
Answer 11.
A and D are correct. While fragment II wouldn’t fulfill the hashCode() contract (as you can see by the results), it is legal Java. For the purpose of the exam, if you don’t override hashCode(), every object will have a unique hashcode.
Answer 12.
B and F are correct. After "g" is added, TreeSet s contains six elements and TreeSet subs contains three (b, c, d), because "g" is out of the range of subs. The first pollFirst() finds and removes only the "a". The second pollFirst() finds and removes the "b" from both TreeSets (remember they are backed). The final add() is in range of both TreeSets. The final contents are [c,c2,d,e,g] and [c,c2,d].
Answer 13.
A is correct. The ceilingKey() method’s argument is inclusive. The floorKey() method would be used to find keys before the specified key. The firstKey() method’s argument is also inclusive.
Answer 14.
B is correct.
A is incorrect because polymorphic assignments don’t apply to generic type parameters. C and D are incorrect because they don’t follow basic polymorphism rules.
Answer 15.
G is correct. Class Shoe needs to implement Comparable in order for a TreeSet (which keeps its elements sorted) to be able to contain Shoe objects.
Previous Chapter: Quick Review - Chapters 38 to 51
Next Chapter: Chapter 52 - Inner Classes
Labels:
java scjp,
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self assement,
self assessment scjp
| Reactions: |
Saturday, February 19, 2011
Self Test: Chapters 32 to 37
Questions:
Question 1:
Given:
import java.util.regex.*;
class TestRegex {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}
And the command line:
java TestRegex "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails
Question 2:
Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class MusicPlayer extends Player implements Serializable {
MusicPlayer() { System.out.print("c"); }
public static void main(String[] args) {
MusicPlayer c1 = new MusicPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
MusicPlayer c2 = (MusicPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
What is the result?
A. pc
B. pcc
C. pcp
D. pcpc
E. Compilation fails
F. An exception is thrown at runtime
Question 3:
Given:
class Test {
public static void main(String[] args) {
String s = "-";
Integer x = 343;
long L343 = 343L;
if(x.equals(L343)) s += ".e1 ";
if(x.equals(343)) s += ".e2 ";
Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));
if(s1 == 7) s += "=s ";
if(s1 < new Integer(7+1)) s += "fly "; System.out.println(s); } } Which of the following will be included in the output String s? (Choose all that apply.) A. .e1 B. .e2 C. =s D. fly E. None of the above F. Compilation fails G. An exception is thrown at runtime Question 4:
Given:
import java.io.*;
class Engine { }
public class Ferrari implements Serializable {
private Engine k = new Engine();
public static void main(String[] args) {
Ferrari c = new Ferrari();
c.serializeIt(c);
}
void serializeIt(Ferrari c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(c);
os.close();
System.out.println("done");
} catch (Exception x) {System.out.println("exc"); }
}
}
What is the result? (Choose all that apply.)
A. exc
B. done
C. Compilation fails
D. Exactly one object is serialized
E. Exactly two objects are serialized
Question 5:
Given:
import java.io.*;
public class SerializeTest {
public static void main(String[] args) {
SplSerialTest s = new SplSerialTest();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myTestFile"));
SplSerialTest s2 = (SplSerialTest)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SplSerialTest implements Serializable {
transient int y = 7;
static int z = 9;
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output is 10 0 9
C. The output is 10 0 10
D. The output is 10 7 9
E. The output is 10 7 10
F. In order to alter the standard deserialization process you would implement the readObject() method in SplSerialTest
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SplSerialTest
Question 6:
Given:
3. public class TestStrings {
4. public static void main(String[] args) {
5. String s1 = "abc";
6. String s2 = s1;
7. s1 += "d";
8. System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10. StringBuffer sb1 = new StringBuffer("abc");
11. StringBuffer sb2 = sb1;
12. sb1.append("d");
13. System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The first line of output is abc abc true
C. The first line of output is abc abc false
D. The first line of output is abcd abc false
E. The second line of output is abcd abc false
F. The second line of output is abcd abcd true
G. The second line of output is abcd abcd false
Question 7:
Given:
3. import java.io.*;
4. public class TestReader {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myTestFile.txt");
9. BufferedReader br = new BufferedReader(fr);
10. while((s = br.readLine()) != null)
11. System.out.println(s);
12. br.flush();
13. } catch (IOException e) { System.out.println("io error"); }
16. }
17. }
And given that myTestFile.txt contains the following two lines of data:
ab
cd
What is the result?
A. ab
B. abcd
C. ab
D. cd
E. a
F. b
G. c
H. d
I. Compilation fails
Question 8:
Given:
3. import java.io.*;
4. public class TestConsole {
5. public static void main(String[] args) {
6. Console c = System.console();
7. String u = c.readLine("%s", "username: ");
8. System.out.println("hello " + u);
9. String pw;
10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
11. // check for valid password
12. }
13. }
If line 6 creates a valid Console object, and if the user enters rocky as a username and 1234 as a password, what is the result? (Choose all that apply.)
A. username:
B. password:
C. username: rocky
D. password:
E. username: rocky
F. password: 1234
G. Compilation fails
H. An exception is thrown at runtime
Question 9:
Given:
3. import java.io.*;
4. class Automobile { }
5. class Engine { }
6. class Car extends Automobile implements Serializable { }
7. class Ferrari extends Car { }
8. class Lamborghini extends Car {
9. Engine w = new Engine();
10. }
Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ferrari
C. Lamborghini
D. Engine
E. Automobile
Question 10:
Given:
3. import java.text.*;
4. public class TestNumbers {
5. public static void main(String[] args) {
6. String s = "987.123456";
7. double d = 987.123456d;
8. NumberFormat nf = NumberFormat.getInstance();
9. nf.setMaximumFractionDigits(5);
10. System.out.println(nf.format(d) + " ");
11. try {
12. System.out.println(nf.parse(s));
13. } catch (Exception e) { System.out.println("got exc"); }
14. }
15. }
Which are true? (Choose all that apply.)
A. The output is 987.12345 987.12345
B. The output is 987.12346 987.12345
C. The output is 987.12345 987.123456
D. The output is 987.12346 987.123456
E. The try/catch block is unnecessary
F. The code compiles and runs without exception
G. The invocation of parse() must be placed within a try/catch block
Question 11:
Given:
3. import java.util.*;
4. public class TestScanner {
5. public static void main(String[] args) {
6. String input = "1 2 a 3 45 6";
7. Scanner sc = new Scanner(input);
8. int x = 0;
9. do {
10. x = sc.nextInt();
11. System.out.print(x + " ");
12. } while (x!=0);
13. }
14. }
What is the result?
A. 1 2
B. 1 2 3 45 6
C. 1 2 3 4 5 6
D. 1 2 a 3 45 6
E. Compilation fails
F. 1 2 followed by an exception
Question 12:
Given:
3. import java.util.regex.*;
4. public class TestPatterns {
5. public static void main(String[] args) {
6. Pattern p = Pattern.compile(args[0]);
7. Matcher m = p.matcher(args[1]);
8. int count = 0;
9. while(m.find())
10. count++;
11. System.out.print(count);
12. }
13. }
And given the command line invocation:
java TestPatterns "\d+" ab2c4d67
What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails
Answers:
Answer 1:
E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The start() method returns the starting position of the previous match because, again, we said find 0 to many occurrences.
Answer 2:
C is correct. It’s okay for a class to implement Serializable even if its superclass doesn’t. However, when you deserialize such an object, the non-serializable superclass must run its constructor. Remember, constructors don’t run on deserialized classes that implement Serializable
Answer 3:
B, C, and D are correct. Remember, that the equals() method for the integer wrappers will only return true if the two primitive types and the two values are equal. With C, it’s okay to unbox and use ==. For D, it’s okay to create a wrapper object with an expression, and unbox it for comparison with a primitive.
Remember that A is using the equals() method to try to compare two different types.
Answer 4:
A is correct. An instance of type Ferrari Has-a Engine. Because Engine doesn’t implement Serializable, any attempt to serialize an instance of Ferrari will cause an exception to be thrown.
If Engine did implement Serializable then two objects would have been serialized.
Answer 5:
C and F are correct. C is correct because static and transient variables are not serialized when an object is serialized. F is a valid statement.
G is incorrect because you don’t implement the defaultReadObject() method, you call it from within the readObject() method, along with any custom read operations your class needs.
Answer 6:
D and F are correct. While String objects are immutable, references to Strings are mutable. The code s1 += "d"; creates a new String object. StringBuffer objects are mutable, so the append() is changing the single StringBuffer object to which both StringBuffer references refer
Answer 7:
I is correct. Readers don’t have flush() methods. So, compilation would fail
Answer 8:
G is correct. The code compilation fails because the readPassword method returns a character array while the pw variable is a String
Answer 9:
A and B are correct. Lamborghini instances cannot be serialized because they “have” an instance of Engine, which is not serializable. Automobile instances cannot be serialized even though the subclass Car can be.
Answer 10:
D, F, and G are correct. The setMaximumFractionDigits() applies to the formatting but not the parsing. The try/catch block is placed appropriately. This one might scare you into thinking that you’ll need to memorize more than you really do. If you can remember that you’re formatting the number and parsing the string you should be fine for the exam.
Answer 11:
F is correct. The nextXxx() methods are typically invoked after a call to a hasNextXxx(), which determines whether the next token is of the correct type.
Answer 12:
B is correct. The “\d” metacharacter looks for digits, and the + quantifier says look for “one or more” occurrences. The find() method will find three sets of one or more consecutive digits: 2, 4, and 67.
Previous Chapter: Quick Review - Chapters 32 to 37
Next Chapter: Chapter 38 - Overriding toString(), hashCode() and equals() Methods
Question 1:
Given:
import java.util.regex.*;
class TestRegex {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}
And the command line:
java TestRegex "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails
Question 2:
Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class MusicPlayer extends Player implements Serializable {
MusicPlayer() { System.out.print("c"); }
public static void main(String[] args) {
MusicPlayer c1 = new MusicPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
MusicPlayer c2 = (MusicPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
What is the result?
A. pc
B. pcc
C. pcp
D. pcpc
E. Compilation fails
F. An exception is thrown at runtime
Question 3:
Given:
class Test {
public static void main(String[] args) {
String s = "-";
Integer x = 343;
long L343 = 343L;
if(x.equals(L343)) s += ".e1 ";
if(x.equals(343)) s += ".e2 ";
Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));
if(s1 == 7) s += "=s ";
if(s1 < new Integer(7+1)) s += "fly "; System.out.println(s); } } Which of the following will be included in the output String s? (Choose all that apply.) A. .e1 B. .e2 C. =s D. fly E. None of the above F. Compilation fails G. An exception is thrown at runtime Question 4:
Given:
import java.io.*;
class Engine { }
public class Ferrari implements Serializable {
private Engine k = new Engine();
public static void main(String[] args) {
Ferrari c = new Ferrari();
c.serializeIt(c);
}
void serializeIt(Ferrari c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(c);
os.close();
System.out.println("done");
} catch (Exception x) {System.out.println("exc"); }
}
}
What is the result? (Choose all that apply.)
A. exc
B. done
C. Compilation fails
D. Exactly one object is serialized
E. Exactly two objects are serialized
Question 5:
Given:
import java.io.*;
public class SerializeTest {
public static void main(String[] args) {
SplSerialTest s = new SplSerialTest();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myTestFile"));
SplSerialTest s2 = (SplSerialTest)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SplSerialTest implements Serializable {
transient int y = 7;
static int z = 9;
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output is 10 0 9
C. The output is 10 0 10
D. The output is 10 7 9
E. The output is 10 7 10
F. In order to alter the standard deserialization process you would implement the readObject() method in SplSerialTest
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SplSerialTest
Question 6:
Given:
3. public class TestStrings {
4. public static void main(String[] args) {
5. String s1 = "abc";
6. String s2 = s1;
7. s1 += "d";
8. System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10. StringBuffer sb1 = new StringBuffer("abc");
11. StringBuffer sb2 = sb1;
12. sb1.append("d");
13. System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The first line of output is abc abc true
C. The first line of output is abc abc false
D. The first line of output is abcd abc false
E. The second line of output is abcd abc false
F. The second line of output is abcd abcd true
G. The second line of output is abcd abcd false
Question 7:
Given:
3. import java.io.*;
4. public class TestReader {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myTestFile.txt");
9. BufferedReader br = new BufferedReader(fr);
10. while((s = br.readLine()) != null)
11. System.out.println(s);
12. br.flush();
13. } catch (IOException e) { System.out.println("io error"); }
16. }
17. }
And given that myTestFile.txt contains the following two lines of data:
ab
cd
What is the result?
A. ab
B. abcd
C. ab
D. cd
E. a
F. b
G. c
H. d
I. Compilation fails
Question 8:
Given:
3. import java.io.*;
4. public class TestConsole {
5. public static void main(String[] args) {
6. Console c = System.console();
7. String u = c.readLine("%s", "username: ");
8. System.out.println("hello " + u);
9. String pw;
10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
11. // check for valid password
12. }
13. }
If line 6 creates a valid Console object, and if the user enters rocky as a username and 1234 as a password, what is the result? (Choose all that apply.)
A. username:
B. password:
C. username: rocky
D. password:
E. username: rocky
F. password: 1234
G. Compilation fails
H. An exception is thrown at runtime
Question 9:
Given:
3. import java.io.*;
4. class Automobile { }
5. class Engine { }
6. class Car extends Automobile implements Serializable { }
7. class Ferrari extends Car { }
8. class Lamborghini extends Car {
9. Engine w = new Engine();
10. }
Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ferrari
C. Lamborghini
D. Engine
E. Automobile
Question 10:
Given:
3. import java.text.*;
4. public class TestNumbers {
5. public static void main(String[] args) {
6. String s = "987.123456";
7. double d = 987.123456d;
8. NumberFormat nf = NumberFormat.getInstance();
9. nf.setMaximumFractionDigits(5);
10. System.out.println(nf.format(d) + " ");
11. try {
12. System.out.println(nf.parse(s));
13. } catch (Exception e) { System.out.println("got exc"); }
14. }
15. }
Which are true? (Choose all that apply.)
A. The output is 987.12345 987.12345
B. The output is 987.12346 987.12345
C. The output is 987.12345 987.123456
D. The output is 987.12346 987.123456
E. The try/catch block is unnecessary
F. The code compiles and runs without exception
G. The invocation of parse() must be placed within a try/catch block
Question 11:
Given:
3. import java.util.*;
4. public class TestScanner {
5. public static void main(String[] args) {
6. String input = "1 2 a 3 45 6";
7. Scanner sc = new Scanner(input);
8. int x = 0;
9. do {
10. x = sc.nextInt();
11. System.out.print(x + " ");
12. } while (x!=0);
13. }
14. }
What is the result?
A. 1 2
B. 1 2 3 45 6
C. 1 2 3 4 5 6
D. 1 2 a 3 45 6
E. Compilation fails
F. 1 2 followed by an exception
Question 12:
Given:
3. import java.util.regex.*;
4. public class TestPatterns {
5. public static void main(String[] args) {
6. Pattern p = Pattern.compile(args[0]);
7. Matcher m = p.matcher(args[1]);
8. int count = 0;
9. while(m.find())
10. count++;
11. System.out.print(count);
12. }
13. }
And given the command line invocation:
java TestPatterns "\d+" ab2c4d67
What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails
Answers:
Answer 1:
E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The start() method returns the starting position of the previous match because, again, we said find 0 to many occurrences.
Answer 2:
C is correct. It’s okay for a class to implement Serializable even if its superclass doesn’t. However, when you deserialize such an object, the non-serializable superclass must run its constructor. Remember, constructors don’t run on deserialized classes that implement Serializable
Answer 3:
B, C, and D are correct. Remember, that the equals() method for the integer wrappers will only return true if the two primitive types and the two values are equal. With C, it’s okay to unbox and use ==. For D, it’s okay to create a wrapper object with an expression, and unbox it for comparison with a primitive.
Remember that A is using the equals() method to try to compare two different types.
Answer 4:
A is correct. An instance of type Ferrari Has-a Engine. Because Engine doesn’t implement Serializable, any attempt to serialize an instance of Ferrari will cause an exception to be thrown.
If Engine did implement Serializable then two objects would have been serialized.
Answer 5:
C and F are correct. C is correct because static and transient variables are not serialized when an object is serialized. F is a valid statement.
G is incorrect because you don’t implement the defaultReadObject() method, you call it from within the readObject() method, along with any custom read operations your class needs.
Answer 6:
D and F are correct. While String objects are immutable, references to Strings are mutable. The code s1 += "d"; creates a new String object. StringBuffer objects are mutable, so the append() is changing the single StringBuffer object to which both StringBuffer references refer
Answer 7:
I is correct. Readers don’t have flush() methods. So, compilation would fail
Answer 8:
G is correct. The code compilation fails because the readPassword method returns a character array while the pw variable is a String
Answer 9:
A and B are correct. Lamborghini instances cannot be serialized because they “have” an instance of Engine, which is not serializable. Automobile instances cannot be serialized even though the subclass Car can be.
Answer 10:
D, F, and G are correct. The setMaximumFractionDigits() applies to the formatting but not the parsing. The try/catch block is placed appropriately. This one might scare you into thinking that you’ll need to memorize more than you really do. If you can remember that you’re formatting the number and parsing the string you should be fine for the exam.
Answer 11:
F is correct. The nextXxx() methods are typically invoked after a call to a hasNextXxx(), which determines whether the next token is of the correct type.
Answer 12:
B is correct. The “\d” metacharacter looks for digits, and the + quantifier says look for “one or more” occurrences. The find() method will find three sets of one or more consecutive digits: 2, 4, and 67.
Previous Chapter: Quick Review - Chapters 32 to 37
Next Chapter: Chapter 38 - Overriding toString(), hashCode() and equals() Methods
Labels:
java scjp,
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self assement,
self assessment scjp,
self test,
self test scjp
| Reactions: |
Monday, February 14, 2011
Self test – Chapters 27 to 31
Questions:
Question 1:
Given two files:
1. class One {
2. public static void main(String[] args) {
3. int assert = 0;
4. }
5. }
1. class Two {
2. public static void main(String[] args) {
3. assert(false);
4. }
5. }
And the four command-line invocations:
javac -source 1.3 One.java
javac -source 1.4 One.java
javac -source 1.3 Two.java
javac -source 1.4 Two.java
What is the result? (Choose all that apply.)
A. Only one compilation will succeed
B. Exactly two compilations will succeed
C. Exactly three compilations will succeed
D. All four compilations will succeed
E. No compiler warnings will be produced
F. At least one compiler warning will be produced
Question 2:
Given:
class Plane {
static String s = "-";
public static void main(String[] args) {
new Plane().s1();
System.out.println(s);
}
void s1() {
try { s2(); }
catch (Exception e) { s += "c"; }
}
void s2() throws Exception {
s3(); s += "2";
s3(); s += "2b";
}
void s3() throws Exception {
throw new Exception();
}
}
What is the result?
A. -
B. -c
C. -c2
D. -2c
E. -c22b
F. -2c2b
G. -2c2bc
H. Compilation fails
Question 3:
Given:
try { int x = Integer.parseInt("two"); }
Which could be used to create an appropriate catch block? (Choose all that apply.)
A. ClassCastException
B. IllegalStateException
C. NumberFormatException
D. IllegalArgumentException
E. ExceptionInInitializerError
F. ArrayIndexOutOfBoundsException
Question 4:
Which are true? (Choose all that apply.)
A. It is appropriate to use assertions to validate arguments to methods marked public
B. It is appropriate to catch and handle assertion errors
C. It is NOT appropriate to use assertions to validate command-line arguments
D. It is appropriate to use assertions to generate alerts when you reach code that should not be reachable
E. It is NOT appropriate for assertions to change a program’s state
Question 5:
Given:
1. class TestLoops {
2. public static void main(String[] args) {
3. int[] x = {7,6,5,4,3,2,1};
4. // insert code here
5. System.out.print(y + " ");
6. }
7. }
8. }
Which, inserted independently at line 4, compiles? (Choose all that apply.)
A. for(int y : x) {
B. for(x : int y) {
C. int y = 0; for(y : x) {
D. for(int y=0, z=0; z < x.length; z++) { y = x[z];
E. for(int y=0, int z=0; z < x.length; z++) { y = x[z];
F. int y = 0; for(int z=0; z < x.length; z++) { y = x[z];
Question 6:
Given:
class Ostrich {
static String s = "-";
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
try { throw new Exception();
} catch (Exception ex) { s += "ic "; }
throw new Exception(); }
catch (Exception x) { s += "mc "; }
finally { s += "mf "; }
} finally { s += "of "; }
System.out.println(s);
} }
What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails
Question 7:
Given:
3. class SubException extends Exception { }
4. class SubSubException extends SubException { }
5.
6. public class CC { void doStuff() throws SubException { } }
7.
8. class CC2 extends CC { void doStuff() throws SubSubException { } }
9.
10. class CC3 extends CC { void doStuff() throws Exception { } }
11.
12. class CC4 extends CC { void doStuff(int x) throws Exception { } }
13.
14. class CC5 extends CC { void doStuff() { } }
What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 8
C. Compilation fails due to an error on line 10
D. Compilation fails due to an error on line 12
E. Compilation fails due to an error on line 14
Question 8:
Given:
3. public class TestLoops {
4. static int x = 7;
5. public static void main(String[] args) {
6. String s = "";
7. for(int y = 0; y < 3; y++) {
8. x++;
9. switch(x) {
10. case 8: s += "8 ";
11. case 9: s += "9 ";
12. case 10: { s+= "10 "; break; }
13. default: s += "d ";
14. case 13: s+= "13 ";
15. }
16. }
17. System.out.println(s);
18. }
19. static { x++; }
20. }
What is the result?
A. 9 10 d
B. 8 9 10 d
C. 9 10 10 d
D. 9 10 10 d 13
E. 8 9 10 10 d 13
F. 8 9 10 9 10 10 d 13
G. Compilation fails
Question 9:
Given:
3. class Limitless { }
4. public class Beyond extends Limitless {
5. static Integer i;
6. public static void main(String[] args) {
7. int sw = (int)(Math.random() * 3);
8. switch(sw) {
9. case 0: { for(int x = 10; x > 5; x++)
10. if(x > 10000000) x = 10;
11. break; }
12. case 1: { int y = 7 * i; break; }
13. case 2: { Limitless inf = new Beyond();
14. Beyond b = (Beyond)inf; }
15. }
16. }
17. }
And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception
Question 10:
Given:
3. public class Spears {
4. public static void main(String[] args) {
5. int[] ia = {1,3,5,7,9};
6. for(int x : ia) {
7. for(int j = 0; j < 3; j++) {
8. if(x > 4 && x < 8) continue;
9. System.out.print(" " + x);
10. if(j == 1) break;
11. continue;
12. }
13. continue;
14. }
15. }
16. }
What is the result?
A. 1 3 9
B. 5 5 7 7
C. 1 3 3 9 9
D. 1 1 3 3 9 9
E. 1 1 1 3 3 3 9 9 9
F. Compilation fails
Question 11:
Given:
3. public class OverAndOut {
4. static String s = "";
5. public static void main(String[] args) {
6. try {
7. s += "1";
8. throw new Exception();
9. } catch (Exception e) { s += "2";
10. } finally { s += "3"; doStuff(); s += "4";
11. }
12. System.out.println(s);
13. }
14. static void doStuff() { int x = 0; int y = 7/x; }
15. }
What is the result?
A. 12
B. 13
C. 123
D. 1234
E. Compilation fails
F. 123 followed by an exception
G. 1234 followed by an exception
H. An exception is thrown with no other output
Question 12:
Given:
3. public class Breeze {
4. public static void main(String[] args) {
5. foreach:
6. for(int j=0; j<5; j++) {
7. for(int k=0; k< 3; k++) {
8. System.out.print(" " + j);
9. if(j==3 && k==1) break foreach;
10. if(j==0 || j==2) break;
11. }
12. }
13. }
14. }
What is the result?
A. 0 1 2 3
B. 1 1 1 3 3
C. 0 1 1 1 2 3 3
D. 1 1 1 3 3 4 4 4
E. 0 1 1 1 2 3 3 4 4 4
F. Compilation fails
Question 13:
Given:
3. public class GotYa {
4. public static void main(String[] args) {
5. // insert code here
6.
7. }
8. void go() {
9. go();
10. }
11. }
And given the following three code fragments:
I. new GotYa().go();
II. try { new GotYa().go(); }
catch (Error e) { System.out.println("ouch"); }
III. try { new GotYa().go(); }
catch (Exception e) { System.out.println("ouch"); }
When fragments I - III are added, independently, at line 5, which are true? (Choose all that apply.)
A. Some will not compile
B. They will all compile
C. All will complete normally
D. None will complete normally
E. Only one will complete normally
F. Two of them will complete normally
Question 14:
Given:
3. public class Funny {
4. public static void main(String[] args) {
5. int j = 7;
6. assert(++j > 7);
7. assert(++j > 8): "hi";
8. assert(j > 10): j=12;
9. assert(j==12): doStuff();
10. assert(j==12): new Funny();
11. }
12. static void doStuff() { }
13. }
Which are true? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 6
C. Compilation fails due to an error on line 7
D. Compilation fails due to an error on line 8
E. Compilation fails due to an error on line 9
F. Compilation fails due to an error on line 10
Question 15:
Given:
1. public class ThrowMe {
2. // insert code here
3. int x = 0;
4. System.out.println(7/x);
5. }
6. }
And given the following four code fragments:
I. public static void main(String[] args) {
II. public static void main(String[] args) throws Exception {
III. public static void main(String[] args) throws IOException {
IV. public static void main(String[] args) throws RuntimeException {
If the four fragments are inserted independently at line 4, which are true? (Choose all that apply.)
A. All four will compile and execute without exception
B. All four will compile and execute and throw an exception
C. Some, but not all, will compile and execute without exception
D. Some, but not all, will compile and execute and throw an exception
E. When considering fragments II, III, and IV, of those that will compile, adding a try/catch block around line 6 will cause compilation to fail
Answers:
Answer 1:
B and F are correct. Class One will compile (and issue a warning) using the 1.3 flag, and class Two will compile using the 1.4 flag.
A, C, D, and E are incorrect based on the above.
Answer 2:
B is correct. Once s3() throws the exception to s2(), s2() throws it to s1(), and no more of s2()’s code will be executed.
A, C, D, E, F, G, and H are incorrect based on the above.
Answer 3:
C and D are correct. Integer.parseInt can throw a NumberFormatException, and IllegalArgumentException is its superclass (i.e., a broader exception).
A, B, E, and F are not in NumberFormatException’s class hierarchy
Answer 4:
C, D, and E are correct statements.
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so.
Answer 5:
A, D, and F are correct. A is an example of the enhanced for loop. D and F are examples of the basic for loop.
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement.
Answer 6:
E is correct. There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block runs.
A, B, C, D, and F are incorrect based on the above.
Answer 7:
C is correct. An overriding method cannot throw a broader exception than the method it’s overriding. Class CC4’s method is an overload, not an override.
A, B, D, and E are incorrect based on the above.
Answer 8:
D is correct. Did you catch the static initializer block? Remember that switches work on “fall-thru” logic, and that fall-thru logic also applies to the default case, which is used when no other case matches.
A, B, C, E, F, and G are incorrect based on the above.
Answer 9:
D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will initiate an endless loop, not a stack overflow. Case 2’s downcast will not cause an exception.
A, B, C, E, and G are incorrect based on the above.
Answer 10:
D is correct. The basic rule for unlabeled continue statements is that the current iteration stops early and execution jumps to the next iteration. The last two continue statements are redundant!
A, B, C, E, and F are incorrect based on the above.
Answer 11:
H is correct. It’s true that the value of String s is 123 at the time that the divide-by-zero exception is thrown, but finally() is not guaranteed to complete, and in this case finally() never completes, so the System.out.println (S.O.P.) never executes.
A, B, C, D, E, F, and G are incorrect based on the above.
Answer 12:
C is correct. A break breaks out of the current innermost loop and continues. A labeled break breaks out of and terminates the current loops.
A, B, D, E, and F are incorrect based on the above.
Answer 13:
B and E are correct. First off, go() is a badly designed recursive method, guaranteed to cause a StackOverflowError. Since Exception is not a superclass of Error, catching an Exception will not help handle an Error, so fragment III will not complete normally. Only fragment II will catch the Error.
A, C, D, and F are incorrect based on the above.
Answer 14:
E is correct. When an assert statement has two expressions, the second expression must return a value. The only two-expression assert statement that doesn’t return a value is on line 9.
A, B, C, D, and F are incorrect based on the above
Answer 15:
D is correct. This is kind of sneaky, but remember that we’re trying to toughen you up for the real exam. If you’re going to throw an IOException, you have to import the java.io package or declare the exception with a fully qualified name.
E is incorrect because it’s okay to both handle and declare an exception. A, B, and C are incorrect based on the above.
Previous Chapter: Quick Review - Chapters 27 to 31
Next Chapter: Chapter 32 - String Class
Question 1:
Given two files:
1. class One {
2. public static void main(String[] args) {
3. int assert = 0;
4. }
5. }
1. class Two {
2. public static void main(String[] args) {
3. assert(false);
4. }
5. }
And the four command-line invocations:
javac -source 1.3 One.java
javac -source 1.4 One.java
javac -source 1.3 Two.java
javac -source 1.4 Two.java
What is the result? (Choose all that apply.)
A. Only one compilation will succeed
B. Exactly two compilations will succeed
C. Exactly three compilations will succeed
D. All four compilations will succeed
E. No compiler warnings will be produced
F. At least one compiler warning will be produced
Question 2:
Given:
class Plane {
static String s = "-";
public static void main(String[] args) {
new Plane().s1();
System.out.println(s);
}
void s1() {
try { s2(); }
catch (Exception e) { s += "c"; }
}
void s2() throws Exception {
s3(); s += "2";
s3(); s += "2b";
}
void s3() throws Exception {
throw new Exception();
}
}
What is the result?
A. -
B. -c
C. -c2
D. -2c
E. -c22b
F. -2c2b
G. -2c2bc
H. Compilation fails
Question 3:
Given:
try { int x = Integer.parseInt("two"); }
Which could be used to create an appropriate catch block? (Choose all that apply.)
A. ClassCastException
B. IllegalStateException
C. NumberFormatException
D. IllegalArgumentException
E. ExceptionInInitializerError
F. ArrayIndexOutOfBoundsException
Question 4:
Which are true? (Choose all that apply.)
A. It is appropriate to use assertions to validate arguments to methods marked public
B. It is appropriate to catch and handle assertion errors
C. It is NOT appropriate to use assertions to validate command-line arguments
D. It is appropriate to use assertions to generate alerts when you reach code that should not be reachable
E. It is NOT appropriate for assertions to change a program’s state
Question 5:
Given:
1. class TestLoops {
2. public static void main(String[] args) {
3. int[] x = {7,6,5,4,3,2,1};
4. // insert code here
5. System.out.print(y + " ");
6. }
7. }
8. }
Which, inserted independently at line 4, compiles? (Choose all that apply.)
A. for(int y : x) {
B. for(x : int y) {
C. int y = 0; for(y : x) {
D. for(int y=0, z=0; z < x.length; z++) { y = x[z];
E. for(int y=0, int z=0; z < x.length; z++) { y = x[z];
F. int y = 0; for(int z=0; z < x.length; z++) { y = x[z];
Question 6:
Given:
class Ostrich {
static String s = "-";
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
try { throw new Exception();
} catch (Exception ex) { s += "ic "; }
throw new Exception(); }
catch (Exception x) { s += "mc "; }
finally { s += "mf "; }
} finally { s += "of "; }
System.out.println(s);
} }
What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails
Question 7:
Given:
3. class SubException extends Exception { }
4. class SubSubException extends SubException { }
5.
6. public class CC { void doStuff() throws SubException { } }
7.
8. class CC2 extends CC { void doStuff() throws SubSubException { } }
9.
10. class CC3 extends CC { void doStuff() throws Exception { } }
11.
12. class CC4 extends CC { void doStuff(int x) throws Exception { } }
13.
14. class CC5 extends CC { void doStuff() { } }
What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 8
C. Compilation fails due to an error on line 10
D. Compilation fails due to an error on line 12
E. Compilation fails due to an error on line 14
Question 8:
Given:
3. public class TestLoops {
4. static int x = 7;
5. public static void main(String[] args) {
6. String s = "";
7. for(int y = 0; y < 3; y++) {
8. x++;
9. switch(x) {
10. case 8: s += "8 ";
11. case 9: s += "9 ";
12. case 10: { s+= "10 "; break; }
13. default: s += "d ";
14. case 13: s+= "13 ";
15. }
16. }
17. System.out.println(s);
18. }
19. static { x++; }
20. }
What is the result?
A. 9 10 d
B. 8 9 10 d
C. 9 10 10 d
D. 9 10 10 d 13
E. 8 9 10 10 d 13
F. 8 9 10 9 10 10 d 13
G. Compilation fails
Question 9:
Given:
3. class Limitless { }
4. public class Beyond extends Limitless {
5. static Integer i;
6. public static void main(String[] args) {
7. int sw = (int)(Math.random() * 3);
8. switch(sw) {
9. case 0: { for(int x = 10; x > 5; x++)
10. if(x > 10000000) x = 10;
11. break; }
12. case 1: { int y = 7 * i; break; }
13. case 2: { Limitless inf = new Beyond();
14. Beyond b = (Beyond)inf; }
15. }
16. }
17. }
And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception
Question 10:
Given:
3. public class Spears {
4. public static void main(String[] args) {
5. int[] ia = {1,3,5,7,9};
6. for(int x : ia) {
7. for(int j = 0; j < 3; j++) {
8. if(x > 4 && x < 8) continue;
9. System.out.print(" " + x);
10. if(j == 1) break;
11. continue;
12. }
13. continue;
14. }
15. }
16. }
What is the result?
A. 1 3 9
B. 5 5 7 7
C. 1 3 3 9 9
D. 1 1 3 3 9 9
E. 1 1 1 3 3 3 9 9 9
F. Compilation fails
Question 11:
Given:
3. public class OverAndOut {
4. static String s = "";
5. public static void main(String[] args) {
6. try {
7. s += "1";
8. throw new Exception();
9. } catch (Exception e) { s += "2";
10. } finally { s += "3"; doStuff(); s += "4";
11. }
12. System.out.println(s);
13. }
14. static void doStuff() { int x = 0; int y = 7/x; }
15. }
What is the result?
A. 12
B. 13
C. 123
D. 1234
E. Compilation fails
F. 123 followed by an exception
G. 1234 followed by an exception
H. An exception is thrown with no other output
Question 12:
Given:
3. public class Breeze {
4. public static void main(String[] args) {
5. foreach:
6. for(int j=0; j<5; j++) {
7. for(int k=0; k< 3; k++) {
8. System.out.print(" " + j);
9. if(j==3 && k==1) break foreach;
10. if(j==0 || j==2) break;
11. }
12. }
13. }
14. }
What is the result?
A. 0 1 2 3
B. 1 1 1 3 3
C. 0 1 1 1 2 3 3
D. 1 1 1 3 3 4 4 4
E. 0 1 1 1 2 3 3 4 4 4
F. Compilation fails
Question 13:
Given:
3. public class GotYa {
4. public static void main(String[] args) {
5. // insert code here
6.
7. }
8. void go() {
9. go();
10. }
11. }
And given the following three code fragments:
I. new GotYa().go();
II. try { new GotYa().go(); }
catch (Error e) { System.out.println("ouch"); }
III. try { new GotYa().go(); }
catch (Exception e) { System.out.println("ouch"); }
When fragments I - III are added, independently, at line 5, which are true? (Choose all that apply.)
A. Some will not compile
B. They will all compile
C. All will complete normally
D. None will complete normally
E. Only one will complete normally
F. Two of them will complete normally
Question 14:
Given:
3. public class Funny {
4. public static void main(String[] args) {
5. int j = 7;
6. assert(++j > 7);
7. assert(++j > 8): "hi";
8. assert(j > 10): j=12;
9. assert(j==12): doStuff();
10. assert(j==12): new Funny();
11. }
12. static void doStuff() { }
13. }
Which are true? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 6
C. Compilation fails due to an error on line 7
D. Compilation fails due to an error on line 8
E. Compilation fails due to an error on line 9
F. Compilation fails due to an error on line 10
Question 15:
Given:
1. public class ThrowMe {
2. // insert code here
3. int x = 0;
4. System.out.println(7/x);
5. }
6. }
And given the following four code fragments:
I. public static void main(String[] args) {
II. public static void main(String[] args) throws Exception {
III. public static void main(String[] args) throws IOException {
IV. public static void main(String[] args) throws RuntimeException {
If the four fragments are inserted independently at line 4, which are true? (Choose all that apply.)
A. All four will compile and execute without exception
B. All four will compile and execute and throw an exception
C. Some, but not all, will compile and execute without exception
D. Some, but not all, will compile and execute and throw an exception
E. When considering fragments II, III, and IV, of those that will compile, adding a try/catch block around line 6 will cause compilation to fail
Answers:
Answer 1:
B and F are correct. Class One will compile (and issue a warning) using the 1.3 flag, and class Two will compile using the 1.4 flag.
A, C, D, and E are incorrect based on the above.
Answer 2:
B is correct. Once s3() throws the exception to s2(), s2() throws it to s1(), and no more of s2()’s code will be executed.
A, C, D, E, F, G, and H are incorrect based on the above.
Answer 3:
C and D are correct. Integer.parseInt can throw a NumberFormatException, and IllegalArgumentException is its superclass (i.e., a broader exception).
A, B, E, and F are not in NumberFormatException’s class hierarchy
Answer 4:
C, D, and E are correct statements.
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so.
Answer 5:
A, D, and F are correct. A is an example of the enhanced for loop. D and F are examples of the basic for loop.
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement.
Answer 6:
E is correct. There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block runs.
A, B, C, D, and F are incorrect based on the above.
Answer 7:
C is correct. An overriding method cannot throw a broader exception than the method it’s overriding. Class CC4’s method is an overload, not an override.
A, B, D, and E are incorrect based on the above.
Answer 8:
D is correct. Did you catch the static initializer block? Remember that switches work on “fall-thru” logic, and that fall-thru logic also applies to the default case, which is used when no other case matches.
A, B, C, E, F, and G are incorrect based on the above.
Answer 9:
D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will initiate an endless loop, not a stack overflow. Case 2’s downcast will not cause an exception.
A, B, C, E, and G are incorrect based on the above.
Answer 10:
D is correct. The basic rule for unlabeled continue statements is that the current iteration stops early and execution jumps to the next iteration. The last two continue statements are redundant!
A, B, C, E, and F are incorrect based on the above.
Answer 11:
H is correct. It’s true that the value of String s is 123 at the time that the divide-by-zero exception is thrown, but finally() is not guaranteed to complete, and in this case finally() never completes, so the System.out.println (S.O.P.) never executes.
A, B, C, D, E, F, and G are incorrect based on the above.
Answer 12:
C is correct. A break breaks out of the current innermost loop and continues. A labeled break breaks out of and terminates the current loops.
A, B, D, E, and F are incorrect based on the above.
Answer 13:
B and E are correct. First off, go() is a badly designed recursive method, guaranteed to cause a StackOverflowError. Since Exception is not a superclass of Error, catching an Exception will not help handle an Error, so fragment III will not complete normally. Only fragment II will catch the Error.
A, C, D, and F are incorrect based on the above.
Answer 14:
E is correct. When an assert statement has two expressions, the second expression must return a value. The only two-expression assert statement that doesn’t return a value is on line 9.
A, B, C, D, and F are incorrect based on the above
Answer 15:
D is correct. This is kind of sneaky, but remember that we’re trying to toughen you up for the real exam. If you’re going to throw an IOException, you have to import the java.io package or declare the exception with a fully qualified name.
E is incorrect because it’s okay to both handle and declare an exception. A, B, and C are incorrect based on the above.
Previous Chapter: Quick Review - Chapters 27 to 31
Next Chapter: Chapter 32 - String Class
Labels:
java scjp,
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self assement,
self assessment scjp,
self test,
self test scjp
| Reactions: |
Friday, February 4, 2011
Self Test: Chapters 15 to 21
Self Test Questions:
Question 1
Given:
class GCTest {
Short story = 200;
GCTest go(GCTest cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
GCTest c1 = new GCTest();
GCTest c2 = new GCTest();
GCTest c3 = c1.go(c2);
c1 = null;
// do Stuff
} }
When // doStuff is reached, how many objects are eligible for GC?
A. 0
B. 1
C. 2
D. Compilation fails
E. It is not possible to know
F. An exception is thrown at runtime
Question 2
Given:
class Army {
String invade(short guns) { return "a few"; }
String invade(short... guns) { return "many"; }
}
class Defend {
public static void main(String [] args) {
System.out.println(new Army().invade(7));
}
}
What is the result?
A. many
B. a few
C. Compilation fails
D. The output is not predictable
E. An exception is thrown at runtime
Question 3
Given:
1. class ArrayTest {
2. public static void main(String[] args) {
3. int[][] a = {{1,2,}, {3,4}};
4. int[] b = (int[]) a[1];
5. Object o1 = a;
6. int[][] a2 = (int[][]) o1;
7. int[] b2 = (int[]) o1;
8. System.out.println(b[1]);
9. } }
What is the result?
A. 2
B. 4
C. An exception is thrown at runtime
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 5
F. Compilation fails due to an error on line 6
G. Compilation fails due to an error on line 7
Question 4
Given:
class Driver {
Driver() { }
Driver(Driver m) { m1 = m; }
Driver m1;
public static void main(String[] args) {
Driver m2 = new Driver();
Driver m3 = new Driver(m2); m3.go();
Driver m4 = m3.m1; m4.go();
Driver m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}
What is the result?
A. hi
B. hi hi
C. hi hi hi
D. Compilation fails
E. hi, followed by an exception
F. hi hi, followed by an exception
Question 5
Given:
class Kill {
int x = 5;
public static void main(String[] args) {
final Kill f1 = new Kill();
Kill f2 = new Kill();
Kill f3 = KillSwitch(f1,f2);
System.out.println((f1 == f3) + " " + (f1.x == f3.x));
}
static Kill KillSwitch(Kill x, Kill y) {
final Kill z = x;
z.x = 6;
return z;
} }
What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails
F. An exception is thrown at runtime
Question 6
Given:
class Car {
{ System.out.print("b1 "); }
public Car() { System.out.print("b2 "); }
}
class Ferrari extends Car {
static { System.out.print("r1 "); }
public Ferrari() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class F50 extends Ferrari {
public static void main(String[] args) {
System.out.print("pre ");
new F50();
System.out.println("F50 ");
}
}
What is the result?
A. pre b1 b2 r3 r2 F50
B. pre b2 b1 r2 r3 F50
C. pre b2 b1 r2 r3 F50 r1 r4
D. r1 r4 pre b1 b2 r3 r2 F50
E. r1 r4 pre b2 b1 r2 r3 F50
F. pre r1 r4 b1 b2 r3 r2 F50
G. pre r1 r4 b2 b1 r2 r3 F50
H. The order of output cannot be predicted
I. Compilation fails
Question 7
Given:
3. public class Oops {
4. static int Oops = 7;
5. public static void main(String[] args) {
6. new Oops().go(Oops);
7. System.out.print(" " + Oops);
8. }
9. void go(int Oops) {
10. Oops++;
11. for(int Oops = 3; Oops < 6; Oops++)
12. ;
13. System.out.print(" " + Oops);
14. }
15. }
What is the result?
A. 5 7
B. 5 8
C. 8 7
D. 8 8
E. Compilation fails
F. An exception is thrown at runtime
Question 8
Given:
3. public class Test {
4. static String s = "";
5. public static void main(String[] args) {
6. int x = 4; Boolean y = true; short[] sa = {1,2,3};
7. doSomething(x, y);
8. doSomething(x);
9. doSomething(sa, sa);
10. System.out.println(s);
11. }
12. static void doSomething(Object o) { s += "1"; }
13. static void doSomething(Object... o) { s += "2"; }
14. static void doSomething(Integer... i) { s += "3"; }
15. static void doSomething(Long L) { s += "4"; }
16. }
What is the result?
A. 212
B. 232
C. 234
D. 312
E. 332
F. 334
G. Compilation fails
Question 9
Given:
3. class TestGarbageCollection {
4. int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
5. }
6. public class Eggs {
7. public static void main(String[] args) {
8. TestGarbageCollection [] da = new TestGarbageCollection[3];
9. da[0] = new TestGarbageCollection();
10. TestGarbageCollection d = new TestGarbageCollection();
11. da[1] = d;
12. d = null;
13. da[1] = null;
14. // do stuff
15. }
16. }
Which two are true about the objects created within main(), and eligible for garbage collection when line 14 is reached?
A. Three objects were created
B. Four objects were created
C. Five objects were created
D. Zero objects are eligible for GC
E. One object is eligible for GC
F. Two objects are eligible for GC
G. Three objects are eligible for GC
Question 10
Given:
3. public class Test {
4. int x = 3;
5. public static void main(String[] args) {
6. new Test().go1();
7. }
8. void go1() {
9. int x;
10. go2(++x);
11. }
12. void go2(int y) {
13. int x = ++y;
14. System.out.println(x);
15. }
16. }
What is the result?
A. 2
B. 3
C. 4
D. 5
E. Compilation fails
F. An exception is thrown at runtime
Self Test - Answers:
Question 1:
C is correct. Only one GCTest object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
A, B, D, E, and F are incorrect based on the above
Question 2:
C is correct, compilation fails. The var-args declaration is fine, but invade takes a short, so the argument 7 needs to be cast to a short. With the cast, the answer is B, ‘a few’.
A, B, D, and E are incorrect based on the above.
Question 3:
C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][] not an int[]. If line 7 was removed, the output would be 4.
A, B, D, E, F, and G are incorrect based on the above
Question 4:
F is correct. The m2 object’s m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown
A, B, C, D, and E are incorrect based on the above
Question 5:
A is correct. The references f1, z, and f3 all refer to the same instance of Kill. The final modifier assures that a reference variable cannot be referred to a different object, but final doesn’t keep the object’s state from changing.
B, C, D, E, and F are incorrect based on the above
Question 6:
D is correct. Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down.
A, B, C, E, F, G, H, and I are incorrect based on the above.
Question 7:
E is correct. The parameter declared on line 9 is valid (although ugly), but the variable name Oops cannot be declared again on line 11 in the same scope as the declaration on line 9.
A, B, C, D, and F are incorrect based on the above
Question 8:
A is correct. It’s legal to autobox and then widen. The first call to doSomething() boxes the int to an Integer then passes two objects. The second call cannot widen and then box (making the Long method unusable), so it boxes the int to an Integer. As always, a var-args method will be chosen only if no non-var-arg method is possible. The third call is passing two objects—they are of type ‘short array.’
B, C, D, E, F, and G are incorrect based on the above
Question 9:
C and F are correct. da refers to an object of type “TestGarbageCollection array,” and each TestGarbageCollection object that is created comes with its own “int array” object. When line 14 is reached, only the second TestGarbageCollection object (and its “int array” object) are not reachable
A, B, D, E, and G are incorrect based on the above.
Question 10:
E is correct. In go1() the local variable x is not initialized
A, B, C, D, and F are incorrect based on the above.
Previous Chapter: Quick Review - Chapters 15 to 21
Next Chapter: Chapter 22: Assignment Operator
Question 1
Given:
class GCTest {
Short story = 200;
GCTest go(GCTest cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
GCTest c1 = new GCTest();
GCTest c2 = new GCTest();
GCTest c3 = c1.go(c2);
c1 = null;
// do Stuff
} }
When // doStuff is reached, how many objects are eligible for GC?
A. 0
B. 1
C. 2
D. Compilation fails
E. It is not possible to know
F. An exception is thrown at runtime
Question 2
Given:
class Army {
String invade(short guns) { return "a few"; }
String invade(short... guns) { return "many"; }
}
class Defend {
public static void main(String [] args) {
System.out.println(new Army().invade(7));
}
}
What is the result?
A. many
B. a few
C. Compilation fails
D. The output is not predictable
E. An exception is thrown at runtime
Question 3
Given:
1. class ArrayTest {
2. public static void main(String[] args) {
3. int[][] a = {{1,2,}, {3,4}};
4. int[] b = (int[]) a[1];
5. Object o1 = a;
6. int[][] a2 = (int[][]) o1;
7. int[] b2 = (int[]) o1;
8. System.out.println(b[1]);
9. } }
What is the result?
A. 2
B. 4
C. An exception is thrown at runtime
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 5
F. Compilation fails due to an error on line 6
G. Compilation fails due to an error on line 7
Question 4
Given:
class Driver {
Driver() { }
Driver(Driver m) { m1 = m; }
Driver m1;
public static void main(String[] args) {
Driver m2 = new Driver();
Driver m3 = new Driver(m2); m3.go();
Driver m4 = m3.m1; m4.go();
Driver m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}
What is the result?
A. hi
B. hi hi
C. hi hi hi
D. Compilation fails
E. hi, followed by an exception
F. hi hi, followed by an exception
Question 5
Given:
class Kill {
int x = 5;
public static void main(String[] args) {
final Kill f1 = new Kill();
Kill f2 = new Kill();
Kill f3 = KillSwitch(f1,f2);
System.out.println((f1 == f3) + " " + (f1.x == f3.x));
}
static Kill KillSwitch(Kill x, Kill y) {
final Kill z = x;
z.x = 6;
return z;
} }
What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails
F. An exception is thrown at runtime
Question 6
Given:
class Car {
{ System.out.print("b1 "); }
public Car() { System.out.print("b2 "); }
}
class Ferrari extends Car {
static { System.out.print("r1 "); }
public Ferrari() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class F50 extends Ferrari {
public static void main(String[] args) {
System.out.print("pre ");
new F50();
System.out.println("F50 ");
}
}
What is the result?
A. pre b1 b2 r3 r2 F50
B. pre b2 b1 r2 r3 F50
C. pre b2 b1 r2 r3 F50 r1 r4
D. r1 r4 pre b1 b2 r3 r2 F50
E. r1 r4 pre b2 b1 r2 r3 F50
F. pre r1 r4 b1 b2 r3 r2 F50
G. pre r1 r4 b2 b1 r2 r3 F50
H. The order of output cannot be predicted
I. Compilation fails
Question 7
Given:
3. public class Oops {
4. static int Oops = 7;
5. public static void main(String[] args) {
6. new Oops().go(Oops);
7. System.out.print(" " + Oops);
8. }
9. void go(int Oops) {
10. Oops++;
11. for(int Oops = 3; Oops < 6; Oops++)
12. ;
13. System.out.print(" " + Oops);
14. }
15. }
What is the result?
A. 5 7
B. 5 8
C. 8 7
D. 8 8
E. Compilation fails
F. An exception is thrown at runtime
Question 8
Given:
3. public class Test {
4. static String s = "";
5. public static void main(String[] args) {
6. int x = 4; Boolean y = true; short[] sa = {1,2,3};
7. doSomething(x, y);
8. doSomething(x);
9. doSomething(sa, sa);
10. System.out.println(s);
11. }
12. static void doSomething(Object o) { s += "1"; }
13. static void doSomething(Object... o) { s += "2"; }
14. static void doSomething(Integer... i) { s += "3"; }
15. static void doSomething(Long L) { s += "4"; }
16. }
What is the result?
A. 212
B. 232
C. 234
D. 312
E. 332
F. 334
G. Compilation fails
Question 9
Given:
3. class TestGarbageCollection {
4. int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
5. }
6. public class Eggs {
7. public static void main(String[] args) {
8. TestGarbageCollection [] da = new TestGarbageCollection[3];
9. da[0] = new TestGarbageCollection();
10. TestGarbageCollection d = new TestGarbageCollection();
11. da[1] = d;
12. d = null;
13. da[1] = null;
14. // do stuff
15. }
16. }
Which two are true about the objects created within main(), and eligible for garbage collection when line 14 is reached?
A. Three objects were created
B. Four objects were created
C. Five objects were created
D. Zero objects are eligible for GC
E. One object is eligible for GC
F. Two objects are eligible for GC
G. Three objects are eligible for GC
Question 10
Given:
3. public class Test {
4. int x = 3;
5. public static void main(String[] args) {
6. new Test().go1();
7. }
8. void go1() {
9. int x;
10. go2(++x);
11. }
12. void go2(int y) {
13. int x = ++y;
14. System.out.println(x);
15. }
16. }
What is the result?
A. 2
B. 3
C. 4
D. 5
E. Compilation fails
F. An exception is thrown at runtime
Self Test - Answers:
Question 1:
C is correct. Only one GCTest object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
A, B, D, E, and F are incorrect based on the above
Question 2:
C is correct, compilation fails. The var-args declaration is fine, but invade takes a short, so the argument 7 needs to be cast to a short. With the cast, the answer is B, ‘a few’.
A, B, D, and E are incorrect based on the above.
Question 3:
C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][] not an int[]. If line 7 was removed, the output would be 4.
A, B, D, E, F, and G are incorrect based on the above
Question 4:
F is correct. The m2 object’s m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown
A, B, C, D, and E are incorrect based on the above
Question 5:
A is correct. The references f1, z, and f3 all refer to the same instance of Kill. The final modifier assures that a reference variable cannot be referred to a different object, but final doesn’t keep the object’s state from changing.
B, C, D, E, and F are incorrect based on the above
Question 6:
D is correct. Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down.
A, B, C, E, F, G, H, and I are incorrect based on the above.
Question 7:
E is correct. The parameter declared on line 9 is valid (although ugly), but the variable name Oops cannot be declared again on line 11 in the same scope as the declaration on line 9.
A, B, C, D, and F are incorrect based on the above
Question 8:
A is correct. It’s legal to autobox and then widen. The first call to doSomething() boxes the int to an Integer then passes two objects. The second call cannot widen and then box (making the Long method unusable), so it boxes the int to an Integer. As always, a var-args method will be chosen only if no non-var-arg method is possible. The third call is passing two objects—they are of type ‘short array.’
B, C, D, E, F, and G are incorrect based on the above
Question 9:
C and F are correct. da refers to an object of type “TestGarbageCollection array,” and each TestGarbageCollection object that is created comes with its own “int array” object. When line 14 is reached, only the second TestGarbageCollection object (and its “int array” object) are not reachable
A, B, D, E, and G are incorrect based on the above.
Question 10:
E is correct. In go1() the local variable x is not initialized
A, B, C, D, and F are incorrect based on the above.
Previous Chapter: Quick Review - Chapters 15 to 21
Next Chapter: Chapter 22: Assignment Operator
Labels:
garbage collection,
gc,
java gc,
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self assessment scjp,
self test,
self test scjp,
test scjp
| Reactions: |
Friday, January 28, 2011
Self Test: Chapters 6 to 14
Question 1:
Given:
public abstract interface Cultivate { public void water(String s); }
Which is a correct class? (Choose all that apply.)
A. public abstract class Grow implements Cultivate {
public abstract void water(String s) { }
}
B. public abstract class Grow implements Cultivate { }
C. public class Grow extends Cultivate {
public void water(Integer i) { }
}
D. public class Grow implements Cultivate {
public void water(Integer i) { }
}
E. public class Grow implements Cultivate {
public void water(String i) { }
public void water(Integer s) { }
}
Question 2:
Given:
class Parent {
public Parent(String s) { System.out.print("B"); }
}
public class Child extends Parent {
public Child(String s) { System.out.print("D"); }
public static void main(String [] args) {
new Child("C");
System.out.println(" ");
}
}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails
Question 3:
Given:
class Parent {
private final void flipper() { System.out.println("Parent"); }
}
public class Child extends Parent {
public final void flipper() { System.out.println("Child"); }
public static void main(String [] args) {
new Child().flipper();
}
}
What is the result?
A. Child
B. Parent
C. Parent
D. Child
E. Child
F. Parent
G. Compilation fails
Question :
Which statement(s) are true? (Choose all that apply.)
A. Cohesion is the OO principle most closely associated with hiding implementation details
B. Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through their APIs
C. Cohesion is the OO principle most closely associated with making sure that a class is designed with a runle, well-focused purpose
D. Cohesion is the OO principle most closely associated with allowing a runle object to be seen as having many types
Question 5:
Given the following,
1. class X { void doX() { } }
2. class Y extends X { void doY() { } }
3.
4. class Chrome {
5. public static void main(String [] args) {
6. X x1 = new X();
7. X x2 = new Y();
8. Y y1 = new Y();
9. // insert code here
10. } }
Which, inserted at line 9, will compile? (Choose all that apply.)
A. x2.doY();
B. (Y)x2.doY();
C. ((Y)x2).doY();
D. None of the above statements will compile
Question 6:
Given:
1. Class1 has a Class4
2. Methods in Class1 use public methods in Class2
3. Methods in Class3 use public methods in Class1
4. Methods in Class1 use public variables in Class2
Which is most likely true? (Choose the most likely.)
A. Class4 has low cohesion
B. Class1 has weak encapsulation
C. Class2 has weak encapsulation
D. Class2 has strong encapsulation
E. Class3 is tightly coupled to Class1
Question 7:
Given:
3. class WildCat {
4. public void roar() { System.out.print("Grrrrrrrrr "); }
5. }
6. class Lion extends WildCat {
7. public void sniff() { System.out.print("sniff "); }
8. public void roar() { System.out.print("roarrrrrr "); }
9. }
10. public class WildCatShow {
11. public static void main(String[] args) { new WildCatShow().go(); }
12. void go() {
13. new Lion().roar();
14. ((WildCat) new Lion()).roar();
15. ((WildCat) new Lion()).sniff();
16. }
17. }
What is the result? (Choose all that apply.)
A. roarrrrrr roarrrrrr sniff
B. roarrrrrr Grrrrrrrrr sniff
C. roarrrrrr roarrrrrr followed by an exception
D. roarrrrrr Grrrrrrrrr followed by an exception
E. Compilation fails with an error at line 14
F. Compilation fails with an error at line 15
Question 8:
Given:
3. public class Ferrari extends Car {
4. public static void main(String[] args) {
5. new Ferrari().go();
6. }
7. void go() {
8. go2(new Car(), new Ferrari());
9. go2((Ferrari) new Car(), new Ferrari());
10. }
11. void go2(Car t1, Ferrari r1) {
12. Ferrari r2 = (Ferrari)t1;
13. Car t2 = (Car)r1;
14. }
15. }
16. class Car { }
What is the result? (Choose all that apply.)
A. An exception is thrown at runtime
B. The code compiles and runs with no output
C. Compilation fails with an error at line 8
D. Compilation fails with an error at line 9
E. Compilation fails with an error at line 12
F. Compilation fails with an error at line 13
Question 9:
Given:
3. public class Ferrari extends Car {
4. public static String run() { return "fa"; }
5. public static void main(String[] args) {
6. Ferrari t = new Ferrari();
7. Car s = new Ferrari();
8. System.out.println(t.run() + " " + s.run());
9. }
10. }
11. class Car { public static String run() { return "la"; } }
What is the result?
A. fa fa
B. fa la
C. la la
D. Compilation fails
E. An exception is thrown at runtime
Question 10:
Given:
3. class Manager {
4. static String s = " ";
5. protected Manager() { s += "Manager "; }
6. }
7. class SubManager extends Manager {
8. private SubManager() { s += "sub "; }
9. }
10. public class SubSubManager extends Manager {
11. private SubSubManager() { s += "subsub "; }
12. public static void main(String[] args) {
13. new SubSubManager();
14. System.out.println(s);
15. }
16. }
What is the result?
A. subsub
B. sub subsub
C. Manager subsub
D. Manager sub subsub
E. Compilation fails
F. An exception is thrown at runtime
Question 11:
Given:
3. class Apartments {
4. Apartments() { System.out.print("b "); }
5. Apartments(String name) {
6. this(); System.out.print("bn " + name);
7. }
8. }
9. public class Home extends Apartments {
10. Home() { System.out.print("h "); }
11. Home(String name) {
12. this(); System.out.print("hn " + name);
13. }
14. public static void main(String[] args) { new Home("x "); }
15. }
What is the result?
A. h hn x
B. hn x h
C. b h hn x
D. b hn x h
E. bn x h hn x
F. b bn x h hn x
G. bn x b h hn x
H. Compilation fails
Question 12:
Given:
3. class Animal {
4. String name = "Rocky ";
5. String makeNoise() { return "generic noise"; }
6. }
7. class Tiger extends Animal {
8. String name = "stripes ";
9. String makeNoise() { return "roarrrrrrrrrrr"; }
10. }
11. public class Zoo {
12. public static void main(String[] args) { new Zoo().go(); }
13. void go() {
14. Animal m = new Tiger();
15. System.out.println(m.name + m.makeNoise());
16. }
17. }
What is the result?
A. Rocky roarrrrrrrrrrr
B. stripes roarrrrrrrrrrr
C. Rocky generic noise
D. stripes generic noise
E. Compilation fails
F. An exception is thrown at runtime
Answers:
Q1. B is correct, an abstract class need not implement any or all of an interface’s methods. E is correct, the class implements the interface method and additionally overloads the water() method.
A is incorrect because abstract methods have no body. C is incorrect because classes implement interfaces they don’t extend them. D is incorrect because overloading a method is not implementing it.
Q2. E is correct. The implied super() call in Child’s constructor cannot be satisfied because there isn’t a no-arg constructor in Parent. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.
A, B, C, and D are incorrect based on the above.
Q3. A is correct. Although a final method cannot be overridden, in this case, the method is private, and therefore hidden. The effect is that a new, accessible, method flipper is created. Therefore, no polymorphism occurs in this example, the method invoked is simply that of the child class, and no error occurs.
B, C, D, and E are incorrect based on the preceding.
Q4. Answer C is correct.
A refers to encapsulation, B refers to coupling, and D refers to polymorphism
Q5. C is correct. Before you can invoke Y’s doY method you have to cast x2 to be of type Y. Statement B looks like a proper cast but without the second set of parentheses, the compiler thinks it’s an incomplete statement.
A, B and D are incorrect based on the preceding
Q6. C is correct. Generally speaking, public variables are a sign of weak encapsulation.
A, B, D, and E are incorrect, because based on the information given, none of these statements can be supported.
Q7. F is correct. Class WildCat doesn’t have a sniff method.
A, B, C, D, and E are incorrect based on the above information
Q8. A is correct, a Class3astException will be thrown when the code attempts to downcast a Car to a Ferrari.
B, C, D, E, and F are incorrect based on the above information.
Q9. B is correct. The code is correct, but polymorphism doesn’t apply to static methods.
A, C, D, and E are incorrect based on the above information.
Q10. C is correct. Watch out, SubSubManager extends Manager! Since the code doesn’t attempt to make a SubManager, the private constructor in SubManager is okay.
A, B, D, E, and F are incorrect based on the above information
Q11. C is correct. Remember that constructors call their superclass constructors, which execute first, and that constructors can be overloaded.
A, B, D, E, F, G, and H are incorrect based on the above information
Q12. A is correct. Polymorphism is only for instance methods.
B, C, D, E, and F are incorrect based on the above information
Previous Chapter: Quick Recap Chapters 6 to 14
Next Chapter: Chapter 15: Stack and Heap
Given:
public abstract interface Cultivate { public void water(String s); }
Which is a correct class? (Choose all that apply.)
A. public abstract class Grow implements Cultivate {
public abstract void water(String s) { }
}
B. public abstract class Grow implements Cultivate { }
C. public class Grow extends Cultivate {
public void water(Integer i) { }
}
D. public class Grow implements Cultivate {
public void water(Integer i) { }
}
E. public class Grow implements Cultivate {
public void water(String i) { }
public void water(Integer s) { }
}
Question 2:
Given:
class Parent {
public Parent(String s) { System.out.print("B"); }
}
public class Child extends Parent {
public Child(String s) { System.out.print("D"); }
public static void main(String [] args) {
new Child("C");
System.out.println(" ");
}
}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails
Question 3:
Given:
class Parent {
private final void flipper() { System.out.println("Parent"); }
}
public class Child extends Parent {
public final void flipper() { System.out.println("Child"); }
public static void main(String [] args) {
new Child().flipper();
}
}
What is the result?
A. Child
B. Parent
C. Parent
D. Child
E. Child
F. Parent
G. Compilation fails
Question :
Which statement(s) are true? (Choose all that apply.)
A. Cohesion is the OO principle most closely associated with hiding implementation details
B. Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through their APIs
C. Cohesion is the OO principle most closely associated with making sure that a class is designed with a runle, well-focused purpose
D. Cohesion is the OO principle most closely associated with allowing a runle object to be seen as having many types
Question 5:
Given the following,
1. class X { void doX() { } }
2. class Y extends X { void doY() { } }
3.
4. class Chrome {
5. public static void main(String [] args) {
6. X x1 = new X();
7. X x2 = new Y();
8. Y y1 = new Y();
9. // insert code here
10. } }
Which, inserted at line 9, will compile? (Choose all that apply.)
A. x2.doY();
B. (Y)x2.doY();
C. ((Y)x2).doY();
D. None of the above statements will compile
Question 6:
Given:
1. Class1 has a Class4
2. Methods in Class1 use public methods in Class2
3. Methods in Class3 use public methods in Class1
4. Methods in Class1 use public variables in Class2
Which is most likely true? (Choose the most likely.)
A. Class4 has low cohesion
B. Class1 has weak encapsulation
C. Class2 has weak encapsulation
D. Class2 has strong encapsulation
E. Class3 is tightly coupled to Class1
Question 7:
Given:
3. class WildCat {
4. public void roar() { System.out.print("Grrrrrrrrr "); }
5. }
6. class Lion extends WildCat {
7. public void sniff() { System.out.print("sniff "); }
8. public void roar() { System.out.print("roarrrrrr "); }
9. }
10. public class WildCatShow {
11. public static void main(String[] args) { new WildCatShow().go(); }
12. void go() {
13. new Lion().roar();
14. ((WildCat) new Lion()).roar();
15. ((WildCat) new Lion()).sniff();
16. }
17. }
What is the result? (Choose all that apply.)
A. roarrrrrr roarrrrrr sniff
B. roarrrrrr Grrrrrrrrr sniff
C. roarrrrrr roarrrrrr followed by an exception
D. roarrrrrr Grrrrrrrrr followed by an exception
E. Compilation fails with an error at line 14
F. Compilation fails with an error at line 15
Question 8:
Given:
3. public class Ferrari extends Car {
4. public static void main(String[] args) {
5. new Ferrari().go();
6. }
7. void go() {
8. go2(new Car(), new Ferrari());
9. go2((Ferrari) new Car(), new Ferrari());
10. }
11. void go2(Car t1, Ferrari r1) {
12. Ferrari r2 = (Ferrari)t1;
13. Car t2 = (Car)r1;
14. }
15. }
16. class Car { }
What is the result? (Choose all that apply.)
A. An exception is thrown at runtime
B. The code compiles and runs with no output
C. Compilation fails with an error at line 8
D. Compilation fails with an error at line 9
E. Compilation fails with an error at line 12
F. Compilation fails with an error at line 13
Question 9:
Given:
3. public class Ferrari extends Car {
4. public static String run() { return "fa"; }
5. public static void main(String[] args) {
6. Ferrari t = new Ferrari();
7. Car s = new Ferrari();
8. System.out.println(t.run() + " " + s.run());
9. }
10. }
11. class Car { public static String run() { return "la"; } }
What is the result?
A. fa fa
B. fa la
C. la la
D. Compilation fails
E. An exception is thrown at runtime
Question 10:
Given:
3. class Manager {
4. static String s = " ";
5. protected Manager() { s += "Manager "; }
6. }
7. class SubManager extends Manager {
8. private SubManager() { s += "sub "; }
9. }
10. public class SubSubManager extends Manager {
11. private SubSubManager() { s += "subsub "; }
12. public static void main(String[] args) {
13. new SubSubManager();
14. System.out.println(s);
15. }
16. }
What is the result?
A. subsub
B. sub subsub
C. Manager subsub
D. Manager sub subsub
E. Compilation fails
F. An exception is thrown at runtime
Question 11:
Given:
3. class Apartments {
4. Apartments() { System.out.print("b "); }
5. Apartments(String name) {
6. this(); System.out.print("bn " + name);
7. }
8. }
9. public class Home extends Apartments {
10. Home() { System.out.print("h "); }
11. Home(String name) {
12. this(); System.out.print("hn " + name);
13. }
14. public static void main(String[] args) { new Home("x "); }
15. }
What is the result?
A. h hn x
B. hn x h
C. b h hn x
D. b hn x h
E. bn x h hn x
F. b bn x h hn x
G. bn x b h hn x
H. Compilation fails
Question 12:
Given:
3. class Animal {
4. String name = "Rocky ";
5. String makeNoise() { return "generic noise"; }
6. }
7. class Tiger extends Animal {
8. String name = "stripes ";
9. String makeNoise() { return "roarrrrrrrrrrr"; }
10. }
11. public class Zoo {
12. public static void main(String[] args) { new Zoo().go(); }
13. void go() {
14. Animal m = new Tiger();
15. System.out.println(m.name + m.makeNoise());
16. }
17. }
What is the result?
A. Rocky roarrrrrrrrrrr
B. stripes roarrrrrrrrrrr
C. Rocky generic noise
D. stripes generic noise
E. Compilation fails
F. An exception is thrown at runtime
Answers:
Q1. B is correct, an abstract class need not implement any or all of an interface’s methods. E is correct, the class implements the interface method and additionally overloads the water() method.
A is incorrect because abstract methods have no body. C is incorrect because classes implement interfaces they don’t extend them. D is incorrect because overloading a method is not implementing it.
Q2. E is correct. The implied super() call in Child’s constructor cannot be satisfied because there isn’t a no-arg constructor in Parent. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.
A, B, C, and D are incorrect based on the above.
Q3. A is correct. Although a final method cannot be overridden, in this case, the method is private, and therefore hidden. The effect is that a new, accessible, method flipper is created. Therefore, no polymorphism occurs in this example, the method invoked is simply that of the child class, and no error occurs.
B, C, D, and E are incorrect based on the preceding.
Q4. Answer C is correct.
A refers to encapsulation, B refers to coupling, and D refers to polymorphism
Q5. C is correct. Before you can invoke Y’s doY method you have to cast x2 to be of type Y. Statement B looks like a proper cast but without the second set of parentheses, the compiler thinks it’s an incomplete statement.
A, B and D are incorrect based on the preceding
Q6. C is correct. Generally speaking, public variables are a sign of weak encapsulation.
A, B, D, and E are incorrect, because based on the information given, none of these statements can be supported.
Q7. F is correct. Class WildCat doesn’t have a sniff method.
A, B, C, D, and E are incorrect based on the above information
Q8. A is correct, a Class3astException will be thrown when the code attempts to downcast a Car to a Ferrari.
B, C, D, E, and F are incorrect based on the above information.
Q9. B is correct. The code is correct, but polymorphism doesn’t apply to static methods.
A, C, D, and E are incorrect based on the above information.
Q10. C is correct. Watch out, SubSubManager extends Manager! Since the code doesn’t attempt to make a SubManager, the private constructor in SubManager is okay.
A, B, D, E, and F are incorrect based on the above information
Q11. C is correct. Remember that constructors call their superclass constructors, which execute first, and that constructors can be overloaded.
A, B, D, E, F, G, and H are incorrect based on the above information
Q12. A is correct. Polymorphism is only for instance methods.
B, C, D, E, and F are incorrect based on the above information
Previous Chapter: Quick Recap Chapters 6 to 14
Next Chapter: Chapter 15: Stack and Heap
Labels:
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self test,
self test scjp
| Reactions: |
Monday, January 3, 2011
Self Test – Chapters 1 to 5
We have successfully completed 5 chapters that have covered the basics of the java programming language (Of course, there is still a lot more basic stuff to come) Let us now try to assess how much knowledge we have gained in these chapters.
The following is a quick self-assessment (test). All questions are multiple choice (Like the original SCJP exam). Try to answer them based on what you have learnt in these previous 5 chapters. Don’t worry, I have given the answers to the questions too at the end of the chapter to let you judge how well you have learnt these topics.
Questions:
Question 1:
Which is true? (Choose all that apply.)
A. “X extends Y” is correct if and only if X is a class and Y is an interface
B. “X extends Y” is correct if and only if X is an interface and Y is a class
C. “X extends Y” is correct if X and Y are either both classes or both interfaces
D. “X extends Y” is correct for all combinations of X and Y being classes and/or interfaces
Question 2:
Which method names follow the JavaBeans standard? (Choose all that apply.)
A. addSize
B. getCust
C. deleteRep
D. isTrue
E. putDimensions
Question 3:
Which of the following are valid method declarations? Choose all that apply.
A. public abstract final String getName();
B. public final getName() { return “Anand”; }
C. public static void doSomething() {…}
D. public abstract String getName() { return “Anand” };
Question 4:
Given:
1. enum Animals {
2. DOG("woof"), CAT("meow"), FISH("burble");
3. String sound;
4. Animals(String s) { sound = s; }
5. }
6. class TestEnum {
7. static Animals a;
8. public static void main(String[] args) {
9. System.out.println(a.DOG.sound + " " + a.FISH.sound);
10. }
11. }
What is the result?
A. woof burble
B. Multiple compilation errors
C. Compilation fails due to an error on line 2
D. Compilation fails due to an error on line 3
E. Compilation fails due to an error on line 4
F. Compilation fails due to an error on line 9
Question 5:
Given:
1. public class Electronic implements Device
{ public void doIt() { } }
2.
3. abstract class Phone1 extends Electronic { }
4.
5. abstract class Phone2 extends Electronic
{ public void doIt(int x) { } }
6.
7. class Phone3 extends Electronic implements Device
{ public void doStuff() { } }
8.
9. interface Device { public void doIt(); }
What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails with an error on line 1
C. Compilation fails with an error on line 3
D. Compilation fails with an error on line 5
E. Compilation fails with an error on line 7
F. Compilation fails with an error on line 9
Question 6:
Given:
4. class Announce {
5. public static void main(String[] args) {
6. for(int __x = 0; __x < 3; __x++) ; 7. int #lb = 7; 8. long [] x [5]; 9. Boolean []ba[]; 10. enum Traffic { RED, YELLOW, GREEN }; 11. } 12. } What is the result? (Choose all that apply.) A. Compilation succeeds B. Compilation fails with an error on line 6 C. Compilation fails with an error on line 7 D. Compilation fails with an error on line 8 E. Compilation fails with an error on line 9 F. Compilation fails with an error on line 10 Question 7:
Given:
3. public class TestDays {
4. public enum Days { MON, TUE, WED };
5. public static void main(String[] args) {
6. for(Days d : Days.values() )
7. ;
8. Days [] d2 = Days.values();
9. System.out.println(d2[2]);
10. }
11. }
What is the result? (Choose all that apply.)
A. TUE
B. WED
C. The output is unpredictable
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 6
F. Compilation fails due to an error on line 8
G. Compilation fails due to an error on line 9
Question 8:
Given:
4. public class Frodo extends Hobbit {
5. public static void main(String[] args) {
6. Short myGold = 7;
7. System.out.println(countGold(myGold, 6));
8. }
9. }
10. class Hobbit {
11. int countGold(int x, int y) { return x + y; }
12. }
What is the result?
A. 13
B. Compilation fails due to multiple errors
C. Compilation fails due to an error on line 6
D. Compilation fails due to an error on line 7
E. Compilation fails due to an error on line 11
Question 9:
Which of the following statements are true? Choose all that apply
A. An abstract class can have final methods
B. A Final class can have abstract methods
C. A static method can access instance variables
D. An abstract class can have one or more methods that contain implementations
Question 10:
Given the code below, Guess the output:
1. public class test {
2. public String name = “Anand”;
3. public String getName() {
4. return this.name;
5. }
6. public static void main(String[] args) {
7. System.out.print (“Name is:” + name);
8. System.out.print(“Name is:” + getName());
9. }
10. }
A. Output Anand Anand gets printed in the console
B. Compilation error at line 7
C. Compilation error at line 8
D. Program compiles fine but fails at runtime
Answers:
Answer 1:
C is correct
A is incorrect because classes implement interfaces, they don’t extend them. B is incorrect because interfaces only “inherit from” other interfaces. D is incorrect based on the preceding rules.
Answer 2:
B and D use the valid prefixes ‘get’ and ‘is’. And hence they are correct
A is incorrect because ‘add’ can be used only with Listener methods. C and E are incorrect because ‘delete’ and ‘put’ are not standard JavaBeans name prefixes.
Answer 3:
C is a valid method declaration and hence is correct.
A is incorrect because a method cannot be both abstract and final. B is incorrect because the method’s return type “String” is missing. D is incorrect because an abstract method cannot have any code inside it.
Answer 4:
A is correct; enums can have constructors and variables.
B, C, D, E, and F are incorrect; these lines all use correct syntax
Answer 5:
A is correct; all of these are legal declarations.
B, C, D, E, and F are incorrect based on the above information
Answer 6:
C, D, and F are correct. Variable names cannot begin with a #, an array declaration can’t include a size without an instantiation, and enums can’t be declared within a method.
A, B, and E are incorrect based on the above information
Answer 7:
B is correct. Every enum comes with a static values() method that returns an array of the enum’s values, in the order in which they are declared in the enum
A, C, D, E, F, and G are incorrect based on the above information
Answer 8:
D is correct. The Short myGold is autoboxed correctly, but the countGold() method cannot be invoked from a static context
A, B, C, and E are incorrect based on the above information
Answer 9:
D is correct because an abstract class can have one or more methods that contain implementations (code)
A is correct because an abstract class can have final methods
B is incorrect because a final class cannot have abstract methods C is incorrect because a static method cannot access instance variables
Answer 10:
B & C are correct because the main method is static and it cannot access instance methods or variables.
A & D are incorrect because of the above mentioned reasons.
Previous Chapter - Quick Recap - Chapters 1 to 5
Next Chapter - Chapter 6: Object Oriented Concepts - Encapsulation
The following is a quick self-assessment (test). All questions are multiple choice (Like the original SCJP exam). Try to answer them based on what you have learnt in these previous 5 chapters. Don’t worry, I have given the answers to the questions too at the end of the chapter to let you judge how well you have learnt these topics.
Questions:
Question 1:
Which is true? (Choose all that apply.)
A. “X extends Y” is correct if and only if X is a class and Y is an interface
B. “X extends Y” is correct if and only if X is an interface and Y is a class
C. “X extends Y” is correct if X and Y are either both classes or both interfaces
D. “X extends Y” is correct for all combinations of X and Y being classes and/or interfaces
Question 2:
Which method names follow the JavaBeans standard? (Choose all that apply.)
A. addSize
B. getCust
C. deleteRep
D. isTrue
E. putDimensions
Question 3:
Which of the following are valid method declarations? Choose all that apply.
A. public abstract final String getName();
B. public final getName() { return “Anand”; }
C. public static void doSomething() {…}
D. public abstract String getName() { return “Anand” };
Question 4:
Given:
1. enum Animals {
2. DOG("woof"), CAT("meow"), FISH("burble");
3. String sound;
4. Animals(String s) { sound = s; }
5. }
6. class TestEnum {
7. static Animals a;
8. public static void main(String[] args) {
9. System.out.println(a.DOG.sound + " " + a.FISH.sound);
10. }
11. }
What is the result?
A. woof burble
B. Multiple compilation errors
C. Compilation fails due to an error on line 2
D. Compilation fails due to an error on line 3
E. Compilation fails due to an error on line 4
F. Compilation fails due to an error on line 9
Question 5:
Given:
1. public class Electronic implements Device
{ public void doIt() { } }
2.
3. abstract class Phone1 extends Electronic { }
4.
5. abstract class Phone2 extends Electronic
{ public void doIt(int x) { } }
6.
7. class Phone3 extends Electronic implements Device
{ public void doStuff() { } }
8.
9. interface Device { public void doIt(); }
What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails with an error on line 1
C. Compilation fails with an error on line 3
D. Compilation fails with an error on line 5
E. Compilation fails with an error on line 7
F. Compilation fails with an error on line 9
Question 6:
Given:
4. class Announce {
5. public static void main(String[] args) {
6. for(int __x = 0; __x < 3; __x++) ; 7. int #lb = 7; 8. long [] x [5]; 9. Boolean []ba[]; 10. enum Traffic { RED, YELLOW, GREEN }; 11. } 12. } What is the result? (Choose all that apply.) A. Compilation succeeds B. Compilation fails with an error on line 6 C. Compilation fails with an error on line 7 D. Compilation fails with an error on line 8 E. Compilation fails with an error on line 9 F. Compilation fails with an error on line 10 Question 7:
Given:
3. public class TestDays {
4. public enum Days { MON, TUE, WED };
5. public static void main(String[] args) {
6. for(Days d : Days.values() )
7. ;
8. Days [] d2 = Days.values();
9. System.out.println(d2[2]);
10. }
11. }
What is the result? (Choose all that apply.)
A. TUE
B. WED
C. The output is unpredictable
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 6
F. Compilation fails due to an error on line 8
G. Compilation fails due to an error on line 9
Question 8:
Given:
4. public class Frodo extends Hobbit {
5. public static void main(String[] args) {
6. Short myGold = 7;
7. System.out.println(countGold(myGold, 6));
8. }
9. }
10. class Hobbit {
11. int countGold(int x, int y) { return x + y; }
12. }
What is the result?
A. 13
B. Compilation fails due to multiple errors
C. Compilation fails due to an error on line 6
D. Compilation fails due to an error on line 7
E. Compilation fails due to an error on line 11
Question 9:
Which of the following statements are true? Choose all that apply
A. An abstract class can have final methods
B. A Final class can have abstract methods
C. A static method can access instance variables
D. An abstract class can have one or more methods that contain implementations
Question 10:
Given the code below, Guess the output:
1. public class test {
2. public String name = “Anand”;
3. public String getName() {
4. return this.name;
5. }
6. public static void main(String[] args) {
7. System.out.print (“Name is:” + name);
8. System.out.print(“Name is:” + getName());
9. }
10. }
A. Output Anand Anand gets printed in the console
B. Compilation error at line 7
C. Compilation error at line 8
D. Program compiles fine but fails at runtime
Answers:
Answer 1:
C is correct
A is incorrect because classes implement interfaces, they don’t extend them. B is incorrect because interfaces only “inherit from” other interfaces. D is incorrect based on the preceding rules.
Answer 2:
B and D use the valid prefixes ‘get’ and ‘is’. And hence they are correct
A is incorrect because ‘add’ can be used only with Listener methods. C and E are incorrect because ‘delete’ and ‘put’ are not standard JavaBeans name prefixes.
Answer 3:
C is a valid method declaration and hence is correct.
A is incorrect because a method cannot be both abstract and final. B is incorrect because the method’s return type “String” is missing. D is incorrect because an abstract method cannot have any code inside it.
Answer 4:
A is correct; enums can have constructors and variables.
B, C, D, E, and F are incorrect; these lines all use correct syntax
Answer 5:
A is correct; all of these are legal declarations.
B, C, D, E, and F are incorrect based on the above information
Answer 6:
C, D, and F are correct. Variable names cannot begin with a #, an array declaration can’t include a size without an instantiation, and enums can’t be declared within a method.
A, B, and E are incorrect based on the above information
Answer 7:
B is correct. Every enum comes with a static values() method that returns an array of the enum’s values, in the order in which they are declared in the enum
A, C, D, E, F, and G are incorrect based on the above information
Answer 8:
D is correct. The Short myGold is autoboxed correctly, but the countGold() method cannot be invoked from a static context
A, B, C, and E are incorrect based on the above information
Answer 9:
D is correct because an abstract class can have one or more methods that contain implementations (code)
A is correct because an abstract class can have final methods
B is incorrect because a final class cannot have abstract methods C is incorrect because a static method cannot access instance variables
Answer 10:
B & C are correct because the main method is static and it cannot access instance methods or variables.
A & D are incorrect because of the above mentioned reasons.
Previous Chapter - Quick Recap - Chapters 1 to 5
Next Chapter - Chapter 6: Object Oriented Concepts - Encapsulation
Labels:
SCJP,
SCJP Certification,
scjp exam questions,
scjp exam sample questions,
scjp questions,
self assement,
self assessment scjp,
self test,
self test scjp
| Reactions: |
Subscribe to:
Posts (Atom)
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.
