You are on page 1of 37

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Call Us at +44-208-133-7875 | Sign Out | My Cart | Change Password

Welcome Alex Fernandez !


Home My Account SCJP-6-Training Diagnostic Test Review of attempt 2

Diagnostic Test Review of attempt 2


Finish review

Started on Completed on Time taken Overdue Grade Feedback

Wednesday, 1 June 2011, 12:11 AM Thursday, 2 June 2011, 12:38 PM 1 day 12 hours 1 day 9 hours 2.67 out of a maximum of 60 (4%) FAIL

Feedback to Author

Drag and drop the appropriate choices to fill in the empty boxes, so that the following code works correctly. String str="April 19, 2005"; Date date = DateFormat. getDateInstance DateFormat.LONG parse getDateInstance DateFormat.Default DateFormat.MEDIUM getDate format DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The DateFormat.parse(String source) method parses text from the beginning of the given string to produce a date. Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG, and FULL. The SHORT format consists entirely of numbers while the FULL format contains most of the date components. There is also a default format called DEFAULT and is the same as MEDIUM. Here, str uses the LONG format, so we need to pass in DateFormat.LONG to the getDateInstance method. Check out the DateFormat API at http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html Partially correct
Marks for this submission: 0.67/1.

( DateFormat.MEDIUM

,Locale.US). parse

(str);

Feedback to Author

Drag and drop the given choices in the blanks such that the following code extracts the e-mail ids from the String "The e-mail ids are tom@abc.com and harry@xyz.com". class Test { public static void main(String[] args) { String regex = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*"; String s = "The e-mail ids are tom@abc.com and harry@xyz.com"; Pattern pattern = Pattern. compile Matcher matcher = pattern. matcher while (matcher. find() ) ( regex (s ); );

1 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


{ } } } group() s regex compile matcher find()

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

System.out.println("The e-mail id is: " + matcher. group()

);

The compile method of the Pattern class compiles the given regular expression into a pattern, then the matcher method creates a matcher that will match the given input against this pattern. The find method scans the input sequence looking for the next sequence that matches the pattern. The group method returns the input subsequence matched by the previous match. Now let us analyze how the given regular expression helps in extracting the e-mail ids. The (\w+) grouping looks for word characters, as denoted by the \w. The + indicates that one or more word characters must appear. This must be followed by a literal @ character. The (\w+\.) grouping is similar, but expects a period to follow in order to make a match. The period has been escaped using a backslash because the period character is itself a regex meta-character (a wildcard that matches any character). The next (\w+) grouping is identical to the first grouping -- it looks for one or more word characters. Finally the expression (\.\w+)* asks to 'match a period followed by one or more word characters, and match that combination zero or more times'. Correct
Marks for this submission: 1/1.

Feedback to Author

Drag and drop the code excerpts below in order to complete the following code. String s=new String(); StringBuilder sb=new StringBuilder(); Formatter formatter=new Formatter( sb , Locale.US ); formatter.format("PI=%12.10f",Math.PI); s = String. format ("His name is %1s %2s", "Thomas", "Edison"); System.out.println(s); System.out.println(sb); Locale.US s sb format printf "US" The formatter class has a constructor which creates a new formatter with the specified destination and locale. Formatter(Appendable a, Locale I) The Appendable interface must be implemented by any class whose instances are intended to receive formatted output from a Formatter. This interface is implemented by StringBuilder and not by the String Class. Formatter format(String format, Object....args) The format method of the string class returns a formatted string using the specified format string and arguments. Correct
Marks for this submission: 1/1.

Feedback to Author

Please drag and drop the correct elements to complete the following code.
PrintWriter

wr=new PrintWriter

(new OutputStreamWriter

(new FileWriter(fileName)));

wr.println("hello") wr.close();

2 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


PrintWriter OutputStreamWriter BufferedWriter PrintWriter

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

PrintWriter wr=new PrintWriter(new BufferedWriter(new FileWriter(fileName))); The BufferedWriter is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. It is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as the FileWriter in this question statement. The BufferedWriter can then be passed a PrintWriter, which writes to the underlying stream using the println method. More information here. http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedWriter.html Partially correct
Marks for this submission: 0.67/1.

Feedback to Author

Drag and drop the code excerpts below to complete the following program so that the contents of the file a.txt are printed one line at a time. public static void main(String[] args) { try { Scanner scanner = new Scanner( scanner. while ( ) System.out.println( ); } { e.printStackTrace(); } } catch (FileNotFoundException e) scanner.next() scanner.hasNext() useDelimiter("\n"); scanner.close(); new File("a.txt") "a.txt" finally setDelimiter("\ n") catch (ScannerException e) new File(fileName) scanner.nextElement() scanner.hasMoreElements() The java.util.Scanner class makes it easier to read and parse strings and primitive types using regular expressions. In this program, the Scanner breaks the contents of the File into tokens using a delimiter pattern. You can change the delimiter that is used to tokenize the input through the useDelimiter() method of the Scanner class. You can pass in a String or a java.util.regex.Pattern to the method. You can read the input one line at a time by using the newline character (\n) as a delimiter. The hasNext() method in the Scanner class returns true if another token exists in the Scanner's input, which is the case until it reaches the end of the file. The next() method returns a String that represents the next token. So until it reaches the end of the file, TextScanner prints all String objects returned by next() on a separate line. Want to know more ? Refer to the following links: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html http://java.sun.com/developer/JDCTechTips/2004/tt1201.html#1 Incorrect
Marks for this submission: 0/1.

);

Feedback to Author

Drag and drop the relevant choice to fill in the blanks in the following code so that the output is

3 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Dog is man's friend Ah, apples all over class Split1 { public static void main (String[] args[]) { Pattern p=Pattern.compile( words=p. for ( word ); ("Dog5is6man's78friend"); words)

System.out.println (word); String s1=new String("Aaaah, apples all over"); String[] splits =s1.split( , );

for(int i=0; i<splits.length; i++) System.out.printf(splits[i]); } } String[] "\\d" 5 : String "a" split substr "\d" "d" 4 6 The split method is defined by both Pattern and String classes. It splits the given input sequence around matches of a delimiter pattern. public String[] split(String regex) In using a regular expression as a delimiter, the split() method basically starts at the start of the string and finds the first occurrence of the regular expression. The regular expression "\\d" will find a match with a numeric digit. So the tokens returned by p.split ("Dog5is6man's78friend") would be "Dog", "is", "mans", "friend". There is another form of split method which takes a limit argument- public String[] split(String regex, int limit). The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. So the tokens returned by s1.split("a",4) would be "A", "", "", "h, apples all over". Want to know more? Please refer to http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

Which of the following methods of the Pattern class have equivalent methods in the String class? Select two choices. Choose at least one answer.
a. split b. matches

4 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

c. compile d. group

Choices A and B are the correct answers. Regular expression support has also been introduced in the java.lang.String class through several methods that mimic the behavior of java.util.regex.Pattern. public boolean matches(String regex): Tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str). public String[] split(String regex, int limit): Splits this string around matches of the given regular expression. An invocation of this method of the form str.split(regex, n) yields the same result as the expression Pattern.compile(regex).split(str, n). public String[] split(String regex): Splits this string around matches of the given regular expression. This method works the same as if you invoked the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are not included in the resulting array. Want to know more? Check out http://java.sun.com/docs/books/tutorial/extra/regex/pattern.html http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

