Pages

Showing posts with label OCPJ. Show all posts
Showing posts with label OCPJ. Show all posts

Aug 25, 2012

Exercise-7 (Collections and Generics)



1. Given:
public static void main(String[] args) {
// INSERT DECLARATION 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 // INSERT DECLARATION 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
Answer:
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. (Objective 6.4)

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
Answer:
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. (Objective 6.2)

3. Given:
public static void before() {
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 before() method will print 1 2
B. The before() method will print 1 2 3
C. The before() method will print three numbers, but the order cannot be determined
D. The before() method will not compile
E. The before() method will throw an exception at runtime
Answer:
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 before() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.
A, B, C, and D are incorrect based on the above. (Objective 6.5)

4. Given:
import java.util.*;
class MapEQ {
public static void main(String[] args) {
Map<ToDos, String> m = new HashMap<ToDos, String>();
ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");
ToDos t3 = new ToDos("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(m.size());
} }
class ToDos{
String day;
ToDos(String d) { day = d; }
public boolean equals(Object o) {
return ((ToDos)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
Answer:
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.
A, B, E, and F are incorrect based on the above. (Objective 6.2)

5. Given:
public class AccountManager {
private Map accountTotals = new HashMap(); //line 13
private int retirementFund;

public int getBalance(String accountName) {
Integer total = (Integer) accountTotals.get(accountName);  // line 17
if (total == null)
total = Integer.valueOf(0);
return total.intValue();   // line 20
}
public void setBalance(String accountName, int amount) {
accountTotals.put(accountName, Integer.valueOf(amount)); // line 24
} }
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> accountTotals = new HashMap<String, int>();
B. Replace line 13 with private
Map<String, Integer> accountTotals = new HashMap<String, Integer>();
C. Replace line 13 with
private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>();
D. Replace lines 17-20 with
int total = accountTotals.get(accountName);
if (total == null) total = 0;
return total;
E. Replace lines 17-20 with
Integer total = accountTotals.get(accountName);
if (total == null) total = 0; return total;
F. Replace lines 17-20 with return accountTotals.get(accountName);
G. Replace line 24 with accountTotals.put(accountName, amount);
H. Replace line 24 with accountTotals.put(accountName, amount.intValue());
Answer:
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. (Objective 6.4)

6. Given:
interface Hungry<E> { void munch(E x); }
interface Carnivore<E extends Animal> extends Hungry<E> {}
interface Herbivore<E extends Plant> extends Hungry<E> {}
abstract class Plant {}
class Grass extends Plant {}
abstract class Animal {}
class Sheep extends Animal implements Herbivore<Sheep> {
public void munch(Sheep x) {}
}
class Wolf extends Animal implements Carnivore<Sheep> {
public void munch(Sheep x) {}
}
Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
A. Change the Carnivore interface to
interface Carnivore<E extends Plant> extends Hungry<E> {}
B. Change the Herbivore interface to
interface Herbivore<E extends Animal> extends Hungry<E> {}
C. Change the Sheep class to
class Sheep extends Animal implements Herbivore<Plant> {
public void munch(Grass x) {}
}
D. Change the Sheep class to
class Sheep extends Plant implements Carnivore<Wolf> {
public void munch(Wolf x) {}
}
E. Change the Wolf class to
class Wolf extends Animal implements Herbivore<Grass> {
public void munch(Grass x) {}
}
F. No changes are necessary

Answer:
B is correct. The problem with the original code is that Sheep tries to implement HerbivoresSheep> and Herbivore declares that its type parameter E can be any type that extends Plant. Since a Sheep is not a Plant, Herbivore<Sheep> makes no sense- the type Sheep is outside the allowed range of Herbivore's parameter E. Only solutions that either alter the definition of a Sheep or alter the definition of Herbivore will be able to fix this. So A, E, and F are eliminated. B works, changing the definition of an Herbivore to allow it to eat Sheep solves the problem. C doesn't work because an Herbivore<Plant> must have a munch(Plant) method, not munch(Grass). And D doesn't work, because in D we made Sheep extend Plant, now the Wolf class breaks because its munch(Sheep) method no longer fulfills the contract of Carnivore. (Objective 6.4)

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
Answer:
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. (Objective 6.1)

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
// INSERT DECLARATIONS HERE
output = process(input);
Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)
A. ArrayList<Integer> input = null; ArrayList<Integer> output = null;
B. ArrayList<Integer> input = null; List<Integer> output = null;
C. ArrayList<Integer> input = null; List<Number> output = null;
D. List<Number> input = null; ArrayList<Integer> output = null;
E. List<Number> input = null; List<Number> output = null;
F. List<Integer> input = null; List<Integer> output = null;
G. None of the above
Answer:
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. (Objective 6.4)

9. Given the proper import statement(s), and
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
System.out.print(pq.peek() + " ");
pq.offer("1");
pq.add("3");
pq.remove("1");
System.out.print(pq.poll() + " ");
if(pq.remove("2")) System.out.print(pq.poll() + " ");
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
Answer:
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.
A, C, D, E, F, G, and H are incorrect based on the above. (Objective 6.1)

10. Given:
import java.util.*;
public class Mixup {
public static void main(String[] args) {
Object o = new Object();
// insert code here   line 7
s.add("o");
s.add(o);
}
}
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
Answer:
A, B, C, D, and F are all correct.
Only E is incorrect. Elements of a TreeSet must in some way implement Comparable. (Objective 6.1)

11. Given:
import java.util.*;
class Turtle {
int size;
public Turtle(int s) { size = s; }
public boolean equals(Object o) { return (this.size == ((Turtle)o).size); }
// insert code here line 8
}
public class TurtleTest {
public static void main(String[] args) {
LinkedHashSet<Turtle> t = new LinkedHashSet<Turtle>();
t.add(new Turtle(1)); t.add(new Turtle(2)); t.add(new Turtle(1));
System.out.println(t.size());
}
}
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
Answer:
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.
B, C, E, and F are incorrect based on the above. (Objective 6.2)

12. Given the proper import statement(s), and:
TreeSet<String> s = new TreeSet<String>();
 TreeSet<String> subs = new TreeSet<String>();
s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");

subs = (TreeSet)s.subSet("b", true, "d", true);
s.add("g");
s.pollFirst();
s.pollFirst();
s.add("c2");
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
Answer:
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].
A, C, D, E, G, and H are incorrect based on the above. (Objective 6.3)

13. Given:
import java.util.*;
public class Magellan {
public static void main(String[] args) {
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("a", "apple"); myMap.put("d", "date");
myMap.put("f", "fig"); myMap.put("p", "pear");
System.out.println("1st after mango: " + // sop 1
myMap.higherKey("f"));
System.out.println("1st after mango: " + // sop 2
myMap.ceilingKey("f"));
System.out.println("1st after mango: " + // sop 3
myMap.floorKey("f"));
SortedMap<String, String> sub = new TreeMap<String, String>();
sub = myMap.tailMap("f");
System.out.println("1st after mango: " + // sop 4
sub.firstKey());
}
}
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
Answer:
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.
B, C, D, E, and F are incorrect based on the above. (Objective 6.3)

14. Given:
import java.util.*;
class Business { }
class Hotel extends Business { }
class Inn extends Hotel { }
public class Travel {
ArrayList<Hotel> go() {
// insert code here  line 9
}
}
Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList<Inn>();
B. return new ArrayList<Hotel>();
C. return new ArrayList<Object>();
D. return new ArrayList<Business>();
Answer:
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. (Objective 6.4)

15. Given:
import java.util.*;
class Dog { int size; Dog(int s) { size = s; } }
public class FirstGrade {
public static void main(String[] args) {
TreeSet<Integer> i = new TreeSet<Integer>();
TreeSet<Dog> d = new TreeSet<Dog>();
d.add(new Dog(1)); d.add(new Dog(2)); d.add(new Dog(1));
i.add(1); i.add(2); i.add(1);
System.out.println(d.size() + " " + i.size());
}
}
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
Answer:
G is correct. Class Dog needs to implement Comparable in order for a TreeSet (which keeps its elements sorted) to be able to contain Dog objects.
A, B, C, D, E, and F are incorrect based on the above. (Objective 6.5)

16. Given:
import java.util.*;
public class GeoCache {
public static void main(String[] args) {
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));
}
static class Othello implements Comparator<String> {
public int compare(String a, String b) { return b.compareTo(a); }
}
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output will contain a 1
C. The output will contain a 2
D. The output will contain a -1
E. An exception is thrown at runtime
F. The output will contain "key map marble pen"
G. The output will contain "pen marble map key"
Answer:
D and G are correct. First, the compareTo() method will reverse the normal sort. Second, the sort() is valid. Third, the binarySearch() gives -1 because it needs to be invoked using the same Comparator (o), as was used to sort the array. Note that when the binarySearch() returns an "undefined result" it doesn't officially have to be a -1, but it usually is, so if you selected only G, you get full credit!
A, B, C, E, and F are incorrect based on the above. (Objective 6.5)


regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 17, 2012

OCJP Exercise -6 (Strings)



1. Given:
import java.util.regex.*;
class Regex2 {
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 Regex2 "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails
Answer:
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.
A, B, C, D, F, and G are incorrect based on the above. (Objective 3.5)

2. Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class CardPlayer extends Player implements Serializable {
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
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);
CardPlayer c2 = (CardPlayer) 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
Answer:
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.
A, B, D, E, and F are incorrect based on the above. (Objective 3.3)

3. Given:
class TKO {
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
Answer:
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.
A, E, F, and G are incorrect based on the above. (Remember that A is using the equals() method to try to compare two different types.) (Objective 3.1)

4. Given:
import java.io.*;
class Keyboard { }
public class Computer implements Serializable {
	
		private Keyboard k = new Keyboard();
public static void main(String[] args) {
Computer c = new Computer();
c.storeIt(c);
}
void storeIt(Computer c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
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
Answer:
A is correct. An instance of type Computer Has-a Keyboard. Because Keyboard doesn't implement Serializable, any attempt to serialize an instance of Computer will cause an exception to be thrown.
B, C, D, and E are incorrect based on the above. If Keyboard did implement Serializable then two objects would have been serialized. (Objective 3.3)

5. Using the fewest fragments possible (and filling the fewest slots possible), complete the code below so that the class builds a directory named "dir3" and creates a file named "file3" inside "dir3". Note you can use each fragment either zero or one times. Code:
import java.io.______________
class Maker {
public static void main(String[] args) {
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
} }
Fragments:
File; FileDescriptor; FileWriter; Directory;
try { .createNewDir(); File dir File
{ } (Exception x) ("dir3"); file
file .createNewFile(); = new File = new File
dir (dir, "file3"); (dir, file); .createFile();
} catch ("dir3", "file3"); .mkdir(); File file

Answer:
import java.io.File;
class Maker {
public static void main(String[] args) {
try {
File dir = new File("dir3");
dir.mkdir();
File file = new File(dir, "file3");
file.createNewFile();
} catch (Exception x) { }
} }

Notes: The new File statements don't make actual files or directories, just objects. You need the mkdir() and createNewFile() methods to actually create the directory and the file. (Objective 3.2)

6. Given that 1119280000000L is roughly the number of milliseconds from Jan. 1, 1970, to June 20, 2005, and that you want to print that date in German, using the LONG style such that "June" will be displayed as "Juni", complete the code using the fragments below. Note: you can use each fragment either zero or one times, and you might not need to fill all of the slots. Code:
import java.___________
import java.___________
class DateTwo {
public static void main(String[] args) {
Date d = new Date(1119280000000L);
DateFormat df = ___________________________
________________ , _________________ );
System.out.println(________________
}
}
Fragments:
io.*; new DateFormat( Locale.LONG
nio.*; DateFormat.getInstance( Locale.GERMANY
util.*; DateFormat.getDateInstance( DateFormat.LONG
text.*; util.regex; DateFormat.GERMANY
date.*; df.format(d)); d.format(df));

Answer:
import java.util.*; import java.text.*; class DateTwo { public static void main(String[] args) { Date d = new Date(1119280000000L); DateFormat df = DateFormat.getDateInstance( DateFormat.LONG, Locale.GERMANY); System.out.println(df.format(d)); } } Notes: Remember that you must build DateFormat objects using static methods. Also remember that you must specify a Locale for a DateFormat object at the time of instantiation. The getInstance() method does not take a Locale. (Objective 3.4)

7. Given:
import java.io.*;
class Directories {
static String [] dirs = {"dir1", "dir2"};
public static void main(String [] args) {
for (String d : dirs) {
// insert code 1 here
File file = new File(path, args[0]);
// insert code 2 here
}
}
}
and that the invocation
java Directories file2.txt
is issued from a directory that has two subdirectories, "dir1" and "dir2", and that "dir1" has a file "file1.txt" and "dir2" has a file "file2.txt", and the output is "false true", which set(s) of code fragments must be inserted? (Choose all that apply.)

A. String path = d; System.out.print(file.exists() + " ");
B. String path = d; System.out.print(file.isFile() + " ");
C. String path = File.separator + d; System.out.print(file.exists() + " ");
D. String path = File.separator + d; System.out.print(file.isFile() + " ");
Answer:
A and B are correct. Because you are invoking the program from the directory whose direct subdirectories are to be searched, you don't start your path with a File.separator character. The exists() method tests for either files or directories; the isFile() method tests only for files. Since we're looking for a file, both methods work.
C and D are incorrect based on the above. (Objective 3.2)

8. Given:
import java.io.*;
public class TestSer {
public static void main(String[] args) {
SpecialSerial s = new SpecialSerial();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myFile"));
SpecialSerial s2 = (SpecialSerial)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SpecialSerial 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 SpecialSerial
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SpecialSerial
Answer:
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.
A, B, D, and E are incorrect based on the above. 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. (Objective 3.3)

9. Given:
3. public class Theory {
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
Answer:
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.
A, B, C, E, and G are incorrect based on the above. (Objective 3.1)

10. Given:
3. import java.io.*;
4. public class ReadingFor {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myfile.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 myfile.txt contains the following two lines of data:
ab cd
What is the result?
A. ab
B. abcd
C. ab cd
D. a b c d
E. Compilation fails
Answer:
E is correct. You need to call flush() only when you're writing data. Readers don't have flush() methods. If not for the call to flush(), answer C would be correct.
A, B, C, and D are incorrect based on the above. (Objective 3.2)

11. Given:
3. import java.io.*;
4. public class Talker {
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 fred as a username and 1234 as a password, what is the result? (Choose all that apply.)
A.
username:
password:
B.
username: fred
password:
C.
username: fred
password: 1234
D. Compilation fails
E. An exception is thrown at runtime
Answer:
D is correct. The readPassword() method returns a char[]. If a char[] were used, answer B would be correct.
A, B, C, and E are incorrect based on the above. (Objective 3.2)

12. Given:
3. import java.io.*;
4. class Vehicle { }
5. class Wheels { }
6. class Car extends Vehicle implements Serializable { }
7. class Ford extends Car { }
8. class Dodge extends Car {
9. Wheels w = new Wheels();
10. }
Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ford
C. Dodge
D. Wheels
E. Vehicle
Answer:
A and B are correct. Dodge instances cannot be serialized because they "have" an instance of Wheels, which is not serializable. Vehicle instances cannot be serialized even though the subclass Car can be.
C, D, and E are incorrect based on the above. (Objective 3.3)

13. Given:
3. import java.text.*;
4. public class Slice {
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
Answer:
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.
A, B, C, and E are incorrect based on the above. (Objective 3.4)

14. Given:
3. import java.util.regex.*;
4. public class Archie {
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 Archie "\d+" ab2c4d67
What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails
Answer:
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.
A, C, D, E, and F are incorrect based on the above. (Objective 3.5)

15. Given:
import java.util.*;
public class Looking {
public static void main(String[] args) {
String input = "1 2 a 3 45 6";
Scanner sc = new Scanner(input);
int x = 0;
do {
x = sc.nextInt();
System.out.print(x + " ");
} while (x!=0);
}
}
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
Answer:
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.
A, B, C, D, and E are incorrect based on the above. (Objective 3.5)


.


regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 2, 2012

Operators


Relational Operators (Objective 7.6)
  1. Relational operators always result in a boolean value (true or false).
  2. There are six relational operators: >, >=, <, <=, ==, and !=. 
  3. The last two (== and !=) are sometimes referred to as equality operators.
  4. When comparing characters, Java uses the Unicode value of the character as the numerical value.
Equality operators
  1. There are two equality operators: == and != .
  2. Four types of things can be tested: numbers, characters, booleans, and reference variables.
  3. When comparing reference variables, == returns true only if both references refer to the same object. 
instanceof Operator (Objective 7.6)
  1. instanceof is for reference variables only, and checks for whether the object is of a particular type.
  2. The instanceof operator can be used only to test objects (or null) against class types that are in the same class hierarchy.
  3. For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.
Arithmetic Operators (Objective 7.6)
  1. There are four primary math operators: add, subtract, multiply, and divide.
  2. The remainder operator (%), returns the remainder of a division.
  3. Expressions are evaluated from left to right, unless you add parentheses, or unless some operators in the expression have higher precedence than others.
  4. The *, /, and % operators have higher precedence than + and -.
String Concatenation Operator (Objective 7.6)
  1. If either operand is a String, the + operator concatenates the operands. 
  2. If both operands are numeric, the + operator adds the operands.
Increment/Decrement Operators (Objective 7.6)
  1. Prefix operators (++ and --) run before the value is used in the expression.
  2. Postfix operators (++ and --) run after the value is used in the expression.
  3. In any expression, both operands are fully evaluated before the operator is applied.
  4. Variables marked final cannot be incremented or decremented.
Ternary (Conditional Operator) (Objective 7.6)
  1. Returns one of two values based on whether a boolean expression is true or false.
  2. Returns the value after the ? if the expression is true.
  3. Returns the value after the : if the expression is false.
Logical Operators (Objective 7.6)
  1. The exam covers six "logical" operators: &, |, ^, !, &&, and ||.
  2. Logical operators work with two expressions (except for !) that must resolve to boolean values.
  3. The && and & operators return true only if both operands are true.
  4. The || and | operators return true if either or both operands are true.
  5. The && and || operators are known as short-circuit operators.
  6. The && operator does not evaluate the right operand if the left operand is false.
  7. The || does not evaluate the right operand if the left operand is true.
  8. The & and | operators always evaluate both operands.
  9. The ^ operator (called the "logical XOR"), returns true if exactly one operand is true.
  10. The ! operator (called the "inversion" operator), returns the opposite value of the boolean operand it precedes.


regards,
Tech Dexters Support Team,
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Jul 18, 2012

OCPJ Exercise-2 (Object Orientation)




1. Given:
public abstract interface Frobnicate { public void twiddle(String s); }
Which is a correct class? (Choose all that apply.) A.
public abstract class Frob implements Frobnicate {
public abstract void twiddle(String s) { }
}
B.
 public abstract class Frob implements Frobnicate { } 
C.
public class Frob extends Frobnicate {
  public void twiddle(Integer i) { }
}
D.
public class Frob implements Frobnicate {
public void twiddle(Integer i) { }
}
E.
public class Frob implements Frobnicate {
  public void twiddle(String i) { }
  public void twiddle(Integer s) { }
}
Answer:
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 twiddle() 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.
(Objective 5.4)


2. Given:
class Top {
   public Top(String s) { System.out.print("B"); }
}
public class Bottom2 extends Top {
   public Bottom2(String s) { System.out.print("D"); }
   public static void main(String [] args) {
     new Bottom2("C");
     System.out.println(" ");
   } 
}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails
Answer:
E is correct. The implied super() call in Bottom2's constructor cannot be satisfied because there isn't a no-arg constructor in Top. 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. (Objective 1.6)


3. Given:
class Clidder {
  private final void flipper() { System.out.println("Clidder"); }
}
public class Clidlet extends Clidder {
  public final void flipper() { System.out.println("Clidlet"); }
  public static void main(String [] args) {
  new Clidlet().flipper();
  }
}
What is the result? A. Clidlet
B. Clidder
C. Clidder Clidlet
D. Clidlet Clidder
E. Compilation fails
Answer:
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.(Objective 5.3)


4. Using the fragments below, complete the following code so it compiles. Note, you may not have to fill all of the slots.
Code:

class AgedP {
   __________ __________ __________ __________ __________
   public AgedP(int x) {
       __________ __________ __________ __________ __________
   }
}

public class Kinder extends AgedP {
   __________ __________ __________ _________ ________ __________
   public Kinder(int x) {
     __________ __________ __________ __________ __________ ();
   }
}
Fragments: Use the following fragments zero or more times:
AgedP super this ( ) { } ;

Answer:
class AgedP {
AgedP() {}
public AgedP(int x) {
}
}
public class Kinder extends AgedP {
public Kinder(int x) {
super();
}
}
As there is no droppable tile for the variable x and the parentheses (in the Kinder constructor), are already in place and empty, there is no way to construct a call to the superclass constructor that takes an argument. Therefore, the only remaining possibility is to create a call to the noargument superclass constructor. This is done as: super();. The line cannot be left blank, as the parentheses are already in place. Further, since the superclass constructor called is the noargument version, this constructor must be created. It will not be created by the compiler because there is another constructor already present.(Objective 5.4)


5 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 single, well-focused purpose
D. Cohesion is the OO principle most closely associated with allowing a single object to be seen as having many types
Answer:
Answer C is correct.
A refers to encapsulation, B refers to coupling, and D refers to polymorphism.(Objective 5.1)


6. Given the following,
class X { void do1() { } }
class Y extends X { void do2() { } }

class Chrome {
  public static void main(String [] args) {
    X x1 = new X();
    X x2 = new Y();
    Y y1 = new Y();
    
    // insert code here
  }
}
Which, inserted at line 9, will compile? (Choose all that apply.)
A. x2.do2();
B. (Y)x2.do2();
C. ((Y)x2).do2();
D. None of the above statements will compile
Answer:
C is correct. Before you can invoke Y's do2 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.(Objective 5.2)


7. Given:
1. ClassA has a ClassD
2. Methods in ClassA use public methods in ClassB
3. Methods in ClassC use public methods in ClassA
4. Methods in ClassA use public variables in ClassB
Which is most likely true? (Choose the most likely.) A. ClassD has low cohesion
B. ClassA has weak encapsulation
C. ClassB has weak encapsulation
D. ClassB has strong encapsulation
E. ClassC is tightly coupled to ClassA
Answer:
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. (Objective 5.1)


8. Given:
class Dog {
  public void bark() { System.out.print("woof "); }
}
class Hound extends Dog {
  public void sniff() { System.out.print("sniff "); }
  public void bark() { System.out.print("howl "); }
}
public class DogShow {
  public static void main(String[] args) { new DogShow().go(); }
  void go() {
    new Hound().bark();
    ((Dog) new Hound()).bark();
    ((Dog) new Hound()).sniff();
  }
}
What is the result? (Choose all that apply.)
A. howl howl sniff
B. howl woof sniff
C. howl howl followed by an exception
D. howl woof followed by an exception
E. Compilation fails with an error at line 12
F. Compilation fails with an error at line 13
Answer:
F is correct. Class Dog doesn't have a sniff method.
A, B, C, D, and E are incorrect based on the above information. (Objective 5.2)


9. Given:
public class Redwood extends Tree {
   public static void main(String[] args) {
     new Redwood().go();
   }
   void go() {
     go2(new Tree(), new Redwood());
     go2((Redwood) new Tree(), new Redwood());
   }
   void go2(Tree t1, Redwood r1) {
     Redwood r2 = (Redwood)t1;
     Tree t2 = (Tree)r1;
   }
}
class Tree { }
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 6
D. Compilation fails with an error at line 7
E. Compilation fails with an error at line 10
F. Compilation fails with an error at line 11
Answer:
A is correct, a ClassCastException will be thrown when the code attempts to downcast a Tree to a Redwood.
B, C, D, E, and F are incorrect based on the above information.(Objective 5.2)


10. Given:
public class Tenor extends Singer {
   public static String sing() { return "fa"; }
   public static void main(String[] args) {
     Tenor t = new Tenor();
     Singer s = new Tenor();
     System.out.println(t.sing() + " " + s.sing());
   }
}
class Singer { public static String sing() { 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
Answer:
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.(Objective 5.2)


11. Given:
class Alpha {
  static String s = " ";
  protected Alpha() { s += "alpha "; }
}
class SubAlpha extends Alpha {
  private SubAlpha() { s += "sub "; }
}
public class SubSubAlpha extends Alpha {
  private SubSubAlpha() { s += "subsub "; }
  public static void main(String[] args) {
    new SubSubAlpha();
    System.out.println(s);
  }
}
What is the result? A. subsub
B. sub subsub
C. alpha subsub
D. alpha sub subsub
E. Compilation fails
F. An exception is thrown at runtime
Answer:
C is correct. Watch out, SubSubAlpha extends Alpha! Since the code doesn't attempt to make a SubAlpha, the private constructor in SubAlpha is okay.
A, B, D, E, and F are incorrect based on the above information. (Objective 5.3)


12. Given:
class Building {
   Building() { System.out.print("b "); }
   Building(String name) {
      this(); 
      System.out.print("bn " + name);
   }
}
public class House extends Building {
   House() { System.out.print("h "); }
   House(String name) {
      this(); 
      System.out.print("hn " + name);
   }
   public static void main(String[] args) { new House("x "); }
}
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
Answer:
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.(Objectives 1.6, 5.4)


13. Given:
class Mammal {
String name = "furry ";
String makeNoise() { return "generic noise"; }
}
class Zebra extends Mammal {
String name = "stripes ";
String makeNoise() { return "bray"; }
}
public class ZooKeeper {
public static void main(String[] args) { new ZooKeeper().go(); }
void go() {
Mammal m = new Zebra();
System.out.println(m.name + m.makeNoise());
}
}
What is the result?
A. furry bray
B. stripes bray
C. furry generic noise
D. stripes generic noise
E. Compilation fails
F. An exception is thrown at runtime
Answer:
A is correct. Polymorphism is only for instance methods.
B, C, D, E, and F are incorrect based on the above information.(Objectives 1.5, 5.4)


14. You're designing a new online board game in which Floozels are a type of Jammers, Jammers can have Quizels, Quizels are a type of Klakker, and Floozels can have several Floozets. Which of the following fragments represent this design? (Choose all that apply.)
A.
import java.util.*;
interface Klakker { }
class Jammer { Set q; }
class Quizel implements Klakker { }
public class Floozel extends Jammer { List f; }
interface Floozet { }
B.
import java.util.*;
class Klakker { Set q; }
class Quizel extends Klakker { }
class Jammer { List f; }
class Floozet extends Floozel { }
public class Floozel { Set k; }
C.
import java.util.*;
class Floozet { }
class Quizel implements Klakker { }
class Jammer { List q; }
interface Klakker { }
class Floozel extends Jammer { List f; }
D.
import java.util.*;
interface Jammer extends Quizel { }
interface Klakker { }
interface Quizel extends Klakker { }
interface Floozel extends Jammer, Floozet { }
interface Floozet { }
Answer:
A and C are correct. The phrase "type of" indicates an "is-a" relationship (extends or implements), and the phrase “have” is of course a "has-a" relationship (usually instance variables).
B and D are incorrect based on the above information. (Objective 5.5)


15. Given:
class A { }

class B extends A { }

public class ComingThru {
  static String s = "-";
  
  public static void main(String[] args) {
  A[] aa = new A[2];
  B[] ba = new B[2];
  sifter(aa);
  sifter(ba);
  sifter(7);
  
  System.out.println(s);
  }
  
  static void sifter(A[]... a2) { s += "1"; }
  static void sifter(B[]... b1) { s += "2"; }
  static void sifter(B[] b1) { s += "3"; }
  static void sifter(Object o) { s += "4"; }
}
What is the result?
A. -124
B. -134
C. -424
D. -434
E. -444
F. Compilation fails
Answer:
D is correct. In general, overloaded var-args methods are chosen last. Remember that arrays are objects. Finally, an int can be boxed to an Integer and then "widened" to an Object.
A, B, C, E, and F are incorrect based on the above information.(Objective 1.5)


regards,
Tech Dexters Support Team,
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Jul 6, 2012

OCPJ Exercise - I


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
Answer:
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. (Objective 1.2)

2. Which method names follow the JavaBeans standard? (Choose all that apply.)
A. addSize
B. getCust
C. deleteRep
D. isColorado
E. putDimensions
Answer:
B and D use the valid prefixes 'get' and 'is'.
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. (Objective 1.4)

3. Given:
  1. class Voop {
  2. public static void main(String[] args) {
  3. doStuff(1);
  4. doStuff(1,2);
  5. }
  6.  // insert code here
  7. }
Which, inserted independently at line 6, will compile? (Choose all that apply.)
A. static void doStuff(int... doArgs) { }
B. static void doStuff(int[] doArgs) { }
C. static void doStuff(int doArgs...) { }
D. static void doStuff(int... doArgs, int y) { }
E. static void doStuff(int x, int... doArgs) { }
Answer:
A and E use valid var-args syntax.
B and C are invalid var-arg syntax, and D is invalid because the var-arg must be the last of a method's arguments. (Objective 1.4)

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
Answer:
A is correct; enums can have constructors and variables.
B, C, D, E, and F are incorrect; these lines all use correct syntax. (Objective 1.3)


5. Given two files:

1. package pkgA;
2. public class Foo {
3. int a = 5;
4. protected int b = 6;
5. public int c = 7;
6. }

3. package pkgB;
4. import pkgA.*;
5. public class Baz {
6. public static void main(String[] args) {
7. Foo f = new Foo();
8. System.out.print(" " + f.a);
9. System.out.print(" " + f.b);
10. System.out.print(" " + f.c);
11. }
12. }

What is the result? (Choose all that apply.)
A. 5 6 7
B. 5 followed by an exception
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
Answer:
D and E are correct. Variable a has default access, so it cannot be accessed from outside the package. Variable b has protected access in pkgA.
A, B, C, and F are incorrect based on the above information. (Objective 1.1)


6. 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
Answer:
A is correct; all of these are legal declarations.
B, C, D, E, and F are incorrect based on the above information. (Objective 1.2)


7. 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
Answer:
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. (Objective 1.3)


8. 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
Answer:
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. (Objective 1.3)


9. 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
Answer:
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. (Objective 1.4)



regards,
Tech Dexters Support Team,
Hyderabad.

for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses




Jul 5, 2012

Declaration and Access Control


Identifiers (Objective 1.3)

  •  Identifiers can begin with a letter, an underscore, or a currency character.
  •  After the first character, identifiers can also include digits.
  •  Identifiers can be of any length.
  •  JavaBeans methods must be named using camelCase, and depending on the method's purpose, must start with set, get, is, add, or remove.

Declaration Rules (Objective 1.1)

  • A source code file can have only one public class.
  • If the source file contains a public class, the filename must match the public class name.
  • A file can have only one package statement, but multiple imports.
  • The package statement (if any) must be the first (non-comment) line in a source file.
  • The import statements (if any) must come after the package and before the class declaration.
  • If there is no package statement, import statements must be the first (noncomment) statements in the source file.
  • package and import statements apply to all classes in the file.
  • A file can have more than one nonpublic class.
  • Files with no public classes have no naming restrictions.

Class Access Modifiers (Objective 1.1)

  • There are three access modifiers: public, protected, and private.
  • There are four access levels: public, protected, default, and private.
  • Classes can have only public or default access.
  • A class with default access can be seen only by classes within the same package.
  • A class with public access can be seen by all classes from all packages.
  • Class visibility revolves around whether code in one class can
    • Create an instance of another class
    • Extend (or subclass), another class
    • Access methods and variables of another class

Class Modifiers (Nonaccess) (Objective 1.2)

  • Classes can also be modified with final, abstract, or strictfp.
  • A class cannot be both final and abstract.
  • A final class cannot be subclassed.
  • An abstract class cannot be instantiated.
  • A single abstract method in a class means the whole class must be abstract.
  • An abstract class can have both abstract and nonabstract methods.
  • The first concrete class to extend an abstract class must implement all of its abstract methods.

 Member Access Modifiers (Objectives 1.3 and 1.4)

  • Methods and instance (nonlocal) variables are known as "members."
  • Members can use all four access levels: public, protected, default, private.
  • Member access comes in two forms:
    • Code in one class can access a member of another class.
    • A subclass can inherit a member of its superclass.
  • If a class cannot be accessed, its members cannot be accessed.
  • Determine class visibility before determining member visibility.
  • public members can be accessed by all other classes, even in other packages.
  • If a superclass member is public, the subclass inherits it—regardless of package.
  • Members accessed without the dot operator (.) must belong to the same class.
  • this. always refers to the currently executing object.
  • this.aMethod() is the same as just invoking aMethod().
  • private members can be accessed only by code in the same class.
  • private members are not visible to subclasses, so private members cannot be inherited.



Static Variables and Methods (Objective 1.4)

  • They are not tied to any particular instance of a class.
  • No classes instances are needed in order to use static members of the class.
  • There is only one copy of a static variable / class and all instances share it.
  • static methods do not have direct access to non-static members.

Enums (Objective 1.3)

  • An enum specifies a list of constant values assigned to a type.
  • An enum is NOT a String or an int; an enum constant's type is the enum type. For example, SUMMER and FALL are of the enum type Season.
  • An enum can be declared outside or inside a class, but NOT in a method.
  • An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor.
  • enum constructors can have arguments, and can be overloaded.
  • enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
  • The semicolon at the end of an enum declaration is optional. These are legal:
  • enum Foo { ONE, TWO, THREE}
  • enum Foo { ONE, TWO, THREE};
  • MyEnum.values() returns an array of MyEnum's values.

Methods with var-args (Objective 1.4)

  • As of Java 5, methods can declare a parameter that accepts from zero to many arguments, a so-called var-arg method.
  • A var-arg parameter is declared with the syntax type... name; for instance:                                                  doStuff(int... x) { }
  • A var-arg method can have only one var-arg parameter.
  • In methods with normal parameters and a var-arg, the var-arg must come last.




Jul 3, 2012

OCPJ Exam Objectives and Training Topics



Hi All,
Let us start a training process of Oracle Certificate in Java..
In series of further posts, We are discussing about following topics. 
  1. Declarations and Access Control
  2. Object Orientation
  3. Assignments
  4. Operators 
  5. Flow Control
  6. Exceptions
  7. Assertions
  8. Strings
  9. Input / Output
  10. Formatting, and Parsing 
  11. Generics and Collections
  12. Inner Classes
  13. Threads
  14. Development

For every topic I will give you some Drill Points later followed by some practice questions with solution and Explanation. At each topic we will specify the Exam Objective of the given problem.

Exam Objectives:
Prior to the traning session. I want to share Exam Objectives of OCPJ with you..

Objective 1: Declarations, Initialization and Scoping

  1. Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
  2. Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
  3. Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
  4. Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
  5. Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.

Objective 2: Flow Control

  1. Develop code that implements an if or switch statement; and identify legal argument types for these statements.
  2. Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
  3. Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
  4. Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
  5. Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
  6. Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

Objective 3: API Contents

  1. Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
  2. Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.
  3. Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
  4. Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.

Objective 4: Concurrency

  1. Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  2. Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
  3. Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

Objective 5: OO Concepts

  1. Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
  2. Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
  3. Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
  4. Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.
  5. Develop code that implements "is-a" and/or "has-a" relationships.

Objective 6: Collections / Generics

  1. Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
  2. Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
  3. Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.
  4. Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
  5. Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.

Objective 7: Fundamentals

  1. Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
  2. Given an example of a class and a command-line, determine the expected runtime behavior.
  3. Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
  4. Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.
  5. Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
  6. Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.
References


  1. SCJP Sun Certified Programmer for Java 6 Exam 310-065 by Katherine Sierra, Bert Bates
  2. http://www.javachamp.com/
  3. http://scjptest.com/
  4. http://education.oracle.com

regards,
Tech Dexters Support Team,
Hyderabad.

for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses