Ocjp Mock Jgi - III

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: 143 | Questions: 63
Please wait...
Question 1 / 63
0 %
0/100
Score 0/100
1. Given: 11. public class Rainbow { 12. public enum MyColor { 13. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff); 14. private final int rgb; 15. MyColor(int rgb) { this.rgb = rgb; } 16. public int getRGB() { return rgb; } 17. }; 18. public static void main(String[] args) { 19. // insert code here 20. } 21. } Which code fragment, inserted at line 19, allows the Rainbow class to compile?

Explanation

The code fragment "MyColor treeColor = MyColor.GREEN;" allows the Rainbow class to compile because it creates a new variable "treeColor" of type MyColor and assigns it the value MyColor.GREEN. This is a valid operation as MyColor is an enum and GREEN is one of its defined values.

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

OCJP Mock JGI - III tests understanding of Java multithreading, exception handling, and object synchronization. It evaluates skills in handling runtime exceptions and thread operations in Java, essential... see morefor Java certification aspirants. see less

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

Explanation

The output could be 6-1 6-2 5-1 5-2 because the hit() method is synchronized, which means only one thread can access it at a time. However, since there are two threads created in the main method, it is possible for the threads to interleave their execution. Therefore, it is possible for one thread to print "6-1" and "6-2" before the other thread prints "5-1" and "5-2".

Submit
3. Given: 1. package test; 2. 3. class Target { 4. public String name = "hello"; 5. } What can directly access and change the value of the variable name?

Explanation

Any class in the test package can directly access and change the value of the variable "name". This is because the variable "name" has default access modifier, which means it is accessible within the same package. Therefore, any class within the test package can access and modify the value of the variable "name".

Submit
4. 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|". The "%7.3f" format specifier is used to print a floating-point number with a total width of 7 characters, including the decimal point and any leading spaces. The ".3" precision specifier is used to display 3 digits after the decimal point. Therefore, the output will have a total width of 7 characters, with the number "12.345" centered within it.

Submit
5. Assuming that the serializeBanana() and the deserializeBanana() methods will correctly use Java serialization and given: 13. import java.io.*; 14. class Food implements Serializable {int good = 3;} 15. class Fruit extends Food {int juice = 5;} 16. public class Banana extends Fruit { 17. int yellow = 4; 18. public static void main(String [] args) { 19. Banana b = new Banana(); Banana b2 = new Banana(); 20. b.serializeBanana(b); // assume correct serialization 21. b2 = b.deserializeBanana(); // assume correct 22. System.out.println("restore "+b2.yellow+ b2.juice+b2.good); 24. } 25. // more Banana methods go here 50. } What is the result?

Explanation

The code defines a class hierarchy of Food, Fruit, and Banana, with Banana being the most derived class. The Banana class has an instance variable "yellow" with a value of 4. In the main method, a Banana object "b" is created and serialized using the serializeBanana() method (which is assumed to be correct). Then, another Banana object "b2" is created and deserialized using the deserializeBanana() method (also assumed to be correct). Finally, the yellow, juice, and good instance variables of "b2" are printed. Since "b2" is deserialized from "b", it will have the same values for all the instance variables, resulting in "restore 453" being printed.

Submit
6. Given: 11. class Mud { 12. // insert code here 13. System.out.println("hi"); 14. } 15. } And the following five fragments: public static void main(String...a) { public static void main(String.* a) { public static void main(String... a) { public static void main(String[]... a) { public static void main(String...[] a) { How many of the code fragments, inserted independently at line 12, compile?

Explanation

Three of the code fragments, "public static void main(String...a)", "public static void main(String... a)", and "public static void main(String...[] a)", can be inserted independently at line 12 and will compile. These fragments define the main method with a variable-length argument parameter, which is a valid syntax in Java.

Submit
7. Given: 1. public class TestString1 { 2. public static void main(String[] args) { 3. String str = "420"; 4. str += 42; 5. System.out.print(str); 6. } 7. } What is the output?

Explanation

The output of this code is "42042". The code starts with a string "420" on line 3. On line 4, the "+=" operator is used to concatenate the number 42 to the string, resulting in "42042". Finally, on line 5, the string is printed to the console.

Submit
8. Which capability exists only in java.io.FileWriter?

Explanation

The capability of writing a line separator to an open stream exists only in java.io.FileWriter. This means that FileWriter specifically allows for the writing of a line separator, which is a special character or sequence of characters used to indicate the end of a line in a text file. 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 I/O classes in Java, not exclusive to FileWriter.

Submit
9. Given: 10. class Nav{ 11. public enum Direction { NORTH, SOUTH, EAST, WEST } 12. } 13. public class Sprite{ 14. // insert code here 15. } Which code, inserted at line 14, allows the Sprite class to compile?

Explanation

The code "Nav.Direction d = Nav.Direction.NORTH;" allows the Sprite class to compile because it correctly specifies the fully qualified name of the Direction enum. This ensures that the compiler can identify the enum and its values without any ambiguity.

Submit
10. Given: 5. class Atom { 6. Atom() { System.out.print("atom "); } 7. } 8. class Rock extends Atom { 9. Rock(String type) { System.out.print(type); } 10. } 11. public class Mountain extends Rock { 12. Mountain() { 13. super("granite "); 14. new Rock("granite "); 15. } 16. public static void main(String[] a) { new Mountain(); } 17. } What is the result?

Explanation

The correct answer is "atom granite atom granite" because when the Mountain class is instantiated, it calls the constructor of the Rock class with the argument "granite". This constructor then prints "granite". Then, a new instance of the Rock class is created with the argument "granite", which also prints "granite". Finally, the constructor of the Mountain class calls the constructor of the Atom class, which prints "atom". Therefore, the output is "atom granite atom granite".

Submit
11. Given: 11. abstract class Vehicle { public int speed() { return 0; } 12. class Car extends Vehicle { public int speed() { return 60; } 13. class RaceCar extends Car { public int speed() { return 150; } ... 21. RaceCar racer = new RaceCar(); 22. Car car = new RaceCar(); 23. Vehicle vehicle = new RaceCar(); 24. System.out.println(racer.speed() + ", " + car.speed() 25. + ", " + vehicle.speed()); What is the result?

Explanation

The result is "150, 150, 150" because the speed() method is overridden in each class. When the speed() method is called on the RaceCar object, it returns 150. Similarly, when the speed() method is called on the Car object and the Vehicle object, they both refer to the RaceCar object and return 150 as well. Therefore, the result is 150, 150, 150.

Submit
12. Given: 10. int x = 0; 11. int y = 10; 12. do { 13. y--; 14. ++x; 15. } while (x < 5); 16. System.out.print(x + "," + y); What is the result?

Explanation

The code snippet is using a do-while loop to decrement the value of y by 1 and increment the value of x by 1 until x is less than 5. Since the initial value of x is 0, the loop will run 5 times (from x = 0 to x = 4). Therefore, the final values of x and y will be 5 and 5 respectively.

Submit
13. Given: 11. public class Barn { 12. public static void main(String[] args) { 13. new Barn().go("hi", 1); 14. new Barn().go("hi", "world", 2); 15. } 16. public void go(String... y, int x) { 17. System.out.print(y[y.length - 1] + " "); 18. } 19. } What is the result?

Explanation

The code will fail to compile because the method go() has a parameter of type int (x) after the varargs parameter (y). According to the rules of varargs, the varargs parameter must be the last parameter in the method signature. Therefore, having an int parameter after the varargs parameter is not allowed and will result in a compilation error.

Submit
14. Given: 11. class Mud { 12. // insert code here 13. System.out.println("hi"); 14. } 15. } And the following five fragments: public static void main(String...a) { public static void main(String.* a) { public static void main(String... a) { public static void main(String[]... a) { public static void main(String...[] a) { How many of the code fragments, inserted independently at line 12, compile?

Explanation

Three of the code fragments, "public static void main(String...a)", "public static void main(String... a)", and "public static void main(String...[] a)", can be inserted independently at line 12 and will compile. These fragments define the main method with the correct syntax, allowing the program to run and print "hi". The other two fragments, "public static void main(String.* a)" and "public static void main(String[]... a)", have incorrect syntax and will not compile.

Submit
15. 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 four objects eligible for the garbage collector. The objects eligible for garbage collection are the ones that are no longer referenced by any active variables. In this case, i2 is set to null, meaning it no longer references any object. Additionally, i3 is reassigned to reference the same object as i1, so the previous object it referenced is also no longer referenced. Therefore, i2 and the two previously referenced objects by i3 are eligible for garbage collection.

Submit
16. Given: 7. void waitForSignal() { 8. Object obj = new Object(); 9. synchronized (Thread.currentThread()) { 10. obj.wait(); 11. obj.notify(); 12. } 13. } Which statement is true?

Explanation

The code can throw an IllegalMonitorStateException because the obj.wait() and obj.notify() methods can only be called within a synchronized block on the object that is being waited on or notified. In this case, the synchronized block is using Thread.currentThread() as the lock object, so calling obj.wait() and obj.notify() will result in an IllegalMonitorStateException.

Submit
17. A UNIX user named Bob wants to replace his chess program with a new one, but he is not sure where the old one is installed. Bob is currently able to run a Java chess program starting from his home directory /home/bob using the command: java -classpath /test:/home/bob/downloads/*.jar games.Chess Bob's CLASSPATH is set (at login time) to: /usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/*.jar What is a possible location for the Chess.class file?

Explanation

A possible location for the Chess.class file is /test/games/Chess.class. This is because the command to run the Java chess program includes the classpath argument "-classpath /test:/home/bob/downloads/*.jar", which means that the program will look for the Chess.class file in the /test directory. Additionally, the package structure of the chess program is specified as "games.Chess", indicating that the Chess.class file should be located in a "games" directory within the classpath. Therefore, /test/games/Chess.class is a possible location for the file.

Submit
18. Given: 3. public class Batman { 4. int squares = 81; 5. public static void main(String[] args) { 6. new Batman().go(); 7. } 8. void go() { 9. incr(++squares); 10. System.out.println(squares); 11. } 12. void incr(int squares) { squares += 10; } 13. } What is the result?

Explanation

The result is 82 because the variable "squares" is incremented by 10 inside the "incr" method, which is called in the "go" method. The "++" operator before "squares" in the line "incr(++squares)" increments the value of "squares" before passing it to the "incr" method. Therefore, the original value of 81 is incremented by 10 to become 91, and then it is printed in the line "System.out.println(squares)" in the "go" method.

Submit
19. Given: 22. public void go() { 23. String o = ""; 24. z: 25. for(int x = 0; x < 3; x++) { 26. for(int y = 0; y < 2; y++) { 27. if(x==1) break; 28. if(x==2 && y==1) break z; 29. o = o + x + y; 30. } 31. } 32. System.out.println(o); 33. } What is the result when the go() method is invoked?

Explanation

The go() method contains nested for loops. The outer loop iterates from 0 to 2, while the inner loop iterates from 0 to 1.

At line 27, if x equals 1, the inner loop is terminated using the "break" statement. This means that when x is 1, the inner loop will not execute and move to the next iteration of the outer loop.

At line 28, if x equals 2 and y equals 1, the outer loop is terminated using the "break z" statement. This means that when x is 2 and y is 1, both the inner and outer loops will be terminated.

The variable "o" stores the concatenation of x and y at each iteration of the inner loop. Therefore, the final value of "o" will be "000120".

Hence, the result when the go() method is invoked is "000120".

Submit
20. Which statement is true?

Explanation

The finalize() method for a given object is called no more than once by the garbage collector. This means that even if the garbage collector runs multiple times, the finalize() method will only be called once for a specific object.

Submit
21. Given: 22. StringBuilder sb1 = new StringBuilder("123"); 23. String s1 = "123"; 24. // insert code here 25. System.out.println(sb1 + " " + s1); Which code fragment, inserted at line 24, outputs "123abc 123abc"?

Explanation

The code fragment "sb1.append("abc"); s1 = s1.concat("abc");" is the correct answer because it appends "abc" to the StringBuilder object sb1 using the append() method and concatenates "abc" to the String object s1 using the concat() method. This ensures that both sb1 and s1 have "abc" added to their original values, resulting in the desired output "123abc 123abc".

Submit
22. Given: 33. try { 34. // some code here 35. } catch (NullPointerException e1) { 36. System.out.print("a"); 37. } catch (Exception e2) { 38. System.out.print("b"); 39. } finally { 40. System.out.print("c"); 41. } If some sort of exception is thrown at line 34, which output is possible?

Explanation

If an exception is thrown at line 34, the catch block at line 35 will catch the exception since it is specifically catching NullPointerException. It will then print "a". After the catch block, the finally block at line 40 will always execute and print "c". Therefore, the possible output in this scenario is "ac".

Submit
23. Given: 1. interface TestA { String toString(); } 2. public class Test { 3. public static void main(String[] args) { 4. System.out.println(new TestA() { 5. public String toString() { return "test"; } 6. }); 7. } 8. } What is the result?

Explanation

The code creates an anonymous inner class that implements the TestA interface and overrides the toString() method to return "test". The anonymous inner class is then instantiated and its toString() method is called when printing to the console. Therefore, the result is "test".

Submit
24. Given: 1. class Super { 2. private int a; 3. protected Super(int a) { this.a = a; } 4. } ... 11. class Sub extends Super { 12. public Sub(int a) { super(a); } 13. public Sub() { this.a = 5; } 14. } Which two, independently, will allow Sub to compile? (Choose two.)

Explanation

Changing line 13 to either "public Sub() { this(5); }" or "public Sub() { super(5); }" will allow the Sub class to compile. In the first case, "this(5);" calls the constructor of the Sub class with the argument 5. In the second case, "super(5);" calls the constructor of the Super class with the argument 5. Both of these changes ensure that the Sub class has a valid constructor that can be used to create objects.

Submit
25. 10. interface Foo {} 11. class Alpha implements Foo {} 12. class Beta extends Alpha {} 13. class Delta extends Beta { 14. public static void main( String[] args ) { 15. Beta x = new Beta(); 16. // insert code here 17. } 18. } Which code, inserted at line 16, will cause a java.lang.ClassCastException?

Explanation

The code "Foo f = (Delta)x;" will cause a java.lang.ClassCastException. This is because the object "x" is of type Beta, and cannot be casted to type Delta, which is a subclass of Beta.

Submit
26. Given: 1. public class Person { 2. private String name; 3. public Person(String name) { this.name = name; } 4. public boolean equals(Person p) { 5. return p.name.equals(this.name); 6. } 7. } Which statement is true?

Explanation

The equals method does not properly override the Object.equals method because it takes a parameter of type Person instead of Object. In order to properly override the equals method, it should have the signature "public boolean equals(Object obj)".

Submit
27. Given: 5. class Building { } 6. public class Barn extends Building { 7. public static void main(String[] args) { 8. Building build1 = new Building(); 9. Barn barn1 = new Barn(); 10. Barn barn2 = (Barn) build1; 11. Object obj1 = (Object) build1; 12. String str1 = (String) build1; 13. Building build2 = (Building) barn1; 14. } 15. } Which is true?

Explanation

Line 12 is attempting to cast the object "build1" of type Building to a String. Since Building is not a subclass of String, this cast is not valid and will result in a compilation error. Therefore, if line 12 is removed, the compilation will succeed.

Submit
28. Given: 11. Float pi = new Float(3.14f); 12. if (pi > 3) { 13. System.out.print("pi is bigger than 3. "); 14. } 15. else { 16. System.out.print("pi is not bigger than 3. "); 17. } 18. finally { 19. System.out.println("Have a nice day."); 20. } What is the result?

Explanation

The given code will result in a compilation error. This is because the "finally" block is placed after the "if-else" statements, which is not allowed in Java. The "finally" block should always come after the "try" and "catch" blocks. Therefore, the code will not compile and an error will occur.

Submit
29. Given a valid DateFormat object named df, and 16. Date d = new Date(0L); 17. String ds = "December 15, 2004"; 18. // insert code here What updates d's value with the date represented by ds?

Explanation

The correct answer is 18. try {
19. d = df.parse(ds);
20. } catch(ParseException e) { };

This code block tries to parse the string representation of a date, "December 15, 2004", using the DateFormat object df. If the parsing is successful, the value of d will be updated to the date represented by ds. If there is a ParseException, the catch block will handle the exception.

Submit
30. 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 code in the main method of the Yippee class is using a for loop to iterate over the elements in the args array, starting from index 1. However, since the length of the args array is 0 in the first command line invocation (java Yippee), the loop condition (x

Submit
31. Which Man class properly represents the relationship "Man has a best friend who is a Dog"?

Explanation

The correct answer is "class Man { private Dog bestFriend; }". This answer properly represents the relationship "Man has a best friend who is a Dog" by declaring a private instance variable "bestFriend" of type Dog within the Man class. This allows each instance of the Man class to have a specific Dog object as their best friend.

Submit
32. Given: 1. public class Threads2 implements Runnable { 2. 3. public void run() { 4. System.out.println("run."); 5. throw new RuntimeException("Problem"); 6. } 7. public static void main(String[] args) { 8. Thread t = new Thread(new Threads2()); 9. t.start(); 10. System.out.println("End of method."); 11. } 12. } Which two can be results? (Choose two.)

Explanation

The code creates a new thread and starts it. In the run() method of the Threads2 class, it prints "run." and then throws a RuntimeException with the message "Problem".

Since the new thread is started, it will execute concurrently with the main thread. So, the order of the output is not guaranteed.

The possible results are:

1. End of method. (printed by the main thread)
2. run. (printed by the new thread)
3. java.lang.RuntimeException: Problem (thrown by the new thread)

Therefore, the correct answers are:
- End of method.
- run.
- java.lang.RuntimeException: Problem

Submit
33. Given two files, GrizzlyBear.java and Salmon.java: 1. package animals.mammals; 2. 3. public class GrizzlyBear extends Bear { 4. void hunt() { 5. Salmon s = findSalmon(); 6. s.consume(); 7. } 8. } 1. package animals.fish; 2. 3. public class Salmon extends Fish { 4. public void consume() { /* do stuff */ } 5. } If both classes are in the correct directories for their packages, and the Mammal class correctly defines the findSalmon() method, which change allows this code to compile?

Explanation

The code in GrizzlyBear.java needs to import the Salmon class from the fish package in order to use the findSalmon() method. Therefore, adding "import animals.fish.*;" at line 2 in GrizzlyBear.java allows the code to compile correctly.

Submit
34. Given: 11. double input = 314159.26; 12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN); 13. String b; 14. //insert code here Which code, inserted at line 14, sets the value of b to 314.159,26?

Explanation

The code "b = nf.format( input );" sets the value of b to 314.159,26. This is because the format() method of the NumberFormat class formats the given number according to the specific locale, in this case, the Italian locale. The formatted number is then assigned to the variable b.

Submit
35. Given that the current directory is empty, and that the user has read and write permissions, and the following: 11. import java.io.*; 12. public class DOS { 13. public static void main(String[] args) { 14. File dir = new File("dir"); 15. dir.mkdir(); 16. File f1 = new File(dir, "f1.txt"); 17. try { 18. f1.createNewFile(); 19. } catch (IOException e) { ; } 20. File newDir = new File("newDir"); 21. dir.renameTo(newDir); 22. } 23. } Which statement is true?

Explanation

The code creates a new directory named "dir" and a new file named "f1.txt" inside that directory. Then, it renames the "dir" directory to "newDir". Therefore, the file system has a directory named "newDir", containing a file "f1.txt".

Submit
36. Given a class Repetition: 1. package utils; 2. 3. public class Repetition { 4. public static String twice(String s) { return s + s; } 5. } and given another class Demo: 1. // insert code here 2. 3. public class Demo { 4. public static void main(String[] args) { 5. System.out.println(twice("pizza")); 6. } 7. } Which code should be inserted at line 1 of Demo.java to compile and run Demo to print "pizzapizza"?

Explanation

The correct answer is "import static utils.Repetition.twice;". This is because the method "twice" is a static method in the class "Repetition", and in order to directly access the method without specifying the class name, we need to use the "import static" statement.

Submit
37. Given: 1. public class Donkey2 { 2. public static void main(String[] args) { 3. boolean assertsOn = true; 4. assert (assertsOn) : assertsOn = true; 5. if(assertsOn) { 6. System.out.println("assert is on"); 7. } 8. } 9. } If class Donkey is invoked twice, the first time without assertions enabled, and the second time with assertions enabled, what are the results?

Explanation

When the class Donkey is invoked for the first time without assertions enabled, the code on line 4 does not execute because the condition (assertsOn) is false. Therefore, the if statement on line 5 is not executed, and there is no output.

When the class Donkey is invoked for the second time with assertions enabled, the code on line 4 executes because the condition (assertsOn) is true. This causes the value of assertsOn to be set to true. Therefore, the if statement on line 5 is executed, and the message "assert is on" is printed as output.

Submit
38. 1. public class Score implements Comparable<Score> { 2. private int wins, losses; 3. public Score(int w, int l) { wins = w; losses = l; } 4. public int getWins() { return wins; } 5. public int getLosses() { return losses; } 6. public String toString() { 7. return "<" + wins + "," + losses + ">"; 8. } 9. // insert code here 10. } Which method will complete this class?

Explanation

The correct method to complete the class is "public int compareTo(Score other){/*more code here*/}". This is because the class implements the Comparable interface, which requires the implementation of the compareTo method. The compareTo method is used to compare two objects of the same class and determine their order. In this case, the compareTo method will compare two Score objects based on their wins and losses, allowing for sorting or ordering of Score objects based on their performance.

Submit
39. Given the following directory structure: bigProject |--source | |--Utils.java | |--classes |-- And the following command line invocation: javac -d classes source/Utils.java Assume the current directory is bigProject, what is the result?

Explanation

The given command line invocation "javac -d classes source/Utils.java" compiles the Utils.java file in the source directory and specifies the output directory as classes using the -d flag. Therefore, if the compilation is successful, the resulting Utils.class file will be added to the classes directory.

Submit
40. Given: 11. public static void parse(String str) { 12. try { 13. float f = Float.parseFloat(str); 14. } catch (NumberFormatException nfe) { 15. f = 0; 16. } finally { 17. System.out.println(f); 18. } 19. } 20. public static void main(String[] args) { 21. parse("invalid"); 22. } What is the result?

Explanation

The compilation fails because the variable "f" is declared inside the try block and is not accessible outside of it. Therefore, when trying to print the value of "f" in the finally block, a compilation error occurs.

Submit
41. 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

not-available-via-ai

Submit
42. Given: 1. public class TestOne { 2. public static void main (String[] args) throws Exception { 3. Thread.sleep(3000); 4. System.out.println("sleep"); 5. } 6. } What is the result?

Explanation

The code executes normally and prints "sleep" because the main method is the entry point of the program and it is executed sequentially. The Thread.sleep(3000) method pauses the execution of the program for 3000 milliseconds (3 seconds), allowing the "sleep" message to be printed after the pause.

Submit
43. Given: 21. class Money { 22. private String country = "Canada"; 23. public String getC() { return country; } 24. } 25. class Yen extends Money { 26. public String getC() { return super.country; } 27. } 28. public class Euro extends Money { 29. public String getC(int x) { return super.getC(); } 30. public static void main(String[] args) { 31. System.out.print(new Yen().getC() + " " + new Euro().getC()); 32. } 33. } What is the result?

Explanation

The correct answer is "Compilation fails due to an error on line 26." This is because the method getC() in the Yen class is trying to access the private variable "country" from the superclass Money using the "super" keyword. However, since "country" is a private variable, it is not accessible from the subclass Yen, resulting in a compilation error.

Submit
44. Given: 11. public class Test { 12. public static void main(String [] args) { 13. int x = 5; 14. boolean b1 = true; 15. boolean b2 = false; 16. 17. if ((x == 4) && !b2 ) 18. System.out.print("1 "); 19. System.out.print("2 "); 20. if ((b2 = true) && b1 ) 21. System.out.print("3 "); 22. } 23. } What is the result?

Explanation

The result is "2 3" because the first if statement on line 17 evaluates to false since x is not equal to 4 and b2 is false. Therefore, the code inside the if statement is not executed. The second if statement on line 20 evaluates to true since b2 is assigned the value true and b1 is true. Therefore, the code inside the if statement is executed and "3" is printed. Finally, the program reaches the end of the main method and terminates, resulting in the output "2 3".

Submit
45. Which two statements are true? (Choose two.)

Explanation

The first statement is true because deadlock can occur when multiple threads are waiting for resources that are held by other threads, resulting in a circular dependency. Therefore, it is possible for more than two threads to deadlock at once.

The last statement is also true because invoking Thread.yield() only gives a hint to the scheduler that the current thread is willing to yield its current use of the processor. It does not guarantee that deadlock will be eliminated if the code is already capable of deadlocking.

Submit
46. Given: 1. public class Threads3 implements Runnable { 2. public void run() { 3. System.out.print("running"); 4. } 5. public static void main(String[] args) { 6. Thread t = new Thread(new Threads3()); 7. t.run(); 8. t.run(); 9. t.start(); 10. } 11. } What is the result?

Explanation

The code creates a new Thread object "t" and passes an instance of the Threads3 class as the target for the thread. The run() method of the Threads3 class prints "running".

In line 7 and 8, t.run() is called twice, which simply executes the run() method in the current thread, without starting a new thread. So, "running" is printed twice.

In line 9, t.start() is called, which starts a new thread and invokes the run() method in that new thread. So, "running" is printed for the third time.

Therefore, the code executes and prints "runningrunningrunning".

Submit
47. Which two statements are true about the hashCode method? (Choose two.)

Explanation

The first statement is true because the hashCode method can be used to check if two objects are not equal. The second statement is true because the hashCode method is used by the java.util.HashSet collection class to group elements into hash buckets for efficient retrieval.

Submit
48. Given: 23. Object [] myObjects = { 24. new Integer(12), 25. new String("foo"), 26. new Integer(5), 27. new Boolean(true) 28. }; 29. Arrays.sort(myObjects); 30. for(int i=0; i<myObjects.length; i++) { 31. System.out.print(myObjects[i].toString()); 32. System.out.print(" "); 33. } What is the result?

Explanation

The line 29 is attempting to sort the array "myObjects" using the Arrays.sort() method. However, the array contains objects of different types (Integer, String, and Boolean), which cannot be directly compared. This results in a ClassCastException, as the sort method cannot determine the correct order of the objects.

Submit
49. Given: 11. String[] elements = { "for", "tea", "too" }; 12. String first = (elements.length > 0) elements[0] : null; What is the result?

Explanation

The given code initializes an array of strings called "elements" with three values. Then, it declares a string variable "first" and assigns the value of the first element of the "elements" array to it using the ternary operator. Since the length of the "elements" array is greater than 0, the condition of the ternary operator is true and the value of the first element is assigned to "first". Therefore, the variable "first" is set to elements[0].

Submit
50. Given: 11. public abstract class Shape { 12. private int x; 13. private int y; 14. public abstract void draw(); 15. public void setAnchor(int x, int y) { 16. this.x = x; 17. this.y = y; 18. } 19. } Which two classes use the Shape class correctly? (Choose two.)

Explanation

The first class uses the Shape class correctly because it extends the Shape class and implements the abstract methods. The second class also uses the Shape class correctly because it extends the Shape class and provides an implementation for the draw() method.

Submit
51. QUESTION: 57 Given: 13. public class Pass { 14. public static void main(String [] args) { 15. int x = 5; 16. Pass p = new Pass(); 17. p.doStuff(x); 18. System.out.print(" main x = " + x); 19. } 20. 21. void doStuff(int x) { 22. System.out.print(" doStuff x = " + x++); 23. } 24. } What is the result?

Explanation

The result is "doStuff x = 5 main x = 5" because the variable "x" is passed to the method "doStuff" and is printed with the value of 5. However, the post-increment operator (x++) is used, so the value of "x" is incremented after it is printed in the method. Therefore, when it is printed again in the main method, the value of "x" is still 5.

Submit
52. A team of programmers is reviewing a proposed API for a new utility class. After some discussion, they realize that they can reduce the number of methods in the API without losing any functionality. If they implement the new design, which two OO principles will they be promoting?

Explanation

If the team of programmers decides to reduce the number of methods in the API without losing any functionality, they will be promoting two OO principles: looser coupling and higher cohesion. Looser coupling means that the classes or components in the system are less dependent on each other, making it easier to make changes or updates without affecting other parts of the system. Higher cohesion means that the methods and functionality within a class or component are closely related and focused, leading to a more organized and maintainable codebase.

Submit
53. Given: 11. class Alpha { 12. public void foo() { System.out.print("Afoo "); } 13. } 14. public class Beta extends Alpha { 15. public void foo() { System.out.print("Bfoo "); } 16. public static void main(String[] args) { 17. Alpha a = new Beta(); 18. Beta b = (Beta)a; 19. a.foo(); 20. b.foo(); 21. } 22. } What is the result?

Explanation

The result is "Bfoo Bfoo" because the main method creates an instance of the Beta class and assigns it to a variable of type Alpha. Then, it creates an instance of the Beta class and assigns it to a variable of type Beta. When the foo() method is called on both variables, the overridden version of the method in the Beta class is executed, which prints "Bfoo".

Submit
54. Given: 11. static void test() throws RuntimeException { 12. try { 13. System.out.print("test "); 14. throw new RuntimeException(); 15. } 16. catch (Exception ex) { System.out.print("exception "); } 17. } 18. public static void main(String[] args) { 19. try { test(); } 20. catch (RuntimeException ex) { System.out.print("runtime "); } 21. System.out.print("end "); 22. } What is the result?

Explanation

The code defines a method called "test" that throws a RuntimeException. In the main method, the "test" method is called within a try-catch block. Since the "test" method throws a RuntimeException, it is caught by the catch block in the main method. Therefore, the code will print "test exception end".

Submit
55. Given: 31. // some code here 32. try { 33. // some code here 34. } catch (SomeException se) { 35. // some code here 36. } finally { 37. // some code here 38. } Under which three circumstances will the code on line 37 be executed? (Choose three.)

Explanation

The code on line 37 will be executed under the following three circumstances:
1) When the code on line 33 throws an exception, the catch block on line 34 will handle the exception and then the code on line 37 will be executed in the finally block.
2) When the code on line 35 throws an exception, the catch block on line 34 will handle the exception and then the code on line 37 will be executed in the finally block.
3) When the code on line 33 executes successfully without throwing any exception, the code on line 37 will still be executed in the finally block.

Submit
56. Given: 1. public class Threads4 { 2. public static void main (String[] args) { 3. new Threads4().go(); 4. } 5. public void go() { 6. Runnable r = new Runnable() { 7. public void run() { 8. System.out.print("foo"); 9. } 310-065 4 https://www.testkiller.com https://www.troytec.com 10. }; 11. Thread t = new Thread(r); 12. t.start(); 13. t.start(); 14. } 15. } What is the result?

Explanation

The code will throw an exception at runtime because the start() method of a Thread can only be called once. In this code, the start() method is called twice on the same Thread object, which is not allowed and will result in an exception being thrown.

Submit
57. Given: 1. public class Threads4 { 2. public static void main (String[] args) { 3. new Threads4().go(); 4. } 5. public void go() { 6. Runnable r = new Runnable() { 7. public void run() { 8. System.out.print("foo"); 9. } 10. }; 11. Thread t = new Thread(r); 12. t.start(); 13. t.start(); 14. } 15. } What is the result?

Explanation

The code throws an exception at runtime because the start() method of the Thread class can only be called once. In this code, the start() method is called twice on the same thread object 't', which is not allowed and results in an exception being thrown.

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

Explanation

The correct answer is the first and second options. These two classes correctly implement both the java.lang.Runnable and the java.lang.Cloneable interfaces. The first class, Session, implements the Runnable interface with the run() method and the Cloneable interface with the clone() method. The second class, Session, also implements the Runnable interface with the run() method and the Cloneable interface with the clone() method.

Submit
59. Given a pre-generics implementation of a method: 11. public static int sum(List list) { 12. int sum = 0; 13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) { 14. int i = ((Integer)iter.next()).intValue(); 15. sum += i; 16. } 17. return sum; 18. } What three changes allow the class to be used with generics and avoid an unchecked warning? (Choose three.)

Explanation

The first change, removing line 14, allows the class to be used with generics because it eliminates the need to cast the object returned by the iterator to an Integer.

The second change, replacing line 13 with "for (int i : intList) {", allows the class to be used with generics because it uses the enhanced for loop syntax for iterating over the list, which automatically handles the casting of the objects to the specified type.

The third change, replacing the method declaration with "sum(List intList)", allows the class to be used with generics because it specifies the type parameter for the List, ensuring type safety and avoiding an unchecked warning.

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

Explanation

The code is attempting to add the value of variable "y" to the value of variable "i", but variable "i" has not been assigned a value. This results in a NullPointerException at runtime because the code is trying to perform an operation on a null object.

Submit
61. Given: 1. public class Blip { 2. protected int blipvert(int x) { return 0; } 3. } 4. class Vert extends Blip { 310-065 10 https://www.testkiller.com https://www.troytec.com 5. // insert code here 6. } Which five methods, inserted independently at line 5, will compile? (Choose five.)

Explanation

The correct answer includes five methods that will compile at line 5. These methods have different parameter types and access modifiers, but they all have the same name "blipvert" and return type. This is allowed because they are considered overloaded methods, meaning they have the same name but different parameters. The access modifiers in the correct answer are public, private, and protected, which are all valid for methods in a subclass. The parameter types include int and long, which are also valid. Overall, the correct answer provides a variety of valid methods that can be inserted at line 5.

Submit
62. Given: 11. public interface A111 { 12. String s = "yo"; 13. public void method1(); 14. } 17. interface B { } 20. interface C extends A111, B { 21. public void method1(); 22. public void method1(int x); 23. } What is the result?

Explanation

The compilation succeeds because the code follows the correct syntax for interfaces. The interface A111 declares a variable "s" and a method "method1()", while interface C extends both interface A111 and interface B and overrides the method "method1()" with two versions, one without parameters and another with an integer parameter. There are no syntax errors in the code, so the compilation is successful.

Submit
63. Given: public class NamedCounter { private final String name; private int count; public NamedCounter(String name) { this.name = name; } public String getName() { return name; } public void increment() { count++; } public int getCount() { return count; } public void reset() { count = 0; } Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)

Explanation

To adapt this class to be used safely by multiple threads, the methods reset(), getCount(), and increment() should be declared using the synchronized keyword. This ensures that only one thread can access these methods at a time, preventing any concurrent modification issues. By synchronizing these methods, it guarantees that the shared count variable is accessed and modified atomically, avoiding any race conditions. Declaring the constructor or other methods with the synchronized keyword is not necessary in this case as they do not involve shared data or critical sections.

Submit
View My Results

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

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

  • Current Version
  • Mar 17, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Mar 08, 2018
    Quiz Created by
    Ganeshkumar
Cancel
  • All
    All (63)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
Given: ...
Given: ...
Given: ...
Given: ...
Assuming that the serializeBanana() and the deserializeBanana()...
Given: ...
Given: ...
Which capability exists only in java.io.FileWriter?
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
A UNIX user named Bob wants to replace his chess program with a new...
Given: ...
Given: ...
Which statement is true?
Given: ...
Given: ...
Given: ...
Given: ...
10. interface Foo {} ...
Given: ...
Given: ...
Given: ...
Given a valid DateFormat object named df, and ...
Given: ...
Which Man class properly represents the relationship "Man has a...
Given: ...
Given two files, GrizzlyBear.java and Salmon.java: ...
Given: ...
Given that the current directory is empty, and that the user has read...
Given a class Repetition: ...
Given: ...
1. public class Score implements Comparable<Score> { ...
Given the following directory structure: ...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Which two statements are true? (Choose two.)
Given: ...
Which two statements are true about the hashCode method? (Choose two.)
Given: ...
Given: ...
Given: ...
QUESTION: 57 ...
A team of programmers is reviewing a proposed API for a new utility...
Given: ...
Given: ...
Given: ...
Given: ...
Given: ...
Which two classes correctly implement both the java.lang.Runnable and...
Given a pre-generics implementation of a method: ...
Given: ...
Given: ...
Given: ...
Given: ...
Alert!

Advertisement