Which of the following statements will compile without errors and print "5 + 6 = 11" when inserted at line 6 independently? class Test { public static void main(String[] args) { int x = 5; int y = 6; int sum = x + y; // line 6 } } Choose one answer.
a. System.out.format("%d + %d = %d\n", x, y, sum); b. System.out.printf("%d + %d = %d\n", x, y, sum); c. System.out.println(x + " + " + y + " = " + sum); d. All of the above

Choice D is the correct answer. Starting with Java 5, you can use System.out.printf() to send formatted numerical output to the console. It uses a java.util.Formatter object internally. printf (String format, Object... args) The format argument is a String object in which you embed specifier substrings that indicate how the arguments should be formatted in the output. You can get more information about the printf method at http://java.sun.com/j2se/5.0/docs/api/java/io /PrintStream.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

In the class Prop, how do you read the value of the system property 'FOO' set using the command 'java -DFOO=bar Prop FOO'? Select two choices. Choose at least one answer.
a. System.getProperty("FOO"); b. System.property("FOO"); c. System.getProperties().get("FOO"); d. System.getPropertyValue("FOO"); e. System.findProperty("FOO");

Choices A and C are the correct answers.

5 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

You can read the value of a system property that has been set using the -D command-line switch in two ways. public static String getProperty(String key) This method returns the property value corresponding to the key passed. public static Properties getProperties() This method returns a Properties object containing all the system properties. Then we can call the get(String) method on the Properties object to get a particular property value. Note that the difference between the two methods is that the former one returns a String object while the later one returns an Object that has to be cast to String before use as the Properties class is a subclass of the Hashtable class. For more information, refer to http://java.sun.com/docs/books/tutorial/essential/system/properties.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

10

Given the following code : File f = new File("myfile.txt"); What method will cause the file "myfile.txt" to be created in the underlying operating system? Choose one answer.
a. f.write(); b. f.close(); c. f.flush(); d. None of the above

Choice D is the correct answer. The File class mainly describes a file that might exist. To actually create it in the underlying file system, you need to pass the instance of the File class to an instance of one of the OutputStream or Writer classes. For example, File f = new File("test.txt"); FileOutputStream fos = new FileOutputStream(f); Read about the File class at http://java.sun.com/j2se/1.5/docs/api/java/io/File.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

11

In a thread, the wait() method must be called within which of the following? Choose one answer.
a. A while loop b. The run() method c. synchronized code d. The constructor e. It doesn't matter where the wait()method is called from

Choice C is the correct answer. The wait() method is defined in the Object class. The wait() method can only be called from within synchronized code, also it should be invoked only by the thread which currently owns the lock of the object on which wait() is invoked. The thread releases the lock and goes into the waiting state when this method is invoked. Incorrect
Marks for this submission: 0/1.

Feedback to Author

12

What will be the output when compiling and running the following code? public class MyThread implements Runnable {

6 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


String myString = "Yes "; public void run() { this.myString = "No "; } public static void main(String[] args) { MyThread t = new MyThread(); new Thread(t).start(); for (int i=0; i < 10; i++) System.out.print(t.myString); }

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choose one answer.

a. Compilation error. b. Prints: Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on. c. Prints: No No No No No No No No No No and so on. d. Prints: Yes No Yes No Yes No Yes No Yes No and so on. e. The output cannot be determined.

Choice E is the correct answer. Please note that there will not be any compilation error when the above code is compiled. Also note that calling the start() method on a Thread doesn't start the Thread. It only makes a Thread ready to be scheduled for execution. Depending on the operating system and on the other running threads, the thread on which start() is called will get executed. In the above case, it is not guaranteed that the thread will be executed (i.e., that its run() method will be called), always before the "for" loop is executed. Thus the output cannot be determined. Incorrect

Marks for this submission: 0/1.

Feedback to Author

13

What will happen when you attempt to compile and run the following code? public class Test { int i = 0; public static void main(String[] argv) { Test t = new Test(); t.myMethod(); } public void myMethod() { while(true) { try { wait(); } catch (InterruptedException e) { } i++; } }

Choose one answer.

a. Compile-time error, no matching notify method b. Compiles and runs in an infinite loop c. Compiles and runs without producing any output d. IllegalMonitorStateException is thrown

Choice D is the correct answer. The wait()/notify() methods can only be used within a code segment that is synchronized. Only a thread which owns the lock of the object can invoke these methods. In this case, the calling code is not synchronized and will thus cause an IllegalMonitorStateException at runtime. Since the code compiles fine, choice A is incorrect.

7 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Since an exception is thrown, choices B and C are incorrect. Check out the API for more about the wait and notify methods http://java.sun.com/j2se/1.5.0/docs/api/java/lang /Object.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

14

What will happen when you attempt to compile and run the following code? 1. public class RecurThread extends Thread 2. { 3. public void run() 4. { 5. System.out.println("Java Threads"); 6. start(); 7. } 8. 9. public static void main(String[] args) 10. { 11. RecurThread t1 = new RecurThread(); 12. t1.start(); 13. } 14. } Choose one answer.
a. It will repetitively print - Java Threads. b. The code will not compile. c. It will throw IllegalThreadStateException at runtime. d. It will throw StackOverflowError at runtime.

Choice C is the correct answer. The code will compile without any error, but it will throw an IllegalThreadStateException at runtime. At line 12, the t1.start() invocation schedules the thread for execution. When the run() method of this thread is executed, the statement at line 5 prints "Java Threads". But at line 6, the start() invocation is encountered, since the thread has been already started (at line 12). This invocation results in an IllegalThreadStateException being thrown at runtime. Thus, the invocation at line 6 effectively becomes the second invocation after line 12 to start the same thread. It does not become a recursive call, as it might seem apparently. It is important to understand that you can invoke the start() method only once for each thread, invoking it again results in an IllegalThreadStateException being thrown at runtime. Want to know more? The following article discusses important concepts about multithreading http://www.developerlife.com/lessons/threadsintro/default.htm Incorrect
Marks for this submission: 0/1.

Feedback to Author

15

What will be the result of compiling and running the following program? class TestThread extends Thread { private int i; public void run() { i++; } public static void main(String[] args) { TestThread a = new TestThread(); a.run(); System.out.print(a.i); a.start(); System.out.print(a.i); }

8 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choose one answer.

a. Compiler error b. IllegalThreadStateException is thrown c. Prints "11" d. Prints "12" e. Prints "00" f. Prints "01" g. Prints "11" or "12" h. Prints "00" or "01"

Choice G is the correct answer. Here, first the run() method of the object refered to by a is directly invoked. When the run() method of a Thread is invoked instead of the start() method, it is executed by the same thread as a conventional method. So it increments i to 1, now the output is 1. After this, the invocation of the start() method schedules a new thread of execution. Now it is impossible to predict whether the new thread will run first or the second print statement will be executed by the main thread first. So the result of the second print statement can be 1 or 2 depending on the scheduling of the 2 threads. Refer to http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

16

What will happen when you attempt to compile and run the following code? 1. public class ThreadDemo 2. { 3. private int count = 1; 4. 5. public synchronized void doSomething() 6. { 7. for(int i=0; i < 10; i++) 8. System.out.println(count++); 9. } 10. 11. public static void main(String[] args) 12. { 13. ThreadDemo demo = new ThreadDemo(); 14. Thread a1 = new A(demo); 15. Thread a2 = new A(demo); 16. a1.start(); 17. a2.start(); 18. } 19. } 20. 21. class A extends Thread 22. { 23. ThreadDemo demo; 24. public A(ThreadDemo td) 25. { 26. demo = td; 27. } 28. public void run() 29. { 30. demo.doSomething(); 31. } 32. } Choose one answer.
a. It will print the numbers 0 to 19 sequentially. b. It will print the numbers 1 to 20 sequentially. c. It will print the numbers 1 to 20, but the order cannot be determined. d. It will print the numbers 0 to 19, but the order cannot be determined. e. The code will not compile.

Choice B is the correct answer. The code will compile without any error and it will print the numbers 1 to 20 sequentially. The doSomething() method is a synchronized method, hence when one thread is executing this method; the other

9 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

threads must wait to obtain the lock of this object. When two thread objects a1 and a2 are created, and their start() methods are invoked, any one of these two threads will obtain the lock on the ThreadDemo instance, and its run() method will invoke the doSomething() method, printing values 1 to 10 (note that count is 1 initially). Once the first thread completes its execution, the second thread will start executing, starting from 11 (since value of the variable 'count' is now 11). The other thread will print values from 11 to 20. Note that the doSomething() method prints the value of the variable 'count', which starts from 1; and not the local variable 'i', which starts from 0. Want to know more? The following article discusses important concepts about multithreading http://www.developerlife.com/lessons/threadsintro/default.htm Incorrect
Marks for this submission: 0/1.

Feedback to Author

17

What will be the result of compiling and running the following program code? class TestThread extends Thread { public void restart() { startMe(); } public static void startMe() { synchronized(TestThread.class) { TestThread.class.notifyAll(); System.out.println("Trying to Notify"); } } public void run() { try { synchronized(this) { wait(); System.out.println("Notified"); } } catch(InterruptedException e) {} } public static void main(String[] args) { TestThread t1 = new TestThread(); t1.start(); t1.restart(); }

Choose one answer.

a. "Trying to Notify" is printed followed by "Notified" b. Only "Trying to Notify" is printed c. No output d. Compiler error e. Throws an exception at runtime

Choice B is the correct answer. Here, we first start the thread t1, which locks the object t1 and goes into the waiting state. The main thread then invokes the restart() method on t1, which invokes the static method startMe(). The startMe()method gets the lock on the class object TestThread.class, then it calls notifyAll(). Here note that the lock on object t1 is different from the lock on the class TestThread. Both are independent of each other. So this notifyAll() cannot bring the waiting thread t1 out of the waiting state. So it keeps waiting indefinitely. So the output is just "Trying to notify". Incorrect

Marks for this submission: 0/1.

10 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Feedback to Author

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

18

Please drag and drop the given code excerpts to complete the following code so that the output is "Book". Grade{A { B, C, D}; public class EnumTest { public static void main(String[] args) { Grade grade= ; switch(grade) { case : System.out.println(grade); break; default : System.out.println("Default"); } } } Grade.A public String toString(){return "Book";} enum Enum "Book" A return "Book" Enumerated types are declared using the enum keyword. Here Grade is an enumerated type and A, B, and C are the values for that type. You can add methods to an Enum type just as you would add methods to a Java class. The toString() method on an enumerated type returns the name of the value. In this case, the name given for the value A is "Book". The switch statement now supports the use of enum values. You must not prefix each enumerated type with the enum class name, in the case statement. So it is 'case A' and not 'case Grade.A'. Want to know more about enums? Check out http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9 http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html Incorrect
Marks for this submission: 0/1.

},

Feedback to Author

19

Drag and drop the correct elements to complete the following code so that the command line arguments are printed to the out put stream. Assume that the class is in the package called pract.

public class Test { public static void main(String[] args) { for( :args) out.println( } } import static java.lang.System.out.println; s String s package pract; );

11 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


int i=0; args[i] import package pract.*; import static java.lang.System.out; import static java.lang.System;

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

The package statement is used to declare that a class belongs to a particular package. It appears above all the class declarations and import statements, if any. So, in this question, 'package pract' is the first line in the source file. To be able to use the System.out.println by simply mentioning out.println, the static out variable in the System class needs to be imported using static imports. However, the println method cannot be imported this way, since it is not static. Also, the System class cannot be imported by static import. The enhanced for loop is of the form: for ( VariableModifiersopt Type Identifier: Expression) Statement Here it is of the form for(String s:args) out.println(s); To know more about static imports, refer to http://java.sun.com/docs/books/jls/third_edition/html/packages.html#7.5.3 To know more about the enhanced for loop http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2 Incorrect
Marks for this submission: 0/1.

Feedback to Author

20

Which of the following statements about StringBuilder are true? Select two choices. Choose at least one answer.
a. It has inherent thread protection. b. It is faster than StringBuffer. c. It defines the append and insert methods. d. It is immutable.

Choices B and C are the correct answers. StringBuilder represents a mutable sequence of characters. Even though it is similar to StringBuffer in most aspects, they both differ on the thread protection aspect. StringBuilder instances are not safe for use by multiple threads, while StringBuffer instances have inherent thread protection. This makes StringBuilder faster than StringBuffer. So choice A is incorrect while choice B is correct. Both StringBuilder and StringBuffer classes define the append and insert methods, so choice C is also correct. Since StringBuilder is mutable, choice D is incorrect. For more information, you may refer to http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

21

What is the result of compiling and running the following program? class First { public Object method1() { System.out.println("Calling super class method"); return new String("Base"); } } class Second extends First { public String method1() { System.out.println("Calling sub class method"); return new String("Derived"); } }

12 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

public class CovariantTest2 { public static void main(String[] args) { First o = new Second(); String s=o.method1(); System.out.println(s); } } Choose one answer.
a. Does not compile because the return type must be the same for the overriding method b. Compiles but throws runtime exception c. Prints "Base" d. Prints "Derived" e. None of these

Choice E is the correct answer. This program does not compile, the reason is that the object reference used to invoke the method is of the super class type, so the return type must match the return type declared by the super class version of the method. Here the super class version declares Object as the return type, so you need to cast the result to the String type, when the method is invoked. Choice A is incorrect because the covariant return types feature in Java allows a method in a subclass to return an object whose type is a subclass of the type returned by the method with the same signature in the super class. Choices B, C, and D are incorrect since compilation fails, as explained above. For more information, refer to http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.5 Incorrect
Marks for this submission: 0/1.

Feedback to Author

22

What is the result of compiling and running the following program? class First { public Object method1() { return new String("Base"); } } class Second extends First { public String method1() { return new String("Derived"); } } public class CovariantTest2 { public static void main(String[] args) { First o = new Second(); String s=(String)o.method1(); System.out.println(s); } } Choose one answer.
a. Prints "Base" b. Prints "Derived" c. Does not compile d. Throws exception at runtime

Choice B is the correct answer. The program compiles fine and prints "Derived" when run. Though the object reference used for invoking the method is of super class type, the actual object is of type subclass. So the method called is the one declared in the subclass,

13 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

which prints "Derived". There are no compilation or casting errors, because it is a valid way of overriding using covariant return types. So choices C and D are incorrect. To know more about the covariant return types feature, refer to http://java.sun.com/developer/JDCTechTips /2004/tt1201.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

23

Which of the following choices is the correct set of methods for getting and setting the value of a boolean property 'done' according to Java Bean naming standards? Select two choices. Choose at least one answer.
a. public void setDone(boolean done) public boolean getDone() b. public void setDone(boolean done) public boolean isDone() c. public void setdone(boolean done) public boolean getdone() d. public void setdone(boolean done) public boolean isdone() e. public void getDone(boolean done) public boolean setDone()

Choices A and B are the correct answers. According to the JavaBean naming standards, if the property name is 'x' and the type is Type, the accessor method is of the form: public Type getX() and the mutator method is of the form: public void setX(Type newValue) So choice A is correct. For boolean properties, the accessor method can have the prefix 'is' or 'get'. So the following form is also allowed. public boolean isX() public void setX(boolean newValue) So choice E is incorrect, while choice B is correct. Please note that the starting letter of the property name is capitalized in the accessor and mutator methods. So choices C and D also incorrect. Incorrect
Marks for this submission: 0/1.

Feedback to Author

24

What will be the result of compiling and executing the following code? public static void main(String[] args) { int x = 10; int y; if (x < 100) y = x / 0; if (x >= 100) y = x * 0; System.out.println("The value of y is: " + y); } Choose one answer.
a. Compiler Error b. Prints "The value of y is: 0" c. Throws ArithmeticException d. None of these

Choice A is the correct answer. The code will not compile raising an error that the local variable y might not have been initialized. Unlike member variables, local variables are not automatically initialized to the default values for their declared type. The compiler reports an error if you attempt to use a local variable which has not been initialized under every circumstances. Since the code does not compile, all the other choices are automatically incorrect. For more information, refer to http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.5 Incorrect
Marks for this submission: 0/1.

14 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Feedback to Author

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

25

What will happen when the following code is compiled and run? 1. public class MyClass 2. { 3. int maxElements; 4. void MyClass() 5. { 6. maxElements = 100; 7. System.out.println(maxElements); 8. } 9. public MyClass(int i) 10. { 11. maxElements = i; 12. System.out.println(maxElements); 13. } 14. public static void main(String[] args) 15. { 16. MyClass a = new MyClass(); 17. MyClass b = new MyClass(999); 18. } 19. } Choose one answer.
a. Prints 100 followed by 999 on different lines b. Prints 999 followed by 100 on different lines c. Compilation error at line 4 d. Compilation error at line 16

Choice D is the correct answer. Upon instantiation of MyClass on line 16, the compiler looks for a paramaterless constructor. As there is an overloaded constructor defined, the default constructor (with no arguments) will not be provided by the compiler. Since there is no matching constructor, the code does not compile here. void MyClass() is a normal method and not a constructor since constructors do not have a return value. Since it is a legal method definition, there are no compiler errors at line 4. So choice C is incorrect. Choices A and B are incorrect since the code does not compile. To learn about constructors, refer to http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

26

What is the result of compiling and running the following program? (Assume that the command line arguments 0, 1, and 2 are passed to it) class VarArgTest { public static void f(String... a) { for(String i : a) System.out.print("A"+i); } public static void f(String[] a) { for(String i : a) System.out.print("B"+i); } public static void main(String[] args) { f(args); } } Choose one answer.
a. Compiler Error b. Exception at runtime c. Prints "A0A1A2" d. Prints "B0B1B2" e. None of these

15 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choice A is the correct answer. The code does not compile because the method call made matches with both the methods in the class. Variable arguments (varargs) allow you to specify that a method can take multiple arguments of the same type and don't require that the number of arguments be predetermined. A method can have at most one parameter that is a vararg, it must be the last parameter taken by the method, and it is denoted by the object type, a set of ellipses ( ... ), and the name of the variable. When you specify a variable-length argument list, it is read as "create an array of type <type of varargs>". So the two methods in this class are equivalent, which causes ambiguity for the compiler. Since the program does not compile, the other choices are automatically incorrect. Refer to http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html for more on how to use varargs. Incorrect
Marks for this submission: 0/1.

Feedback to Author

27

Drag and drop the given class definitions corresponding to their relationships. Subclass of IllegalArgumentException Thrown when an assertion fails Thrown when an application recurses too deeply Thrown when an unexpected exception has occurred in a static initializer AssertionError StackOverflowError NumberFormatException ExceptionInInitializerError AssertionException IllegalStateException RecursionError NullPointerException StaticInitializerError NumberFormatException is thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. It is a subclass of IllegalArgumentException. AssertionError is thrown to indicate that an assertion has failed. StackOverflowError is thrown when a stack overflow occurs because an application recurses too deeply. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable. Incorrect
Marks for this submission: 0/1.

Feedback to Author

28

Drag and drop the correct elements so that the following code compiles and runs, printing "catch1finally1finally2" class Test { void f() { throw new ; } public static void main (String[ ] args) { Test t=new Test(); try { t.f(); throw new Throwable(); } catch ( { try { e)

Exception

throw

16 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


} catch(Exception ex) { System.out.print("catch1"); ex; } finally { System.out.print("finally1"); }

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

} finally { System.out.print("finally2"); System.exit(0); }

throws Throwable() RuntimeException() (Exception)e throw e Throwable The code demonstrates the use of nested try/catch blocks for exception handling. The method f() throws RuntimeException, which is caught by the catch block with a Throwable argument. This is possible because RuntimeException is a subclass of Exception which inherits from Throwable. Within the catch block, there is a nested try block. Here the code prints "catch1", then rethrows the exception, which is again caught by its corresponding catch. From the catch block, the exception is rethrown again. Before the exception propagates outside, the control moves to the finally block, where "finally1" is printed. Now the control reaches the enclosing finally block producing the output "finally2". Want to know more about exceptions? Check out http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html http://java.sun.com/docs/books/tutorial/essential/exceptions/handling.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

29

Which of the following choices is the last line of output, when the code below is executed? public class Test { public static void main(String[] args) { int counter = 0; outer: for(int i = 0; i < 4; ++i) middle: for(int j = 0; j < 4; ++j) inner: for(int k = 0; k < 4; ++k) { System.out.println("Hello - " + ++counter); if((k % 4) == 0) break outer; } } } Choose one answer.
a. Hello - 1 b. Hello - 4 c. Hello - 0 d. None of the above

Choice A is the correct answer. Since 0 mod 4 is 0, the inner loop is executed only once and then the break statement will be called, which completes the main method, and thus, the final line of output would be Hello - 1.

17 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Want to know more about the for and break statements?

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Check out the following links http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.1 http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15 Incorrect


Marks for this submission: 0/1.

Feedback to Author

30

What will be the result of executing the following code? public static void main(String[] args) { char digit = 'a'; for (int i = 0; i < 10; i++) { switch (digit) { case 'x' : { int j = 0; System.out.println(j); } default : { int j = 100; System.out.println(j); } } } int i = j; System.out.println(i); } Choose one answer.
a. 100 will be printed 11 times. b. 100 will be printed 10 times and then there will be a runtime exception. c. The code will not compile because the variable i cannot be declared twice within the main() method. d. The code will not compile because the variable j cannot be declared twice within the switch statement. e. None of these.

Choice E is the correct answer. The code will not compile. There is no problem with the declaration of another variable i as both variables are in disjoint blocks (the first one is inside the for loop and its scope is limited to the for loop, whereas the second is outside the for loop) and, therefore, in different scopes. The problem is with the variable j. The two declarations of the variable j are perfectly valid as they are in disjoint blocks and, therefore, different scopes. The error is that both declarations of j are not available outside the case or default statements, whereas we are trying to assign it to the variable i. Therefore, the compiler complains and reports that the variable j cannot be found. You can read more about the switch statement at http://java.sun.com/docs/books/jls/third_edition /html/statements.html#14.11 Incorrect
Marks for this submission: 0/1.

Feedback to Author

31

What will be the result of compiling and running the following code? Assume that assertions are enabled at compile time as well as at runtime. class Test { String f(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } } public static void main(String[] args)

18 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


{

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Test t = new Test(); for (int i = 0; i < 4; i++) { System.out.print(t.f(i)); }

Choose one answer.

a. Prints "ABC" and throws AssertionError b. Prints "ABC" and throws AssertionException c. Prints "ABC" and exits without any error d. Compilation error e. None of the above

Choice D is the correct answer. This code does not compile because if the method containing the switch statement is declared with a non void return type and if no return statement appears after the switch statement, then each case of the switch must have a return statement or a throw statement. Here there is no return statement after the switch statement, so all the cases should have had a return or throw statement. The default case has no return statement here, so the compiler will complain because assertions might not always be enabled. Here, instead of assert false, you can use throw AssertionError which will be executed even if assertions are disabled. To know more about the assert statement, refer to http://java.sun.com/docs/books/jls/third_edition /html/statements.html#14.10 Incorrect
Marks for this submission: 0/1.

Feedback to Author

32

What is the result of compiling and running the following code? class Test { public static void main(String[] args) { int i=0; try { for ( ; true ; i++ ) //1 { if( i/i++ > 0) break; // 2 } } catch(RuntimeException e) { System.out.println("RuntimeException"); } catch(ArithmeticException e) { System.out.println("ArithmeticException"); } catch(Exception e) { System.out.println("Exception"); } finally { System.out.println("finally"); } } } Choose one answer.
a. Compiles and runs, no exceptions are thrown. Prints "finally" b. Compiler error at line 1 c. Compiler error at line 2 d. Compiles and runs, prints "Arithmetic Exception" and "finally"

19 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

e. Compiles and runs, prints "RuntimeException", "ArithmeticException", and "finally" f. Compiles and runs, prints "RuntimeException" and "finally" g. Compiles and runs, prints "Exception" and "finally" h. None of the above

Choice H is the correct answer. The program does not compile, but not because of errors in lines 1 and 2. Thus, choices B and C are incorrect. ArithmeticException is the subclass of RuntimeException. Notice that the catch clause for RuntimeException is above that of ArithmeticException. It means that if ArithmeticException occurs, it will be caught by the first catch itself and control will never reach the second catch. Compiler sees this and complains that ArithmeticException has already been handled once, and that it cannot be handled again. The rule to understand here is that the more specific exceptions should always be handled first. Here ArithmeticException is more specific than RuntimeException, so its catch clause should come first. Thus, choice H is correct while the remaining choices are incorrect. Learn more about exceptions at http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#11.5" Incorrect
Marks for this submission: 0/1.

Feedback to Author

33

What will be the result of attempting to compile and run the following program? class Test { void f() { throw new RuntimeException(); } public static void main (String[] args) throws Exception { Test t=new Test(); try { t.f(); } catch (Throwable e) { try { throw (Exception)e; } catch(Exception ex) { System.out.print("catch1 "); return; } finally { System.out.print("finally1 "); return; } } finally { System.out.print("finally2 "); } } } Choose one answer.
a. Compiler error b. Prints "catch1 finally1" c. Prints "catch1 finally1 finally2" d. Prints "finally2" e. None of the above

Choice C is the correct answer. There are no errors in this program. It has two try/catch/finally blocks, one is nested inside the other. If the Throwable object had not been cast to the Exception type, the program wouldn't have compiled because the inner catch block only handles Exception and the main method also does not declare to throw Throwable.

20 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Now when the program runs, the control moves to the main catch block where it is thrown again and handled by the inner catch block. Then the inner finally block is executed, followed by the outer one. So the output is "catch1 finally1 finally2". Note that even though there is a return statement in the catch block, the code inside the inally block will still be executed. Incorrect
Marks for this submission: 0/1.

Feedback to Author

34

What will appear in the standard output if tryThis() throws an IOException at runtime? 1. try 2. { 3. tryThis(); 4. return; 5. } 6. catch(IOException x1) 7. { 8. System.out.println("exception 1"); 9. return; 10. } 11. catch(Exception x2) 12. { 13. System.out.println("exception 2"); 14. return; 15. } 16. finally 17. { 18. System.out.println("finally"); 19. } Choose one answer.
a. "exception 1" followed by "finally" b. "exception 2" followed by "finally" c. "exception 1" d. "exception 2"

Choice A is the correct answer. Regardless of whether or not an exception occurred, or whether or not it was handled, execution proceeds next to the finally block associated with the try block. Here the exception gets handled in lines 6 to 9 and then the execution proceeds to the finally block at line 16. Hence the output is "exception 1" followed by "finally". Incorrect
Marks for this submission: 0/1.

Feedback to Author

35

You would like to print the message "No Errors" if the String reference variable s is neither null nor referring to a zero length String. Select the correct choices in the given code below to achieve this goal? if( ) System.out.println("No Errors");

&& s.length > 0 s!=null s.length()==0 s.length()>0 s.length==0 | || & The length() method of the String class returns the length of the String. Here if s is null, the statement s.length()>0, will throw NullPointerException. So this statement must not be executed if s is null. The & operator always evaluates both operands, so s.length() will be executed under all circumstances if & is used. && is a short circuit operator. If the left hand operand is evaluated to false, the right hand operand will not be evaluated and thus no exception will be thrown. So the statement s.length() > 0 will be executed only if s !=null is true. If both cases are satisfied, the message "No Errors" will be printed. Incorrect
Marks for this submission: 0/1.

21 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Feedback to Author

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

36

Drag and drop the right option so that the result is 12. int i=4; = ; System.out.println(i); --i i* i+ i/ i-iThe code demonstrates the use of the overloaded assignment operators. The statement i*=--i; is the same as i=i*(--i); The result of the expression --i is 4-1=3. So the expression i*(--i) can be evaluated as 4*3=12. The other expressions listed in the choices, do not evaluate to a result of 12. Read more about assignment operators at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5281 Incorrect
Marks for this submission: 0/1.

Feedback to Author

37

Drag and drop the method descriptions which match the method names below. The finalize method The System.gc() method May cause the garbage collector to run Causes the garbage collector to run immediately May or maynot be called just before garbage collection happens Can be used to resurrect an object It is possible to create new live references to the object on which the finalize() method is invoked. This puts the object back into a reachable state. This practice is known as resurrection, however it is worth mentioning that this is not recommended. The finalize() method of an object will be definitely called before garbage collection happens, though it is not guaranteed that an object will be garbage collected or not, during its life time. The System.gc() statement merely *suggests* that the Java Virtual Machine expend effort toward recycling unused objects in order to free the memory they currently occupy. So it may cause the garbage collector to run but there is absolutely no guarantee. Want to know more? You can read more about garbage collection at http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html http://www.developer.com/tech/article.php/628881 Also, the API documentation of the Object class contains the necessary information about the finalize() method http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

38

How many object references will be referring to the object created at line 7, after the execution of line 11 in the following code? 1. public class TestGC 2. { 3. public static void main(String[] args) 4. { 5. Object x = new Integer(10); 6. Object y = new Long(100); 7. Object z = new StringBuffer("Garbage"); 8. Object obj = x; 9. x = z; 10. z = y; 11. y = x; // Remaining code here }

22 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


} Choose one answer.
a. 0 b. 1 c. 2 d. 3

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choice C is the correct answer. There will be two object references, 'x' and 'y' referring to the object created at line 7, after the execution of line 11. Now let us look at the execution of the code. Lines 5, 6, and 7 create three objects - Integer, Long, and StringBuffer referred to by three object references x, y, and z respectively. After the execution of line 8, the object reference 'obj' refers to the Integer object referred to by 'x'. At line 9, 'x' starts referring to the StringBuffer object referred to by 'z'. At line 10, 'z' starts referring to the Long object referred to by 'y'. At line 11, 'y' starts referring to the StringBuffer object, which is also being referred to by 'x'. Thus, after execution of line 11, the Integer object is referred to by 'obj' (assigned at line 8), the Long object is referred to by 'z' (assigned at line 10), and the StringBuffer object is referred to by 'x' and 'y' (assigned at line 9 and line 11). Hence, there will be two object references referring to the StringBuffer object created at line 7, after the execution of line 11. It is important to understand and track the object references to a particular object in the given code. An object with 0 (zero) references is a candidate for garbage collection. Want to know more? You can read more about garbage collection at http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html http://www.developer.com/tech/article.php/628881 Incorrect
Marks for this submission: 0/1.

Feedback to Author

39

What will happen when you attempt to compile and run the following code? public class Static { static { int x = 5; } static int x,y; public static void main(String[] args) { x--; myMethod(); System.out.println(x + y + ++x); } public static void myMethod() { y = x++ + ++x; } } Choose one answer.
a. Compiler error b. prints : 1 c. prints : 2 d. prints : 3 e. prints : 7 f. prints : 8

Choice D is the correct answer. The above code will not give any compilation error. Note that "Static" is a valid class name. Thus, choice A is incorrect. When executing the above code, the static variables (x and y) will be first initialized to 0. Then, the static block will be called and finally the main() method will be called. The execution of the static block will have no effect on the output as it declares a new variable (int x). The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1.

23 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

In case the statement is "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1. Finally, when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which results in 3 as given in the output. Thus choice D is correct. Incorrect

Marks for this submission: 0/1.

Feedback to Author

40

What will be the result of executing the following code? // Filename; SuperclassX.java package packageX; public class SuperclassX { protected void superclassMethodX() { } int superclassVarX; } // Filename SubclassY.java 1. package packageX.packageY; 2. import packageX.*; 3. public class SubclassY extends SuperclassX 4. { 5. SuperclassX objX = new SubclassY(); 6. SubclassY objY = new SubclassY(); 7. void subclassMethodY() 8. { 9. objY.superclassMethodX(); 10. int i; 11. i = objY.superclassVarX; 12. } 13. } Choose one answer.
a. Compilation error at line 5 b. Compilation error at line 9 c. Runtime exception at line 11 d. None of these

Choice D is the correct answer. When no access modifier is specified for a member, the latter is only accessible by other classes defined in the same package. Even if its class is visible in another package, the member is not accessible there. In the question above, the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the SuperclassX class is visible and the protected method superclassMethodX()is accessible. Thus the compiler will raise an error at line 11. Check out access control rules at http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6 Incorrect
Marks for this submission: 0/1.

Feedback to Author

41

You want to execute a class named My.class in the package whiz.utilities.myapp. The path to that directory is /java/MyPackages/whiz/utilities/myapp Which command would you use to run the class? Choose one answer.
a. java -classpath . /java/MyPackages/whiz/utilities/myapp My b. java -classpath /java/MyPackages whiz.utilities.myapp.My c. java -classpath . java.MyPackages.whiz.utilities.myapp.My d. java -classpath . /java/MyPackages/whiz/utilities/myapp/My

Choice B is the correct answer. Java classes are organized into packages which are mapped to directories in the file system. When classes are stored in a directory (folder), like /java/MyPackages/whiz/utilities/myapp, then the class path entry points to the directory that contains the first element of the package name. (in this case, /java/MyPackages, since the package name is whiz.utilities.myapp.)

24 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Want to know more about setting classpaths? Check out http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/classpath.html Incorrect
Marks for this submission: 0/1.

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Feedback to Author

42

What will happen when you attempt to compile and run the following code? public class MyArray { public static void arrange(int[] array) { int length = array.length; int half = length/2; while( half>= 1) { for(int i=half;i<length;i++) { int temp=array[i]; int test=i; while(test>= half && temp < array[test - half]) { array[test] = array[test - half]; test -= half; } array[test] = temp; } half/=2; } } public static void main(String[] args) { int[] array = {2,3,1}; arrange(array); for(int i=0; i<array.length;i++) { System.out.print(array[i]); } }

Choose one answer.

a. Compiler error b. Exception at runtime c. No output d. Prints : 231 e. Prints : 123 f. Prints : 012

Choice E is the correct answer. Arrays can be used as arguments of a user-defined method exactly as any other type. However, since arrays in Java are actually hidden references, the method can change the elements in the array. In the above code, there will not be any compile-time or runtime error. Inside the main method, first an array is initialized and then it is passed to the arrange method and finally the array is printed. The arrange method performs sorting (shell sort) on the array passed to it as an input. After the execution of the arrange() method, the array is sorted. As stated earlier, since arrays in Java are actually hidden references, the method can change the elements in the array. Thus finally when the array is printed, the sorted array will be printed which will have its elements as 1, 2, and 3 in that order. Thus "123" will be the output of the above code. Incorrect
Marks for this submission: 0/1.

Feedback to Author

43

Which of the following code snippets can be inserted at line 10, so that the object created at line 5 becomes eligible for garbage collection? 1. public class TestGC

25 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


2. { 3. public static void main(String[] args) 4. { 5. Object a = new Integer(7); 6. Object b = new StringBuffer("Java"); 7. Object c = a; 8. a = b; 9. b = null; 10. // What can be inserted here? 11. } 12. } Choose one answer.
a. a = null; b. b = c; c. a = c; d. c = null; e. None of these

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choice D is the correct answer. The code snippet c = null; can be inserted at line 10, so that there is no reference to the Integer object created at line 5, and thus it becomes eligible for garbage collection. Now let us look at the execution of the code. At line 5, an Integer object is created and it is assigned to the object reference 'a'. Line 6 creates a StringBuffer object. At line 7, the object reference 'c' also refers to whatever 'a' is referring to at that time. Thus, after the execution of line 7, the Integer object (created at line 5) has two references pointing to it. But at line 8, 'a' starts referring to whatever 'b' is referring to at that time. Hence after the execution of line 8, there is only one object reference 'c' referring to the original Integer object created at line 5. This object reference 'c' must be made "null" so that there are no more references to the Integer object, and it would become eligible for garbage collection. Thus, only choice D is correct. Choices A, B, and C are incorrect because none of them affects the object reference 'c', which is referring to the Integer object created at line 5. Want to know more? You can read more about garbage collection at http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html http://www.developer.com/tech/article.php/628881 Incorrect
Marks for this submission: 0/1.

Feedback to Author

44

Which of the following statements will compile when inserted independently within the main method? Select three choices. import java.util.*; class Shape{} class Rectangle extends Shape{} class Generics1 { public static void main(String[] args) { //insert statement here } } Choose at least one answer.
a. Vector v1 = new Vector<Shape>(); b. Vector<?> v2 = new Vector<Rectangle>(); c. Vector<Shape> v3 = new Vector<Shape>(); d. Vector<Rectangle> v4 = new Vector<Shape>(); e. Vector<Shape> v5 = new Vector<Rectangle>(); f. Vector<Object> v6 = new Vector<Shape>(); g. Vector<Rectangle> v7 = new Vector<?>();

Choices A, B, and C are the correct answers. It is legal to assign a generic type to a raw type. So choice A is correct. The wild card type of Vector (Vector<?>) is the supertype of all kinds of Vectors, so the assignment in choice B is legal and correct.

26 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Choice C is also correct because it is legal to instantiate a generic type.

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choices D, E, and F are incorrect because the declared type is not the supertype of the instantiated type. Choice G is incorrect because you cannot instantiate a wild card type since its actual type is unknown at compile time. Note: Please note that Vector<Shape> is not the super type of Vector<Rectangle>. From the generics tutorial: "In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions." http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf [^] Incorrect
Marks for this submission: 0/1.

Feedback to Author

45

What is the result of compiling and running the following program? import java.util.*; 1. class Shape{} 2. class Rect extends Shape{} 3. class Circle extends Shape{} 4. class ShadedRect extends Rect{} 5. class Generics2{ 6. public static void add(List <? extends Shape >l,int pos,Rect r){ 7. l.add(pos,r); 8. } 9. public static void main(String[] args){ 10. List<ShadedRect> l=new LinkedList<ShadedRect>(); 11. add(l,0,new ShadedRect()); 12. } 13. } Choose one answer.
a. Compiler error at line 6 b. Compiler error at line 11 c. Compiler error at line 7 d. ClassCastException is thrown e. Compiles and runs without errors

Choice C is the correct answer. The code does not compile at line 7, since you cannot add objects to a collection of an unknown type. The wild card notation List <? extends Shape> indicates a list which can accept any kind of Shape. However, you cannot add to such a collection since the actual type is unknown at compile time. There are no compiler errors at lines 6 and 11 because ShadedRect, is a subclass of Rect, which is a subclass of Shape. So it is legal to pass List <ShadedRect> as List <? extends Shape>. So choices A and B are incorrect. Choices D and E are incorrect because the code does not even compile. Check out this comprehensive tutorial on generics to learn more, http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

46

Drag and drop the correct choices in the blanks provided in the following program code so that the output is {Huck=2, Jack=3, Tom=1} import java.util.*; class X implements Comparable { String name; X(String name) { this.name=name; }

27 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


public { X x=(X)o; return name. } public String toString() { return name; } (Object o) (x.name);

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

public final class Generics12 { public static void main(String[] argv) { TreeMap < , > tree = new TreeMap < tree. (new X("Tom"),1); tree. (new X("Huck"),2); tree. (new X("Jack"),3); } } put X Comparator compare compareTo Integer int equals Comparer Boolean add

> ();

The TreeMap sorts its contents in the ascending order of its keys. So the class to which the key objects belong, must implement the Comparable interface. The Comparable interface defines the method int compareTo(Object o) which compares this object with the specified object for order. It returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. If you try to add key objects which do not implement the compareTo method, to the TreeMap, then a ClassCastException is thrown. In the given code, the class X implements Comparable interface and defines the compareTo method. The method defines the sorting order for the objects, by comparing the name instance variable of the class. If you pass the TreeMap object to the System.out.println statement, the key value pairs are printed out, in the ascending order of the keys. Thus the output produced is {Huck=2, Jack=3, Tom=1}. More about TreeMap is available at http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

47

Drag and drop the relevant choices to fill in the blanks in the following code so that the output is sorted by name and age of the employee. import java.util.*; class Employee { String name; int age; Employee(String name,int age) { this.name=name; this.age=age; } String getName() { return name; } int getAge()

28 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


{

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

} class MyComparator < T extends Employee > implements Comparator < T > { public int ( obj1, obj2) { String name1=obj1.getName(); String name2=obj2.getName(); if(!name1.equals(name2)) return name1. (name2); else return obj1.age-obj2.age; } } class Generics3 { public static void main(String[] args) { set=new TreeSet <Employee> ( set.add(new Employee("Jacob",30)); set.add(new Employee("George",29)); set.add(new Employee("Daisy",40)); set.add(new Employee("Daisy",22)); for ( e: set) { System.out.println(e); } } } new MyComparator<Employee>() Employee T compareTo <T> Set<Employee> compare <T extends Employee> ? String Set<?> String Set<Object>

return age; } public String toString() { return name+" of age "+age; }

);

The java.lang.Comparator interface defines the compare method whose signature is int compare(Object o1, Object o2). A comparator can be used to define total ordering of objects in a collection based on the result of the compare method. The TreeSet class guarantees that the set will be sorted according to the natural order of the elements (if the elements implement Comparable interface), or by the comparator provided at set creation time, if the constructor used takes the Comparator as the argument. Here the Comparator provides sorting according to the order of the name and age instance variables in the Employee class. The objects in the TreeSet can be iterated using the enhanced for loop. Read more about the comparator at http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

48

What is the result of compiling and running the following code? import java.util.*; public class Test { public static void main(String[] args) { TreeMap myMap = new TreeMap(); myMap.put("ab", 10);

29 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


myMap.put("cd", 5); myMap.put("ca", 30); myMap.put("az", 20); NavigableMap myMap2 = myMap.headMap("cd", true); myMap.put("bl", 100); myMap.put("hi", 100); myMap2.put("bi", 100); System.out.println(myMap.size() + " " + myMap2.size());

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

Choose one answer.

a. Code will not compile. b. Throws an exception at runtime. c. Prints 7 6 d. Prints 7 5

Choice C is the correct answer. This code compiles fine and prints the output shown below. 76 The TreeMap is a NavigableMap that is ordered according to the natural ordering of its keys. The headMap(toKey,inclusive) method of this class returns a view of the portion of this Map whose keys are less than (or equal to, if inclusive is true) toKey. In this program, the value of toKey is "cd". All the keys added; "ab", "cd", "ca", "az" are within the range of "cd", so all are included in the map, myMap2, returned by the headMap method. After the method call to headMap(), two more entries are made into the original map. But only "b1" is included in myMap2 because "h1" is not less than or equal to "cd". Finally one more entry is myMap2, for key "bi". So myMap contains the keys; "ab", "cd", "ca", "az", "b1", "h1", "bi" and myMap2 contains all of these except "h1". So the sizes of these maps are printed as 7 6. You can read more about the NavigableMap at http://www.devx.com/Java/Article/33872 http://java.sun.com/javase/6/docs/api/java/util/NavigableMap.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

49

Which of the following statements about the implementation of the hashCode() method of Object class as shown in the following code is true? 1. public class CorrectHashCode 2. { 3. private int number; 4. 5. public CorrectHashCode(int i) 6. { 7. number = i; 8. } 9. 10. public int hashCode() 11. { 12. int i = (int)(Math.random() * 100); 13. return i * number; 14. } 15. 16. // other methods 17. } Choose one answer.
a. The code implements hashCode() method correctly. b. The code does not implement hashCode() method correctly. c. This implementation of hashCode() method is correct if only if the equals() method is not overridden. d. The given code does not contain enough information to comment on the correctness of the hashCode() method implementation. e. None of these.

Choice B is the correct answer.

30 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

There is enough information available in this code itself to judge its correctness. The presence of the overridden equals(Object o) method is not required to determine this. The code does not implement the hashCode() method correctly. This code returns a hash code that is a product of a random number and an int member variable named "number". The general contract of the hashCode() method mentions the following:If the method is invoked on the same object more than once during an execution of a Java application, the method must consistently return the same integer value, provided no information used in equals comparisons on the object is modified. The absolute integer value need not remain consistent from one execution of an application to another execution of the same application. Since this code returns a hash code that involves a multiplication with a random number, it is improbable that it will consistently return the same integer whenever it is invoked on the same object more than once. Moreover, no matter how the equals() method is overridden, it is highly unlikely that the hash code returned by this method will be the same for two objects of this class which are equal according to the equals method. This code does not abide by the general contract of the hashCode() method, and hence this implementation of the hashCode() method is essentially incorrect; no matter how the equals() method is implemented/overridden. More information is available at http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

50

Which of the following statements regarding the java.util.Set interface are true? Select three choices. Choose at least one answer.
a. java.util.Set extends the java.util.Collection interface. b. java.util.Set maintains a set of key-value pairs. c. java.util.Set does not allow duplicate elements. d. java.util.Set maintains its elements in a sorted order. e. All methods defined in java.util.Set are also defined in java.util.Collection. f. java.util.Set does not allow a null element.

Choices A, C, and E are the correct answers. The java.util.Set extends the java.util.Collection interface and all its methods are also defined in java.util.Collection. java.util.Set does not contain any additional methods; it only imposes an additional restriction that prohibits duplicate elements. A Map maintains key-value pairs hence choice B is incorrect. java.util.Set itself does not impose any order; hence choice D is incorrect. It is very important to understand that even though some implementations of the Set interface may prohibit the addition of a null element, the Set interface itself does allow at most one null element. Set : A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction. Read about java.util.Set at http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

51

Which collection class offers constant-time performance for the basic operations -add(), remove(), contains(), and size()? Choose one answer.
a. TreeSet b. HashSet c. BitSet d. None of these

Choice B is the correct answer. HashSet offers constant time performance for the basic operations (add, remove, contains, and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap

31 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

instance (the number of buckets). Thus, it is very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. The constant time performance for basic operation means operations do not take significantly longer as the size of Set increases. Thus, making it is faster. Also, note that the constant time performance is a "near" constant time performance. TreeSet, on the other hand, provides guaranteed log( n ) time cost for the basic operations, that is, the time increases with the log of the size of the set. Hence choice A is incorrect. BitSet has nothing to do with collections or Set, so choice C is also incorrect. Also, note that JDK 1.4 has added a new class java.util.LinkedHashSet that extends HashSet; this class also provides constant-time performance for the basic operations add, contains, and remove. Read more about HashSet at http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

52

What will be the result of compiling and running the following code? import java.util.*; public class Generics8 { public static void main(String[] args) { ArrayList<String> arr = new ArrayList<String>(); arr.add("B"); arr.add("A"); List <Object> list = new ArrayList <Object>(); list = arr; System.out.print(list); } } Choose one answer.
a. Compiler error b. Throws ClassCastException c. Prints [A,B] d. Prints [B,A]

Choice A is the correct answer. List <Object> is not the supertype of all List types, instead it must be List<?>. So assigning an object of type ArrayList <String> to List <Object> is not allowed by the compiler. Since the code does not compile, all the other choices are automatically incorrect. For more information, check out http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf Incorrect
Marks for this submission: 0/1.

Feedback to Author

53

What is the result of compiling and running the following code? import java.util.*; public class Test1 { public static void main(String[] args) { Set<String> hashSet = new HashSet<String>(); hashSet.add("gh"); hashSet.add("ab"); hashSet.add("A"); hashSet.add("X"); TreeSet<String> treeSet = new TreeSet<String>(hashSet); Set<String> treeSet1 = treeSet.descendingSet(); for(String s : treeSet1) { System.out.print(s + " ");

32 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


}

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

} }

Choose one answer.

a. Code will not compile. b. Throws an exception at runtime. c. Prints X A gh ab d. Prints gh ab X A e. Prints A X gh ab

Choice D is the correct answer. The HashSet is a collection that does not maintain any ordering for its elements. However, the TreeSet maintains the natural order of sorting for its elements. For String objects, the alphabetical order is considered. So the TreeSet treeSet maintains the elements in the order "A", "X", "ab", "gh". ConcurrentSkipListSet and TreeSet implement the NavigableSet interface. Navigable interfaces are useful wherever you have in-memory cached data and you want to perform range-based queries upon keys of a map or entries of a set. The descendingSet() returns the reverse order view of the elements contained in the set. Hence the elements in treeSet1 are arranged in the order "gh", "ab", "X", "A". You can read more about the TreeSet at http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html Incorrect
Marks for this submission: 0/1.

Feedback to Author

54

What is the result of compiling and running the following program? import java.util.*; class Shape{} class Circle extends Shape{} class Rectangle extends Shape{} class Generics4 { public static void main(String[] args) { ArrayList<Circle> a=new ArrayList<Circle>(); a.add(new Circle()); ArrayList b=a; ArrayList<Rectangle> c=(ArrayList<Rectangle>)b; c.add(new Rectangle()); for(Object o:b) System.out.println(o); } } Choose one answer.
a. Compiler error b. ClassCastException is thrown at runtime c. Compiles with warnings, prints some output at runtime d. Compiles with no errors or warnings, prints some output at runtime

Choice C is the correct answer. When a generic type is used without a type parameter, it is called a raw type. Since you can insert all type of objects into these raw types, it is not possible to check their correctness. So assigning generic types to raw types generates an unchecked warning. In this program, you assign the generic types to the raw type variable, and then insert different types of objects into it. The raw type is not type-checked, hence there are no compiler errors. So choice A is incorrect. ClassCastException only arises when you try to cast an object to a subclass of which it is not an instance, There is no such case here, so choice B is also incorrect. Choice D is incorrect because warnings are generated. Incorrect
Marks for this submission: 0/1.

33 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Feedback to Author

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

55

You have a HashMap whose keys need to be retrieved in a sorted manner. Which of the following will help you achieve this? Select two choices. Choose at least one answer.
a. Copy the contents of the HashMap into a TreeMap. b. Add the keys of the HashMap to a TreeSet. c. Pass the HashMap to the Arrays.sort() method. d. Pass the HashMap to the Collections().sort() method.

Choices A and B are the correct answers. Both HashMap and TreeMap are implementations of the Map interface, however HashMap does not maintain any ordering for its elements. TreeMap sorts its elements in the ascending order of the keys, so copying the HashMap contents to the TreeMap allows the keys to be retrieved in a sorted manner. TreeSet is a class which implements the Set interface, it allows sorting of its elements, so copying the HashMap keys into a TreeSet also is a solution. Choice C is incorrect because the Arrays.sort() methods take only the array type as argument. Choice D is incorrect because the Collections.sort() method takes java.util.List as the argument. Incorrect
Marks for this submission: 0/1.

Feedback to Author

56

Drag and drop the given class definitions corresponding to their relationships. Bar IS-A Object Foo IS-A Bar Foo HAS-A Bar class class class class Foo extends Bar{} Bar{} Foo{Bar bar;} Bar extends Foo{}

Two things, X and Y are in the IS-A relationship if the phrases "X is a Y" or "all Xs are Ys" are true. Objects in an IS-A relationship use inheritance as in class X extends Y. For example, A Car is Vehicle, so a Car class might inherit from a Vehicle class. Two things, X and Y are in a HAS-A relationship if Y is a property or component of X, as in the phrases "X has a Y", or "Y is a component of X". If X HAS-A Y, than Y will be an instance variable in class X. In Java, inheritance is marked with the keyword 'extends'. So Foo IS-A Bar is given by class Foo extends Bar{} Since every Java class implicitly extends Object, Bar IS-A Object is given by class Bar{}. Foo HAS-A Bar is given by class Foo { Bar b;} so that the Bar b is an instance variable of the class Foo. Incorrect
Marks for this submission: 0/1.

Feedback to Author

57

Examine the following code. Drag and drop the correct choices in the blanks provided in this code, so that there the code compiles and runs fine. interface IFace{} class CFace implements IFace{} class Base{} class DFace extends CFace{} public class ObRef extends Base { public static void main(String argv[]) { ObRef ob = new ObRef(); Base b = new Base(); Object o1 = new Object(); IFace i2 = new CFace(); o1=new ObRef(); ob= ; =i2; b= ;

34 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


=b; } }

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

o1 o2 (ObRef)o1 ob b A super class / interface type reference variable can refer to an object of the subclass type, but the opposite is not true. So i2 can be assigned to o1, ob can be assigned to b, b can be assigned to o1. Even though o1 refers to an object of the same type as ob, o1 needs to be cast down to the ObRef type before being assigned. This is because o1 is declared as of type Object. Want to know more about assignment conversions ? Check out this link. http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.2 Incorrect
Marks for this submission: 0/1.

Feedback to Author

58

Given the following code, in which order will the output be produced? class C extends A { public C() { System.out.println("C"); } } class A { public A() { System.out.println("A"); } } class B extends C { public B() { System.out.println("B"); } } public class ABC { public static void main(String[] args) { System.out.println("Main"); B c = new B(); } } Choose one answer.
a. C, B, B, Main b. Main, A, C, B c. Main, A, B, C d. Main, A, B, A

Choice B is the correct answer. All constructors implicitly call the no argument constructor of the immediate superclass using super(); if no explicit call is made to the superclass constructor. So in this case, when you instantiate B, its constructor calls the constructor of C. C's constructor calls the constructor of its superclass A. Thus, the order of printing would be Main, A, C, B. Read more about invoking superclass constructors at http://www.javaworld.com/jw-10-2000/jw-1013constructors.html Incorrect
Marks for this submission: 0/1.

35 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test


Feedback to Author

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

59

What will happen when you attempt to compile and run the following code? class MyParent { int x, y; MyParent(int x, int y) { this.x = x; this.y = y; } public int addMe(int x, int y) { return this.x + x + y + this.y; } public int addMe(MyParent myPar) { return addMe(myPar.x, myPar.y); }

class MyChild extends MyParent { int z; MyChild (int x, int y, int z) { super(x,y); this.z = z; } public int addMe(int x, int y, int z) { return this.x + x + this.y + y + this.z + z; } public int addMe(MyChild myChi) { return addMe(myChi.x, myChi.y, myChi.z); } public int addMe(int x, int y) { return this.x + x + this.y + y; }

public class MySomeOne { public static void main(String[] args) { MyChild myChi = new MyChild(10, 20, 30); MyParent myPar = new MyParent(10, 20); int x = myChi.addMe(10, 20, 30); int y = myChi.addMe(myChi); int z = myPar.addMe(myPar); System.out.println(x + y + z); } } Choose one answer.
a. 300 b. 240 c. 120 d. 180 e. Compilation error f. None of the above

Choice A is the correct answer. In the above code, the MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both MyChild and MyParent classes, the addMe() method is overloaded. There is no compilation error anywhere in the above code. When executing, the object of the MyChild class will first be created. Please note that there is a super() call from the constructor of the MyChild class, which will call the constructor of the MyParent class. This will cause the

36 de 37

06/06/2011 21:46

SCJP-6-Training : Diagnostic Test

http://www.whizlabs.com/examprep/mod/quiz/review.php?attempt=14...

value of the z member variable of the MyChild class to be 30 and the x, y member variables of the MyParent class will become 10 and 20, respectively. The next statement will again call the constructor of the MyParent class with the same x and y values. This is followed by the execution of the addMe() method of the MyChild class with x as 10, y as 20, and z as 30. Also x and y are inherited by the MyChild class from the MyParent class. Thus, in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20, and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus, x will become 120. This is followed by the invocation of the other addMe() method which takes an object reference to an instance of the MyChild class. From this method, the method which was called earlier (the addMe method which takes the 3 int arguments) is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120, like x. Now, the addMe() method of the MyParent class is invoked. This method invokes another addMe() method declared in the same class. It's equivalent to the invocation of the addMe(int x, int y) method with x as 10 and y as 20. Also the values of the instance variables x and y of MyParent class are 10 and 20, respectively. The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y, and z after all the invocations will be 120, 120, and 60, respectively. As a result of this, finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus choice A is the correct answer. Incorrect
Marks for this submission: 0/1.

Feedback to Author

60

What are the benefits of high cohesion? Select three choices. Choose at least one answer.
a. Cohesion helps understand what a class or method does b. Cohesion helps understand one class without studying others c. Cohesion minimizes changes in other classes when one class is changed d. Cohesion allows the use of descriptive names e. Cohesion promotes reuse of classes or methods

Choices A, D, and E are the correct answers. Cohesion refers to the number and diversity of tasks that a single unit is responsible for. If each unit is responsible for one single logical task, we say it has high cohesion. Cohesion applies to classes and methods. A well-designed unit will have high cohesion. High cohesion makes it easier to: understand what a class or method does use descriptive names reuse classes or methods Choices B and C are incorrect because cohesion is not about the dependencies between classes. Choices B and C refer to the advantages of loose coupling. Incorrect
Marks for this submission: 0/1.

Finish review
SCJA Certification | SCJP Certification | SCWCD Certification | SCBCD Certification | SCDJWS Certification | SCMAD Certification | SCEA Certification Legal | Policies | Copyrights and Trademarks

37 de 37

06/06/2011 21:46

You might also like