Ocjp Mock Jgi - II

Reviewed by Editorial Team
The ProProfs editorial team is comprised of experienced subject matter experts. They've collectively created over 10,000 quizzes and lessons, serving over 100 million users. Our team includes in-house content moderators and subject matter experts, as well as a global network of rigorously trained contributors. All adhere to our comprehensive editorial guidelines, ensuring the delivery of high-quality content.
Learn about Our Editorial Process
| By Ganeshkumar
G
Ganeshkumar
Community Contributor
Quizzes Created: 2 | Total Attempts: 245
| Attempts: 102 | Questions: 63
Please wait...
Question 1 / 63
0 %
0/100
Score 0/100
1. Which capability exists only in java.io.FileWriter?

Explanation

The capability that exists only in java.io.FileWriter is writing a line separator to an open stream. This means that FileWriter has a specific method or functionality that allows the user to write a line separator, which is a special character or sequence of characters used to indicate the end of a line, to an open stream. The other options mentioned, such as closing an open stream, flushing an open stream, and writing to an open stream, are capabilities that are generally available in various input/output classes in Java.

Submit
Please wait...
About This Quiz
Ocjp Mock Jgi - II - Quiz

OCJP Mock JGI - II assesses advanced Java programming skills, focusing on serialization, I\/O operations, and Java interfaces. The quiz tests error handling, file operations, and regex usage,... see moreessential for Java certification preparation. see less

2. Given: 1. public class LineUp { 2. public static void main(String[] args) { 3. double d = 12.345; 4. // insert code here 5. } 6. } Which code fragment, inserted at line 4, produces the output | 12.345|?

Explanation

The code fragment "System.out.printf("|%7.3f| ", d);" produces the output "| 12.345|" because the "%7.3f" format specifier is used to format the double value "d" with a width of 7 characters, including the decimal point and any leading spaces. The ".3" specifies that the output should have 3 decimal places. The output is enclosed in "|" to match the desired format.

Submit
3. Given: 3. interface Animal { void makeNoise(); } 4. class Horse implements Animal { 5. Long weight = 1200L; 6. public void makeNoise() { System.out.println("whinny"); } 7. } 8. public class Icelandic extends Horse { 9. public void makeNoise() { System.out.println("vinny"); } 10. public static void main(String[] args) { 11. Icelandic i1 = new Icelandic(); 12. Icelandic i2 = new Icelandic(); 12. Icelandic i3 = new Icelandic(); 13. i3 = i1; i1 = i2; i2 = null; i3 = i1; 14. } 15. } When line 14 is reached, how many objects are eligible for the garbage collector?

Explanation

When line 14 is reached, there are 4 objects eligible for the garbage collector. The objects i2 and i3 are set to null, meaning they no longer have any references pointing to them. Additionally, i1 is reassigned to i2, and i3 is reassigned to i1, meaning the original object that i3 was referencing is also eligible for garbage collection. Therefore, a total of 4 objects are eligible for garbage collection.

Submit
4. Given: 1. package geometry; 2. public class Hypotenuse { 3. public InnerTriangle it = new InnerTriangle(); 4. class InnerTriangle { 5. public int base; 6. public int height; 7. } 8. } Which statement is true about the class of an object that can reference the variable base?

Explanation

The variable "base" is a public variable in the InnerTriangle class, which is a member of the geometry package. Therefore, any class that wants to access the variable "base" must also belong to the geometry package.

Submit
5. Given: 1. public class Drink implements Comparable { 2. public String name; 3. public int compareTo(Object o) { 4. return 0; 5. } 6. } and: 20. Drink one = new Drink(); 21. Drink two = new Drink(); 22. one.name= "Coffee"; 23. two.name= "Tea"; 24. TreeSet set = new TreeSet(); 25. set.add(one); 26. set.add(two); A programmer iterates over the TreeSet and prints the name of each Drink object. What is the result?

Explanation

The code will iterate over the TreeSet and print the name of each Drink object. Since the compareTo method in the Drink class returns 0, the TreeSet will consider both Drink objects as equal and will only store one of them. When iterating over the TreeSet, it will only print the name of the Drink object that was stored, which is "Coffee". Therefore, the result will be "Coffee".

Submit
6. Given: 11. public static void main(String[] args) { 12. Integer i = new Integer(1) + new Integer(2); 13. switch(i) { 14. case 3: System.out.println("three"); break; 15. default: System.out.println("other"); break; 16. } 17. } What is the result?

Explanation

The code will output "three". This is because on line 12, the code is creating two Integer objects, adding them together using the "+" operator, and assigning the result to the variable "i". This is possible because of autoboxing, which automatically converts the primitive int values to Integer objects. The value of "i" is then used in the switch statement on line 13. Since the value of "i" is 3, the case 3 is matched and the code prints "three".

Submit
7. Given the following six method names: addListener addMouseListener setMouseListener deleteMouseListener removeMouseListener registerMouseListener How many of these method names follow JavaBean Listener naming rules?

Explanation

Two of the given method names follow JavaBean Listener naming rules. The naming convention for JavaBean Listener methods is to start with "add" followed by the event type, and end with "Listener". In this case, the method names "addListener" and "addMouseListener" follow this convention. The other method names do not follow the convention as they either have incorrect prefixes or do not end with "Listener".

Submit
8. Which statement is true about the classes and interfaces in the exhibit? 1.   public interface A { 2.      public void doSomething(String thing); 3.   } 1.   public class AImpl implements A { 2.      public void doSomething(String thing){ } 3.   } 1.   public class B { 2.      public A doIt() { 3.         // more code here 4.      } 5.       6.      public String execute() { 7.         // more code here 8.      } 9.   } 1.   public class C extends B { 2.      public AImpl doIt() { 3.         // more code here 4.      } 5.       6.      public Object execute() { 7.         // more code here 8.      } 9.   }

Explanation

The compilation of class C will fail because the method "execute()" in class C has a different return type (Object) than the method it is overriding in class B (String). The return type of an overridden method must be the same or a subtype of the return type in the superclass.

Submit
9. What is the output if the main() method is run? 10.    public class Starter extends Thread { 11.       private int x = 2; 12.       public static void main(String[] args)throws Exception { 13.        new Starter().makeItSo(); 14.       } 15.       public Starter() { 16.        x = 5; 17.        start(); 18.       } 19.       public void makeItSo() throws Exception { 20.           join(); 21.           x = x - 1; 22.        System.out.println(x); 23.          } 24.       public void run() { x *= 2; } 25.    }

Explanation

The output of the program is 9.


- The main method creates an instance of the Starter class and calls the makeItSo() method.
- In the constructor of the Starter class, the value of x is set to 5 and the start() method is called, which will eventually execute the run() method.
- The run() method multiplies the value of x by 2, resulting in x being 10.
- The makeItSo() method then calls the join() method, which waits for the thread to complete before continuing.
- After the join() method, the value of x is decremented by 1, resulting in x being 9.
- Finally, the value of x (which is 9) is printed to the console.

Submit
10. Given: 1. class Alligator { 2. public static void main(String[] args) { 3. int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}}; 4. int [][]y = x; 5. System.out.println(y[2][1]); 6. } 7. } What is the result?

Explanation

The code declares and initializes a two-dimensional array `x` with three rows and varying number of columns. Then, it assigns `x` to another two-dimensional array `y`. Finally, it prints the value at index `[2][1]` of `y`, which is `7`.

Submit
11. Given: 1. public class Base { 2. public static final String FOO = "foo"; 3. public static void main(String[] args) { 4. Base b = new Base(); 5. Sub s = new Sub(); 6. System.out.print(Base.FOO); 7. System.out.print(Sub.FOO); 8. System.out.print(b.FOO); 9. System.out.print(s.FOO); 10. System.out.print(((Base)s).FOO); 11. } } 12. class Sub extends Base {public static final String FOO="bar";} What is the result?

Explanation

The correct answer is "foobarfoobarfoo".


In this code, the class "Base" has a public static final String variable "FOO" with the value "foo". The class "Sub" extends "Base" and also has a public static final String variable "FOO" with the value "bar".

In the main method, the code creates an instance of "Base" and an instance of "Sub".

When printing the value of "FOO" for each object, the output is as follows:
- Base.FOO: "foo"
- Sub.FOO: "bar"
- b.FOO: "foo" (since it is referencing the "FOO" variable of the "Base" class)
- s.FOO: "bar" (since it is referencing the "FOO" variable of the "Sub" class)
- ((Base)s).FOO: "foo" (since it is casting "s" to the "Base" class and referencing the "FOO" variable of the "Base" class)

Therefore, the final output is "foobarfoobarfoo".

Submit
12. Given: 15. public class Yippee { 16. public static void main(String [] args) { 17. for(int x = 1; x < args.length; x++) { 18. System.out.print(args[x] + " "); 19. } 20. } 21. } and two separate command line invocations: java Yippee java Yippee 1 2 3 4 What is the result?

Explanation

The program is iterating over the command line arguments starting from index 1 (args[1]). Since the first command line invocation "java Yippee" does not have any arguments, the loop is not executed and no output is produced. However, in the second command line invocation "java Yippee 1 2 3 4", the loop is executed and the program prints the arguments starting from index 1, which are "2 3 4". Therefore, the correct answer is "No output is produced. 2 3 4".

Submit
13. Given: 3. interface Fish { } 4. class Perch implements Fish { } 5. class Walleye extends Perch { } 6. class Bluegill { } 7. public class Fisherman { 8. public static void main(String[] args) { 9. Fish f = new Walleye(); 10. Walleye w = new Walleye(); 11. Bluegill b = new Bluegill(); 12. if(f instanceof Perch) System.out.print("f-p "); 13. if(w instanceof Fish) System.out.print("w-f "); 14. if(b instanceof Fish) System.out.print("b-f "); 15. } 16. } What is the result?

Explanation

The result of this code is "f-p w-f".


- In line 9, a Walleye object is created and assigned to a Fish reference variable. Since Walleye is a subclass of Perch, which implements the Fish interface, this assignment is valid.
- In line 12, the instanceof operator is used to check if the object referred to by 'f' is an instance of the Perch class. Since 'f' is actually referring to a Walleye object, which is a subclass of Perch, this condition is true and "f-p" is printed.
- In line 13, the instanceof operator is used to check if the object referred to by 'w' is an instance of the Fish interface. Since 'w' is a Walleye object, which implements the Fish interface, this condition is true and "w-f" is printed.
- In line 14, the instanceof operator is used to check if the object referred to by 'b' is an instance of the Fish interface. Since 'b' is a Bluegill object, which does not implement the Fish interface, this condition is false and nothing is printed.

Submit
14. What is the output of the program shown in the exhibit? 10.    class Foo { 11.       private int x; 12.       public Foo( int x ) { this.x = x; } 13.       public setX( int x ) { this.x =x; } 14.       public int getX() { return x; } 15.    } 16.     17.    public class Gamma { 18.            19.       static Foo fooBar(Foo foo) { 20.          foo = new Foo(100);     21.          return foo; 22.       } 23.        24.       public static void main(String[] args) { 25.         Foo foo = new Foo(300); 26.         System.out.print(foo.getX()+"-"); 27.          28.         Foo fooFoo = new Foo(100); 29.          System.out.print(foo.getX()+"-"); 30.         System.out.print(fooFoo.getX()+"-"); 31.          32.         foo = fooBar(fooFoo); 33.           System.out.print(foo.getX()+"-"); 34.         System.out.print(fooFoo.getX()); 35.      } 36.   }

Explanation

The program creates two instances of the Foo class, foo and fooFoo, with initial values of 300 and 100 respectively.

In the main method, the value of foo.getX() is printed, which is 300. Then, the value of fooFoo.getX() is printed, which is 100.

Next, the fooBar method is called with fooFoo as an argument. Inside the fooBar method, a new instance of Foo is created with a value of 100 and assigned to the local variable foo. The method returns foo.

Back in the main method, the value of foo.getX() is printed again, which is now 100. Finally, the value of fooFoo.getX() is printed, which is still 100.

Therefore, the output of the program is 300-100-100-100-100.

Submit
15. Given: 84. try { 85. ResourceConnection con = resourceFactory.getConnection(); 86. Results r = con.query("GET INFO FROM CUSTOMER"); 87. info = r.getData(); 88. con.close(); 89. } catch (ResourceException re) { 90. errorLog.write(re.getMessage()); 91. } 92. return info; Which statement is true if a ResourceException is thrown on line 86?

Explanation

If a ResourceException is thrown on line 86, it means that there was an error while querying the resource. In this case, the code in the catch block on line 90 will be executed, which writes the error message to the error log. However, since the exception occurred before reaching line 88, the resource connection will not be closed. Therefore, the statement "The resource connection will not be closed on line 88" is true.

Submit
16. Given: 1. package com.company.application; 2. 3. public class MainClass { 4. public static void main(String[] args) {} 5. } And MainClass exists in the /apps/com/company/application directory. Assume the CLASSPATH environment variable is set to "." (current directory).Which two java commands entered at the command line will run MainClass? (Choose two.)

Explanation

The first command "java com.company.application.MainClass if run from the /apps directory" will run MainClass because it specifies the full package name and class name, and it is run from the correct directory where the MainClass file is located.

The second command "java -classpath /apps com.company.application.MainClass if run from any directory" will also run MainClass because it specifies the classpath to the directory where the MainClass file is located, allowing the JVM to find and run the class from any directory.

Submit
17. Given: 11. public class PingPong implements Runnable { 12. synchronized void hit(long n) { 13. for(int i = 1; i < 3; i++) 14. System.out.print(n + "-" + i + " "); 15. } 16. public static void main(String[] args) { 17. new Thread(new PingPong()).start(); 18. new Thread(new PingPong()).start(); 19. } 20. public void run() { 21. hit(Thread.currentThread().getId()); 22. } 23. } Which two statements are true? (Choose two.)

Explanation

The output could be 8-1 7-1 7-2 8-2 because the hit() method is synchronized, which means only one thread can access it at a time. The two threads created in the main method start simultaneously and call the hit() method. However, only one thread can enter the hit() method at a time, so one thread will complete its execution before the other can enter. This leads to the possibility of the output being in any order depending on which thread enters the hit() method first.

Submit
18. Given: 1. import java.util.*; 2. public class Example { 3. public static void main(String[] args) { 4. // insert code here 5. set.add(new Integer(2)); 6. set.add(new Integer(1)); 7. System.out.println(set); 8. } 9. } Which code, inserted at line 4, guarantees that this program will output [1, 2]?

Explanation

The correct answer is "Set set = new TreeSet();". This code guarantees that the program will output [1, 2] because TreeSet is an implementation of the Set interface that stores elements in sorted order. When elements are added to a TreeSet, they are automatically sorted in ascending order. Therefore, when the integers 2 and 1 are added to the TreeSet, they will be stored in sorted order, resulting in the output [1, 2].

Submit
19. Given this code from Class B: 25. A a1 = new A(); 26. A a2 = new A(); 27. A a3 = new A(); 28. System.out.println(A.getInstanceCount()); What is the result? 1.   public class A { 2.       3.      private int counter = 0; 4.       5.      public static int getInstanceCount() { 6.        return counter; 7.      } 8.       9.      public A() { 10.       counter++; 11.     } 12.     13.  }  

Explanation

The code in class A fails to compile because the variable "counter" is declared as a non-static variable, but it is accessed in a static method "getInstanceCount()". To fix this error, the variable "counter" should be declared as static.

Submit
20. Given: 5. import java.util.*; 6. public class SortOf { 7. public static void main(String[] args) { 8. ArrayList<Integer> a = new ArrayList<Integer>(); 9. a.add(1); a.add(5); a.add(3); 11. Collections.sort(a); 12. a.add(2); 13. Collections.reverse(a); 14. System.out.println(a); 15. } 16. } What is the result?

Explanation

The given code first creates an ArrayList named 'a' and adds integers 1, 5, and 3 to it. Then, it sorts the ArrayList using the Collections.sort() method, resulting in [1, 3, 5]. After that, it adds the integer 2 to the ArrayList using the add() method, resulting in [1, 3, 5, 2]. Finally, it reverses the order of the elements in the ArrayList using the Collections.reverse() method, resulting in [2, 5, 3, 1]. Therefore, the correct answer is [2, 5, 3, 1].

Submit
21. Which can appropriately be thrown by a programmer using Java SE technology to create a desktop application?

Explanation

The NumberFormatException can be thrown by a programmer using Java SE technology to create a desktop application when there is an attempt to convert a string into a numeric type, but the string does not have the appropriate format. This exception is usually thrown when using methods like parseInt() or parseDouble() to convert strings into integers or doubles, respectively. If the string cannot be parsed into a valid number format, the NumberFormatException is thrown.

Submit
22. Given: 11. public class Person { 12. private name; 13. public Person(String name) { 14. this.name = name; 15. } 16. public int hashCode() { 17. return 420; 18. } 19. } Which statement is true?

Explanation

The given answer is correct because in a HashMap, the time to find the value associated with a specific key depends on the size of the map. As the size of the map increases, the time to find the value also increases because the HashMap uses the hash code of the key to determine the bucket where the value is stored. If the number of elements in the map increases, the number of buckets also increases, which can lead to more collisions and slower lookup time. Therefore, the time complexity for finding a value in a HashMap is O(1) on average, but it can be O(n) in the worst case scenario.

Submit
23. Given: 11. String test = "Test A. Test B. Test C."; 12. // insert code here 13. String[] result = test.split(regex); Which regular expression, inserted at line 12, correctly splits test into "Test A", "Test B", and "Test C"?

Explanation

The regular expression "\\.\\s*" correctly splits the string "test" into "Test A", "Test B", and "Test C". This regular expression matches a period followed by zero or more whitespace characters, which is the pattern used to separate the different parts of the string.

Submit
24. Given: 11. public static void main(String[] args) { 12. for (int i = 0; i <= 10; i++) { 13. if (i > 6) break; 14. } 15. System.out.println(i); 16. } What is the result?

Explanation

The code will fail to compile because the variable "i" is declared within the for loop and cannot be accessed outside of it. Therefore, the statement on line 15, which tries to print the value of "i", will result in a compilation error.

Submit
25. Given: 11. public void testIfA() { 12. if (testIfB("True")) { 13. System.out.println("True"); 14. } else { 15. System.out.println("Not true"); 16. } 17. } 18. public Boolean testIfB(String str) { 19. return Boolean.valueOf(str); 20. } What is the result when method testIfA is invoked?

Explanation

The result when method testIfA is invoked is "True". This is because the testIfB method is called with the argument "True", which returns a Boolean value of true. Since the if statement evaluates this Boolean value as true, the code block in line 13 is executed, which prints "True" to the console.

Submit
26. Given: 11. public interface A { public void m1(); } 12. 13. class B implements A { } 14. class C implements A { public void m1() { } } 15. class D implements A { public void m1(int x) { } } 16. abstract class E implements A { } 17. abstract class F implements A { public void m1() { } } 18. abstract class G implements A { public void m1(int x) { } } What is the result?

Explanation

The two classes that do not compile are class D and class G. Class D does not compile because it implements the interface A but does not provide an implementation for the method m1() without any parameters, as required by the interface. Class G does not compile for the same reason, as it also does not provide an implementation for the method m1() without any parameters. The other classes either implement the method m1() as required by the interface or are abstract classes that are not required to provide an implementation.

Submit
27. Given: 2. public class Hi { 3. void m1() { } 4. protected void() m2 { } 5. } 6. class Lois extends Hi { 7. // insert code here 8. } Which four code fragments, inserted independently at line 7, will compile? (Choose four.)

Explanation

The given code is a class named "Hi" with two methods, "m1()" and "m2()", both without any return type. The class "Lois" extends the "Hi" class.

To compile the code at line 7, we need to insert code that is valid and does not cause any compilation errors.

The four code fragments that can be inserted at line 7 and will compile are:
- public void m1() { }
- protected void m1() { }
- public void m2() { }
- protected void m2() { }

Submit
28. Given: 11. public static void main(String[] args) { 12. Object obj = new int[] { 1, 2, 3 }; 13. int[] someArray = (int[])obj; 14. for (int i : someArray) System.out.print(i + " "); 15. } What is the result?

Explanation

The correct answer is "1 2 3" because the code creates an array of integers on line 12 and assigns it to an Object reference. On line 13, the code casts the Object reference back to an int array. Then, on line 14, a for-each loop is used to iterate over the elements of the int array and print them out. Since the int array contains the values 1, 2, and 3, the output will be "1 2 3".

Submit
29. Given: 10: public class Hello { 11: String title; 12: int value; 13: public Hello() { 14: title += " World"; 15: } 16: public Hello(int value) { 17: this.value = value; 18: title = "Hello"; 19: Hello(); 20: } 21: } and: 30: Hello c = new Hello(5); 31: System.out.println(c.title); What is the result?

Explanation

The code fails to compile because the constructor on line 19 is calling the constructor on line 13 using the syntax "Hello();". However, this syntax is not valid for calling a constructor within another constructor. The correct syntax would be "this();" to call the default constructor.

Submit
30. Given: foo and bar are public references available to many other threads. foo refers to a Thread and bar is an Object. The thread foo is currently executing bar.wait(). From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?

Explanation

The most reliable way to ensure that foo will stop executing wait() is by calling bar.notifyAll(). This is because bar is the object on which the wait() method is being called, so calling notifyAll() on bar will notify all threads waiting on that object, including foo. This will allow foo to resume execution and continue its task.

Submit
31. Given: 10. class One { 11. public One foo() { return this; } 12. } 13. class Two extends One { 14. public One foo() { return this; } 15. } 16. class Three extends Two { 17. // insert method here 18. } Which two methods, inserted individually, correctly complete the Three class? (Choose two.)

Explanation

The correct answer is "public Two foo() { return this; }" and "public One foo() { return this; }". These two methods correctly complete the Three class because they override the foo() method from the parent class, Two, and return the appropriate type of object. The first method returns an object of type Two, which is the class that directly extends One. The second method returns an object of type One, which is the class that the Three class ultimately extends.

Submit
32. 1.   class Computation extends Thread { 2.       3.      private int num; 4.      private boolean isComplete; 5.      private int result; 6.       7.      public Computation(int num) { this.num = num; } 8.       9.       public synchronized void run() { 10.       result = num * 2; 11.       isComplete = true; 12.       notify(); 13.    } 14.     15.    public synchronized ing getResult() { 16.       while(!isComplete) { 17.          try { 18.           wait(); 19.          } catch(InterruptedException e){ } 20.       }     21.       return result; 22.    } 23.        24.    public static void main(String[] args) { 25.       Computation[] computations = new Computation[4]; 26.       for(int i = 0; i < computations.length; i++) { 27.          computations[i] = new Computation(i); 28.          computations[i].start(); 29.        } 30.       for(Computation c:computations) 31.          System.out.print(c.getResult()+" "); 32.    } 33.  } What is the result?

Explanation

The code creates an array of Computation objects and starts each thread. Each thread calculates the result by multiplying the given number by 2 and sets the isComplete flag to true. The main thread then waits for each computation to complete and prints the result. Since the computations are running concurrently, the order in which they complete is not guaranteed. Therefore, the output can be "0 2 4 6" or any other possible permutation of these numbers.

Submit
33. Given: 10. interface A { void x(); } 11. class B implements A { public void x() {} public void y() {} } 12. class C extends B { public void x() {} } And: 20. java.util.List<A> list = new java.util.ArrayList<A>(); 21. list.add(new B()); 22. list.add(new C()); 23. for (A a : list) { 24. a.x(); 25. a.y(); 26. } What is the result?

Explanation

The code fails to compile because the method "y()" is not defined in the interface A. Since the variable "a" is of type A, it does not have access to the method "y()" defined in class B. Therefore, calling "a.y()" on line 25 would result in a compilation error.

Submit
34. Given: 12. import java.util.*; 13. public class Explorer2 { 14. public static void main(String[] args) { 15. TreeSet<Integer> s = new TreeSet<Integer>(); 16. TreeSet<Integer> subs = new TreeSet<Integer>(); 17. for(int i = 606; i < 613; i++) 18. if(i%2 == 0) s.add(i); 19. subs = (TreeSet)s.subSet(608, true, 611, true); 20. s.add(629); 21. System.out.println(s + " " + subs); 22. } 23. } What is the result?

Explanation

The code creates a TreeSet named "s" and adds even numbers between 606 and 612 to it. Then, it creates a subset of "s" called "subs" using the subSet() method, with the range [608, 611] inclusive. After that, it adds the number 629 to "s". The output will be [606, 608, 610, 612, 629] for "s" and [608, 610] for "subs".

Submit
35. A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?

Explanation

The correct implementation of the MinMax class is the first one provided. This is because it correctly declares the type parameter E and ensures that it implements the Comparable interface. The put() method allows for storing either the minimum or maximum value based on the implementation.

Submit
36. Given: 11. public void go(int x) { 12. assert (x > 0); 13. switch(x) { 14. case 2: ; 15. default: assert false; 16. } 17. } 18. private void go2(int x) { assert (x < 0); } Which statement is true?

Explanation

The correct answer is "Only the assert statements on lines 15 and 18 are used appropriately." This is because in line 15, the assert statement is used to ensure that the default case in the switch statement is never reached. In line 18, the assert statement is used to check that the value of x is less than 0. Both of these assert statements are used correctly to enforce certain conditions in the code.

Submit
37. Given: 10. class Line { 11. public class Point { public int x,y;} 12. public Point getPoint() { return new Point(); } 13. } 14. class Triangle { 15. public Triangle() { 16. // insert code here 17. } 18. } Which code, inserted at line 16, correctly retrieves a local instance of a Point object?

Explanation

The correct answer is "Line.Point p = (new Line()).getPoint();". This code correctly retrieves a local instance of a Point object by creating a new instance of the Line class using the "new Line()" syntax and then calling the "getPoint()" method on that instance. The "Line.Point" syntax is used to specify that the Point class is a nested class within the Line class.

Submit
38. Given: 11. class X { public void foo() { System.out.print("X "); } } 12. 13. public class SubB extends X { 14. public void foo() throws RuntimeException { 15. super.foo(); 16. if (true) throw new RuntimeException(); 17. System.out.print("B "); 18. } 19. public static void main(String[] args) { 20. new SubB().foo(); 21. } 22. } What is the result?

Explanation

The correct answer is X, followed by an Exception. This is because the foo() method in the SubB class overrides the foo() method in the X class. In the overridden method, it first calls the foo() method of the superclass using super.foo(). Then, it throws a RuntimeException. Since there is no try-catch block to handle the exception, it is propagated up the call stack and the program terminates after printing "X".

Submit
39. 1.   public class Threads1 { 2.      int x = 0; 3.      public class Runner implements Runnable { 4.         public void run() { 5.            int current = 0; 6.            for(int i=0;i<4;i++) { 7.             current = x; 8.          System.out.print(current + ", "); 9.           x = current + 2; 10.          } 11.       } 12.    } 13. 14.    public static void main(String[] args) { 15.       new Threads1().go(); 16.    } 17.     18.    public void go() { 19.       Runnable r1 = new Runnable(); 20.       new Thread(r1).start(); 21.       new Thread(r1).start(); 22.    } 23.   } Which two are possible results? (Choose two.)

Explanation

The code creates two threads that both execute the same Runnable object. The Runnable object has a for loop that runs four times. In each iteration, the current value of x is printed followed by a comma. Then, the value of x is updated by adding 2 to the current value. Since both threads are executing the same Runnable object, they will share the same value of x. Therefore, the possible results will be a combination of the printed values of x from both threads. In this case, the two possible results are 0, 2, 4, 4, 6, 8, 10, 6 and 0, 2, 4, 6, 8, 10, 12, 14.

Submit
40. Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)

Explanation

The two code fragments that will execute the method doStuff() in a separate thread are:

1. new Thread() {
public void run() { doStuff(); }
}.start();

This code creates a new thread using the Thread class and overrides the run() method to call the doStuff() method. The start() method is then called to start the thread and execute the doStuff() method in a separate thread.

2. new Thread(new Runnable() {
public void run() { doStuff(); }
}).start();

This code creates a new thread using the Thread class and passes a Runnable object as a parameter. The run() method of the Runnable object is overridden to call the doStuff() method. The start() method is then called to start the thread and execute the doStuff() method in a separate thread.

Submit
41. Given: 12. NumberFormat nf = NumberFormat.getInstance(); 13. nf.setMaximumFractionDigits(4); 14. nf.setMinimumFractionDigits(2); 15. String a = nf.format(3.1415926); 16. String b = nf.format(2); Which two statements are true about the result if the default locale is Locale.US? (Choose two.)

Explanation

The value of b is 2.00 because the format method of NumberFormat class formats the given number according to the formatting rules set by setMaximumFractionDigits and setMinimumFractionDigits methods. In this case, the number 2 is formatted with a minimum of 2 fraction digits, so it becomes "2.00". The value of a is 3.1416 because the number 3.1415926 is formatted with a maximum of 4 fraction digits and a minimum of 2 fraction digits, so it becomes "3.1416".

Submit
42. Given: 5. public class Tahiti { 6. Tahiti t; 7. public static void main(String[] args) { 8. Tahiti t = new Tahiti(); 9. Tahiti t2 = t.go(t); 10. t2 = null; 11. // more code here 12. } 13. Tahiti go(Tahiti t) { 14. Tahiti t1 = new Tahiti(); Tahiti t2 = new Tahiti(); 15. t1.t = t2; t2.t = t1; t.t = t2; 16. return t1; 17. } 18. } When line 11 is reached, how many objects are eligible for garbage collection?

Explanation

When line 11 is reached, there are no objects eligible for garbage collection. This is because all the objects created in the code are still referenced by variables. The variable t2 is set to null, but it does not affect the eligibility for garbage collection as it was not the only reference to any object. Therefore, all the objects created in the code are still reachable and not eligible for garbage collection.

Submit
43. Given: 5. import java.io.*; 6. public class Talk { 7. public static void main(String[] args) { 8. Console c = new Console(); 9. String pw; 10. System.out.print("password: "); 11. pw = c.readLine(); 12. System.out.println("got " + pw); 13. } 14. } If the user types the password aiko when prompted, what is the result?

Explanation

The code fails to compile due to an error on line 8 because the Console class is not imported properly. The correct import statement should be "import java.io.Console;" instead of "import java.io.*;". Therefore, the code cannot create an instance of the Console class and the compilation fails.

Submit
44. What is the result ? 1.   public class SimplCalc { 2.      public int value; 3.      public void calculate() { value += 7; } 4.   } And: 1.   public class MultiCalc extends SimpleCalc { 2.      public void calculate() { value -=3; } 3.      public void calculate(int multiplier) { 4.        calculate(); 5.        super.calculate(); 6.        value *= multiplier; 7.      } 8.      public static void main(String[] args) { 9.        MultiCalc calculator = new MultiCalc(); 10.       calculator.calculate(2); 11.       System.out.println("Value is: "+calculator.value); 12.     } 13.  }

Explanation

The correct answer is "Value is: 8" because the code creates an instance of the MultiCalc class and calls the calculate() method with an argument of 2. Inside the calculate() method, the calculate() method is called again without any arguments, which adds 7 to the value. Then, the super.calculate() method is called, which adds another 7 to the value. Finally, the value is multiplied by the multiplier, which is 2. Therefore, the final value is 8.

Submit
45. Given: 10. interface Data { public void load(); } 11. abstract class Info { public abstract void load(); } Which class correctly uses the Data interface and Info class?

Explanation

The correct answer is "public class Employee extends Info implements Data { public void load() { /*do something*/ } }". This is the correct class because it correctly implements the Data interface and extends the Info class. The load() method in this class satisfies the requirements of both the Data interface and the Info class.

Submit
46. Given: 21. abstract class C1 { 22. public C1() { System.out.print(1); } 23. } 24. class C2 extends C1 { 25. public C2() { System.out.print(2); } 26. } 27. class C3 extends C2 { 28. public C3() { System.out.println(3); } 29. } 30. public class Ctest { 31. public static void main(String[] a) { new C3(); } 32. } What is the result?

Explanation

The code defines an abstract class C1 with a constructor that prints 1. Class C2 extends C1 and has a constructor that prints 2. Class C3 extends C2 and has a constructor that prints 3. In the main method of the Ctest class, a new object of C3 is created. When this object is created, the constructors of C1, C2, and C3 are called in order, resulting in the output 123.

Submit
47. Given: 1. class TestA { 2. public void start() { System.out.println("TestA"); } 3. } 4. public class TestB extends TestA { 5. public void start() { System.out.println("TestB"); } 6. public static void main(String[] args) { 7. ((TestA)new TestB()).start(); 8. } 9. } What is the result?

Explanation

The code creates a class TestA with a method start() that prints "TestA". Then, a class TestB is created that extends TestA and overrides the start() method to print "TestB". In the main method, an instance of TestB is created and casted to TestA. The start() method is then called on this instance, which results in "TestB" being printed. Therefore, the result is "TestB".

Submit
48. Given: 11. public class Person { 12. private String name; 13. public Person(String name) { 14. this.name = name; 15. } 16. public boolean equals(Object o) { 17. if ( ! ( o instanceof Person) ) return false; 18. Person p = (Person) o; 19. return p.name.equals(this.name); 20. } 21. } Which statement is true?

Explanation

The correct answer is that a HashSet could contain multiple Person objects with the same name. This is because the equals() method in the Person class is overridden to compare the names of two Person objects. However, the hashCode() method is not overridden, which means that the default implementation from the Object class is used. This default implementation generates a unique hash code for each object, regardless of the values of their fields. Therefore, multiple Person objects with the same name will have different hash codes and can be stored in a HashSet.

Submit
49. Given: 11. public class Commander { 12. public static void main(String[] args) { 13. String myProp = /* insert code here */ 14. System.out.println(myProp); 15. } 16. } and the command line: java -Dprop.custom=gobstopper Commander Which two, placed on line 13, will produce the output gobstopper? (Choose two.)

Explanation

The correct answer is System.getProperty("prop.custom") and System.getProperties().getProperty("prop.custom"). These two options will retrieve the value of the system property "prop.custom" that was passed through the command line using the -D flag. The first option, System.getProperty("prop.custom"), directly retrieves the value of the specified system property. The second option, System.getProperties().getProperty("prop.custom"), first retrieves all system properties using System.getProperties() and then specifically retrieves the value of the "prop.custom" property. Both options will return the value "gobstopper" in this case.

Submit
50. Given that the current directory is empty, and that the user has read and write privileges to the current directory, and the following: 1. import java.io.*; 2. public class Maker { 3. public static void main(String[] args) { 4. File dir = new File("dir"); 5. File f = new File(dir, "f"); 6. } 7. } Which statement is true?

Explanation

The given code does not contain any code to create a file or a directory on the file system. The variable "dir" is assigned a new File object with the name "dir", but it does not create a directory with that name. Similarly, the variable "f" is assigned a new File object with the name "f", but it does not create a file with that name. Therefore, nothing is added to the file system.

Submit
51. Which two classes correctly implement both the java.lang.Runnable and the java.lang. Cloneable interfaces? (Choose two.)

Explanation

The correct answers are the first and fourth options. The first option correctly implements both the Runnable and Cloneable interfaces by providing the run() and clone() methods. The fourth option also correctly implements both interfaces, as it extends the abstract class Session and provides the necessary methods.

Submit
52. Which two code fragments are most likely to cause a StackOverflowError? (Choose two.)

Explanation

The first code fragment is likely to cause a StackOverflowError because it creates an array of size 5 and then tries to access index 5, which is out of bounds. This results in an infinite loop of trying to access the same index, causing the stack to overflow.

The second code fragment is also likely to cause a StackOverflowError because it creates a recursive function where doThree calls doTwo and doTwo calls doThree. This creates an infinite loop of function calls, causing the stack to overflow.

Both of these scenarios involve infinite loops or recursive function calls that do not have a base case or termination condition, leading to a stack overflow.

Submit
53. Given: 1. interface A { public void aMethod(); } 2. interface B { public void bMethod(); } 3. interface C extends A,B { public void cMethod(); } 4. class D implements B { 5. public void bMethod(){} 6. } 7. class E extends D implements C { 8. public void aMethod(){} 9. public void bMethod(){} 10. public void cMethod(){} 11. } What is the result?

Explanation

The correct answer is "If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in Line 9." This is because class E extends class D, which implements interface B. Therefore, class E inherits the implementation of bMethod() from class D. In line 9, class E overrides the implementation of bMethod() from class D, so when invoking e.bMethod(), it will invoke the version of bMethod() defined in line 9.

Submit
54. Given: 11. class Mammal { } 12. 13. class Raccoon extends Mammal { 14. Mammal m = new Mammal(); 15. } 16. 17. class BabyRaccoon extends Mammal { } Which four statements are true? (Choose four.)

Explanation

The first statement, "Raccoon is-a Mammal," is true because the class Raccoon extends the class Mammal, indicating that Raccoon is a type of Mammal. The second statement, "Raccoon has-a Mammal," is false because the Raccoon class does not have a Mammal object as a member variable. The third statement, "BabyRaccoon is-a Mammal," is true because the class BabyRaccoon extends the class Mammal, indicating that BabyRaccoon is a type of Mammal. The fourth statement, "BabyRaccoon is-a BabyRaccoon," is true because a class is always considered to be an instance of itself.

Submit
55. Given: 3. public class Breaker { 4. static String o = ""; 5. public static void main(String[] args) { 6. z: 7. o = o + 2; 8. for(int x = 3; x < 8; x++) { 9. if(x==4) break; 10. if(x==6) break z; 11. o = o + x; 12. } 13. System.out.println(o); 14. } 15. } What is the result?

Explanation

The code will fail to compile because the label "z" on line 6 is not used anywhere else in the code. The break statement on line 10 references the label "z", but since it is not used, the code will not compile.

Submit
56. Given: 11. public static void main(String[] args) { 12. try { 13. args = null; 14. args[0] = "test"; 15. System.out.println(args[0]); 16. } catch (Exception ex) { 17. System.out.println("Exception"); 18. } catch (NullPointerException npe) { 19. System.out.println("NullPointerException"); 20. } 21. } What is the result?

Explanation

The code will fail to compile because on line 14, the program is trying to assign a value to the first element of the "args" array, which has been set to null on line 13. Since the "args" array is null, it cannot be accessed and therefore the code will not compile.

Submit
57. Which four statements are true? (Choose four.)

Explanation

Has-a relationships can be implemented using instance variables because an object can have another object as one of its instance variables. Is-a relationships can be implemented using the extends keyword because a class can inherit from another class to establish an is-a relationship. Is-a relationships can also be implemented using the implements keyword to establish a relationship between a class and an interface. An array or a collection can be used to implement a one-to-many has-a relationship because it allows multiple objects to be stored and accessed as a single entity.

Submit
58. Given classes defined in two different files: 1. package packageA; 2. public class Message { 3. String getText() { return "text"; } 4. } And: 1. package packageB; 2. public class XMLMessage extends packageA.Message { 3. String getText() { return "<msg>text</msg>";} 4. public static void main(String[] args) { 5. System.out.println(new XMLMessage().getText()); 6. } 7. } What is the result of executing XMLMessage.main?

Explanation

The result of executing XMLMessage.main is that the compilation fails. This is because the getText() method in the XMLMessage class is attempting to override the getText() method in the Message class, but it is not allowed to do so because the getText() method in the Message class is not declared as public. Therefore, the code does not compile.

Submit
59. Given: 12. import java.io.*; 13. public class Forest implements Serializable { 14. private Tree tree = new Tree(); 15. public static void main(String [] args) { 16. Forest f = new Forest(); 17. try { 18. FileOutputStream fs = new FileOutputStream("Forest.ser"); 19. ObjectOutputStream os = new ObjectOutputStream(fs); 20. os.writeObject(f); os.close(); 21. } catch (Exception ex) { ex.printStackTrace(); } 22. } } 23. 24. class Tree { } What is the result?

Explanation

The code is trying to serialize an instance of the class Forest. However, the class Tree does not implement the Serializable interface, so it cannot be serialized. This will result in a runtime exception being thrown.

Submit
60. Given: 11. public class ItemTest { 12. private final int id; 13. public ItemTest(int id) { this.id = id; } 14. public void updateId(int newId) { id = newId; } 15. 16. public static void main(String[] args) { 17. ItemTest fa = new ItemTest(42); 18. fa.updateId(69); 19. System.out.println(fa.id); 20. } 21. } What is the result?

Explanation

The code will fail to compile because on line 14, the variable "id" is declared as final. This means that once it is assigned a value in the constructor on line 13, it cannot be changed. Therefore, the attempt to update the value of "id" in the "updateId" method on line 14 will result in a compilation error.

Submit
61. Which three statements concerning the use of the java.io.Serializable interface are true? (Choose three.)

Explanation

The first statement is false because objects from classes that use aggregation can be serialized. The second statement is true because an object serialized on one JVM can indeed be successfully deserialized on a different JVM. The third statement is false because the values in fields with the volatile modifier will survive serialization and deserialization. The fourth statement is true because the values in fields with the transient modifier will not survive serialization and deserialization. The fifth statement is true because it is indeed legal to serialize an object of a type that has a supertype that does not implement java.io.Serializable.

Submit
62. A developer is creating a class Book, that needs to access class Paper. The Paper class is deployed in a JAR named myLib.jar. Which three, taken independently, will allow the developer to use the Paper class while compiling the Book class? (Choose three.)

Explanation

The first option, "$JAVA_HOME/jre/lib/ext/myLib.jar", is a valid location for a JAR file that can be accessed by the Book class during compilation. The second option, "/foo/myLib.jar" with a classpath environment variable that includes "/foo/myLib.jar", allows the Book class to access the Paper class. The third option, "/foo/myLib.jar" with the Book class compiled using "javac -classpath /foo/myLib.jar Book.java", sets the classpath to include the JAR file and allows the Book class to use the Paper class.

Submit
63. Given: 5. class A { 6. void foo() throws Exception { throw new Exception(); } 7. } 8. class SubB2 extends A { 9. void foo() { System.out.println("B "); } 10. } 11. class Tester { 12. public static void main(String[] args) { 13. A a = new SubB2(); 14. a.foo(); 15. } 16. } What is the result?

Explanation

The code fails to compile on line 14 because the method foo() in class A throws an exception, and when overriding a method, the subclass must not throw a broader exception or a new checked exception. In this case, the subclass SubB2 does not declare that it throws an exception, causing a compilation error.

Submit
View My Results

Quiz Review Timeline (Updated): Mar 20, 2023 +

Our quizzes are rigorously reviewed, monitored and continuously updated by our expert board to maintain accuracy, relevance, and timeliness.

  • Current Version
  • Mar 20, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Mar 07, 2018
    Quiz Created by
    Ganeshkumar
Cancel
  • All
    All (63)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
Which capability exists only in java.io.FileWriter?
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given the following six method names: ...
Which statement is true about the classes and interfaces in the...
What is the output if the main() method is run? ...
Given: ...
Given: ...
Given: ...
Given: ...
What is the output of the program shown in the exhibit? ...
Given: ...
Given: ...
Given: ...
Given: ...
Given this code from Class B: ...
Given: ...
Which can appropriately be thrown by a programmer using Java SE...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
1.   class Computation extends Thread { ...
Given: ...
Given: ...
A programmer must create a generic class MinMax and the type parameter...
Given: ...
Given: ...
Given: ...
1.   public class Threads1 { ...
Which two code fragments will execute the method doStuff() in a...
Given: ...
Given: ...
Given: ...
What is the result ? ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given that the current directory is empty, and that the user has read...
Which two classes correctly implement both the java.lang.Runnable and...
Which two code fragments are most likely to cause a...
Given: ...
Given: ...
Given: ...
Given: ...
Which four statements are true? (Choose four.)
Given classes defined in two different files: ...
Given: ...
Given: ...
Which three statements concerning the use of the java.io.Serializable...
A developer is creating a class Book, that needs to access class...
Given: ...
Alert!

Advertisement