Core Java Test 6

Approved & Edited by ProProfs Editorial Team
The editorial team at ProProfs Quizzes consists of a select group of subject experts, trivia writers, and quiz masters who have authored over 10,000 quizzes taken by more than 100 million users. This team includes our in-house seasoned quiz moderators and subject matter experts. Our editorial experts, spread across the world, are rigorously trained using our comprehensive guidelines to ensure that you receive the highest quality quizzes.
Learn about Our Editorial Process
| By Dhaya315
D
Dhaya315
Community Contributor
Quizzes Created: 1 | Total Attempts: 256
Questions: 40 | Attempts: 256

SettingsSettingsSettings
Core Java Quizzes & Trivia

Questions and Answers
  • 1. 

    What happens when this code is compiled and executed? String name = null; File file = new File("/folder", name); System.out.print(file.exists());

    • A.

      A.It prints “true”.

    • B.

      B.It prints “false”.

    • C.

      C.NullPointerException at second line.

    • D.

      D.NullPointerException at third line.

    Correct Answer
    B. B.It prints “false”.
    Explanation
    The code initializes the variable "name" as null and then creates a new File object with the directory path "/folder" and the null value of "name". Since the "name" variable is null, the File object will not point to any specific file. Therefore, the exists() method will return false because there is no file at the specified directory path.

    Rate this question:

  • 2. 

    Consider an empty file C:/empty.txt. What happens when this code is compiled and executed? void test() throws IOException { BufferedReader reader = new BufferedReader(           new FileReader("C:/empty.txt")); System.out.println(reader.getLine()); }

    • A.

      A.It prints an empty string “”.

    • B.

      B.It prints null.

    • C.

      C.A NullPointerException is thrown at runtime.

    • D.

      D.Compilation fails.

    Correct Answer
    D. D.Compilation fails.
    Explanation
    The code will fail to compile because the method `getLine()` does not exist in the BufferedReader class.

    Rate this question:

  • 3. 

    What happens when this code is compiled and executed? void test() throws IOException { FileWriter writer = new FileWriter("/fun.log"); writer.write("Hello!"); writer.close(); }

    • A.

      A.A file fun.log is created with the content “Hello!”.

    • B.

      B.A file fun.log is created but it’s empty, because flush() was not called.

    • C.

      C.A runtime exception is thrown because flush() was not called.

    • D.

      D.Compilation fails.

    Correct Answer
    A. A.A file fun.log is created with the content “Hello!”.
    Explanation
    When this code is compiled and executed, a file named "fun.log" is created. The FileWriter object is used to write the string "Hello!" to the file. After writing the content, the writer is closed, which ensures that any buffered data is flushed and the file is properly closed. Therefore, the file "fun.log" is created with the content "Hello!".

    Rate this question:

  • 4. 

    What happens when this code is compiled and executed? void test() throws IOException { PrintWriter writer = new PrintWriter(new PrintWriter("yo.txt")); writer.print("yo"); writer.flush(); writer.close(); }

    • A.

      A.Compilation fails because a PrintWriter cannot accept a PrintWriter in its constructor.

    • B.

      B.Compilation fails because there is no method print().

    • C.

      C.Two files yo.txt with the same content are created.

    • D.

      D.A file yo.txt with the content “yo” is created.

    Correct Answer
    D. D.A file yo.txt with the content “yo” is created.
    Explanation
    The code creates a new PrintWriter object with the file name "yo.txt" as its constructor argument. The code then uses the print() method of the PrintWriter object to write the string "yo" to the file. The flush() method is called to ensure that any buffered data is written to the file, and then the close() method is called to close the file. Therefore, when the code is compiled and executed, a file named "yo.txt" is created with the content "yo".

    Rate this question:

  • 5. 

    Which of these classes defined in java.io and used for file-handling are abstract. Select the two correct answers.

    • A.

      A.InputStream

    • B.

      B.PrintStream

    • C.

      C.Reader

    • D.

      D.FileInputStream

    • E.

      FileWriter

    Correct Answer(s)
    A. A.InputStream
    C. C.Reader
    Explanation
    The classes InputStream and Reader are both abstract classes defined in the java.io package and used for file-handling. These classes provide a framework for reading data from a file, but they cannot be instantiated directly. Instead, they are meant to be extended by concrete subclasses that provide specific implementations for reading different types of data. This abstraction allows for greater flexibility and modularity in file-handling operations.

    Rate this question:

  • 6. 

    Import java.io.*; class Player { Player() { System.out.print("p"); } } class CardPlayer extends Player implements Serializable { CardPlayer() { System.out.print("c"); } public static void main(String[] args) { CardPlayer c1 = new CardPlayer(); try { FileOutputStream fos = new FileOutputStream("play.txt"); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(c1); os.close(); FileInputStream fis = new FileInputStream("play.txt"); ObjectInputStream is = new ObjectInputStream(fis); CardPlayer c2 = (CardPlayer) is.readObject(); is.close(); } catch (Exception x ) { } } } What is the result?

    • A.

      A.pc

    • B.

      B.pcc

    • C.

      C.pcp

    • D.

      D.pcpc

    • E.

      E.Compilation fails

    • F.

      F.An exception is thrown at runtime

    Correct Answer
    C. C.pcp
    Explanation
    The code creates an instance of the CardPlayer class and serializes it to a file named "play.txt". Then, it reads the serialized object from the file and casts it back to a CardPlayer object.

    The output of the program is "pcp".


    - When the CardPlayer object is created, it first calls the constructor of the superclass Player, which prints "p".
    - Then, it calls its own constructor, which prints "c".
    - After serializing and deserializing the object, the main method prints "p" again.
    - Finally, it prints "c" when the constructor of the CardPlayer object is called again.

    Therefore, the output is "pcp".

    Rate this question:

  • 7. 

    Class TKO { public static void main(String[] args) { String s = "-"; Integer x = 343; long L343 = 343L; if(x.equals(L343)) s += ".e1 "; if(x.equals(343)) s += ".e2 "; Short s1 = (short)((new Short((short)343)) / (new Short((short)49))); if(s1 == 7) s += "=s "; if(s1 < new Integer(7+1)) s += "fly "; System.out.println(s); } } Which of the following will be included in the output String s? (Choose all that apply.)

    • A.

      A).e1

    • B.

      B).e2

    • C.

      C)=s

    • D.

      D)fly

    • E.

      E)none of the above

    • F.

      F)compilation fails

    • G.

      G)run time exception

    Correct Answer(s)
    B. B).e2
    C. C)=s
    D. D)fly
    Explanation
    The output String s will include "e2", ".e1", "=s", and "fly". The condition "if(x.equals(343))" evaluates to true, so ".e2" is added to the String s. The condition "if(s1 == 7)" also evaluates to true, so "=s" is added to the String s. Finally, the condition "if(s1 < new Integer(7+1))" evaluates to true, so "fly" is added to the String s.

    Rate this question:

  • 8. 

    Import java.io.*;  class Vehicle { }  class Wheels { }  class Car extends Vehicle implements Serializable { }  class Ford extends Car { }  class Dodge extends Car {  Wheels w = new Wheels();  } Instances of which class(es) can be serialized? (Choose all that apply.)

    • A.

      A.Car

    • B.

      B.Ford

    • C.

      C.Dodge

    • D.

      D.Wheels

    • E.

      E.Vehicle

    Correct Answer(s)
    A. A.Car
    B. B.Ford
    Explanation
    Instances of the Car class and its subclass Ford can be serialized. This is because the Car class implements the Serializable interface, which allows its instances to be converted into a byte stream and saved to a file or transmitted over a network. The Ford class is a subclass of Car, so it inherits the Serializable interface and can also be serialized. The Dodge class, although a subclass of Car, cannot be serialized because it contains a non-serializable member variable (Wheels). The Vehicle class and the Wheels class do not implement the Serializable interface and therefore cannot be serialized.

    Rate this question:

  • 9. 

    Import java.util.regex.*; public class Archie {  public static void main(String[] args) {  Pattern p = Pattern.compile(args[0]); Matcher m = p.matcher(args[1]); int count = 0;  while(m.find())  count++;  System.out.print(count);  }  } And given the command line invocation: java Archie "\d+" ab2c4d67 What is the result?

    • A.

      A.0

    • B.

      B.3

    • C.

      C.4

    • D.

      D.8

    • E.

      E.9

    • F.

      F.compailation fails

    Correct Answer
    B. B.3
    Explanation
    The given code is a Java program that uses regular expressions to count the number of occurrences of a specific pattern in a given input string. The regular expression pattern is provided as the first command line argument, and the input string is provided as the second command line argument.

    In this case, the regular expression pattern "\d+" matches one or more digits. The input string "ab2c4d67" contains the digits 2, 4, and 67, so the pattern matches three times. Therefore, the result of the program is 3, which corresponds to option b.

    Rate this question:

  • 10. 

    Import java.util.*;  public class Looking { public static void main(String[] args) { String input = "1 2 a 3 45 6"; Scanner sc = new Scanner(input); int x = 0; do { x = sc.nextInt(); System.out.print(x + " ");  } while (x!=0);  }  } what is the result??

    • A.

      A.1 2

    • B.

      B.1 2 3 45 6

    • C.

      C.1 2 3 4 5 6

    • D.

      D.1 2 a 3 45 6

    • E.

      E.compilation fails

    • F.

      F.1 2 followed by an exception

    Correct Answer
    F. F.1 2 followed by an exception
    Explanation
    The code is trying to read integers from the given input string using a Scanner object. However, when it encounters the character 'a' in the input string, it throws an InputMismatchException because it is unable to parse it as an integer. Therefore, the code will print "1 2" before throwing the exception.

    Rate this question:

  • 11. 

    Which class is used to write streams of raw bytes to a file?

    • A.

      A.FileReader

    • B.

      B.FileWriter

    • C.

      C.FileInputStream

    • D.

      D.FileOutputStream

    Correct Answer
    C. C.FileInputStream
    Explanation
    The correct answer is c.FileInputStream. This class is used to read streams of raw bytes from a file. It is commonly used when dealing with binary files or when you need to read the contents of a file as raw bytes.

    Rate this question:

  • 12. 

    What happens when this code is compiled and executed? void test() throws IOException { for (int index = 1; index <= 2; index++) { PrintWriter writer = new PrintWriter("/apa"); writer.print("apa"); writer.close(); } }

    • A.

      A.A file apa is created with content “apa”.

    • B.

      B.A file apa is created with content “apaapa”.

    • C.

      C.Two files are created.

    • D.

      D.An exception is thrown at runtime.

    Correct Answer
    A. A.A file apa is created with content “apa”.
    Explanation
    The code creates a file named "apa" and writes the string "apa" into it. The code is executed in a loop that runs twice, so the file "apa" is created and overwritten with the string "apa" twice. Therefore, the final content of the file will be "apa".

    Rate this question:

  • 13. 

    A thread that has called the wait() method of an  object     still owns the lock of the object.

    • A.

      A.True

    • B.

      B.False

    Correct Answer
    B. B.False
    Explanation
    When a thread calls the wait() method of an object, it releases the lock of that object and enters a waiting state. This means that the thread no longer owns the lock of the object. Therefore, the given statement is false.

    Rate this question:

  • 14. 

    A number of threads of the same priority  have relinquished the lock     on a monitor and are in a waiting state after having called the wait()     method of the object. A new thread enters the monitor and calls the     notifyAll() method of the meonitor. Which of these threads will be the     first one to resume?

    • A.

      A.The thread that has been waiting the longest.

    • B.

      B.The thread that was the last one to to exit the monitor.

    • C.

      C.You can never be sure which thread will get to run first.

    • D.

      D.The the first thread that called the wait() method

    Correct Answer
    C. C.You can never be sure which thread will get to run first.
    Explanation
    The order in which threads are resumed after calling the notifyAll() method is not guaranteed. It depends on the underlying thread scheduling algorithm of the operating system. Therefore, you can never be sure which thread will get to run first.

    Rate this question:

  • 15. 

    Which of these are valid contructors of a Thread object?

    • A.

      A.public Thread(Object obj)x

    • B.

      B.public Thread(String name)

    • C.

      C.public Thread(Runnable trgt)

    • D.

      D.public Thread(ThreadGroup grp, Runnable trgt, String name)

    • E.

      E.public Thread(ThreadGroup grp, Object ob)

    Correct Answer(s)
    B. B.public Thread(String name)
    C. C.public Thread(Runnable trgt)
    D. D.public Thread(ThreadGroup grp, Runnable trgt, String name)
    Explanation
    The correct answers are b. public Thread(String name), c. public Thread(Runnable trgt), and d. public Thread(ThreadGroup grp, Runnable trgt, String name). These options represent valid constructors for a Thread object. The first constructor allows you to specify a name for the thread, the second constructor takes a Runnable object as a parameter, and the third constructor allows you to specify a thread group, a runnable object, and a name for the thread.

    Rate this question:

  • 16. 

    If you call  the interrupted() method of a thread object twice     the second call will always return false. 

    • A.

      A.True

    • B.

      B.False

    Correct Answer
    A. A.True
    Explanation
    The interrupted() method in Java is used to check if the current thread has been interrupted or not. When the interrupted() method is called, it clears the interrupted status of the thread and returns true if it was interrupted, otherwise false. If the interrupted() method is called twice on the same thread object, the second call will always return false because the interrupted status has already been cleared by the first call.

    Rate this question:

  • 17. 

    Which of the following are methods of the Thread class? choose all that apply...

    • A.

      A.public void run()

    • B.

      B.public void start()

    • C.

      C.public void exit()

    • D.

      D.public final void setAccess()

    • E.

      E.public final void setPriority(int priNbr)

    • F.

      F.public final int getPriority()

    Correct Answer(s)
    A. A.public void run()
    B. B.public void start()
    E. E.public final void setPriority(int priNbr)
    F. F.public final int getPriority()
    Explanation
    The methods of the Thread class are used to control and manage threads in Java. The correct answers are:

    a. public void run(): This method is used to define the code that will be executed when the thread is started.

    b. public void start(): This method is used to start the execution of the thread.

    e. public final void setPriority(int priNbr): This method is used to set the priority of the thread.

    f. public final int getPriority(): This method is used to get the priority of the thread.

    Rate this question:

  • 18. 

    Calling the destroy() method of a thread object relases all the locks held by     the thread ?

    • A.

      A.True

    • B.

      B.False

    Correct Answer
    B. B.False
    Explanation
    Calling the destroy() method of a thread object does not release all the locks held by the thread. The destroy() method is deprecated and should not be used as it is unsafe and can lead to unpredictable behavior. To release locks held by a thread, the proper approach is to ensure that the locks are released within the code executed by the thread itself, either by using try-finally blocks or by using the synchronized keyword appropriately.

    Rate this question:

  • 19. 

    What will happen when you attempt to compile and run the following code ? 1. public class Test extends Thread{ 2. public static void main(String argv[]){ 3. Test t = new Test(); 4. t.run(); 5. t.start(); 6. } 7. public void run(){ 8. System.out.println(“run-test”); 9. } 10. }

    • A.

      A).run-test run-test

    • B.

      B).run-test

    • C.

      C)Compilation fails due to an error on line 4

    • D.

      D)Compilation fails due to an error on line 7

    Correct Answer
    A. A).run-test run-test
    Explanation
    The code creates a class named Test that extends the Thread class. In the main method, an instance of Test is created and its run method is called directly on line 4. Then, the start method is called on the same instance on line 5.

    When the code is compiled and run, it will print "run-test" twice because the run method is called directly on line 4, and then the start method will execute the run method again in a separate thread. Therefore, the correct answer is "a).run-test run-test".

    Rate this question:

  • 20. 

    What is the output for the below code ? class A implements Runnable{ public void run(){ System.out.println(“run-a”); } } 1. public class Test { 2. public static void main(String… args) { 3. A a = new A(); 4. Thread t = new Thread(a); 5. t.start(); 6. t.start(); 7. } 8. }

    • A.

      A.run-a

    • B.

      B.run-a run-a

    • C.

      C.Compilation fails with an error at line 6

    • D.

      D.Compilation succeed but Runtime Exception

    Correct Answer
    D. D.Compilation succeed but Runtime Exception
    Explanation
    The code will compile successfully, but it will throw a runtime exception 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.

    Rate this question:

  • 21. 

    What is the output for the below code ? class A implements Runnable{ public void run(){ try{ for(int i=0;i<4;i++){ Thread.sleep(100); System.out.println(Thread.currentThread().getName()); } }catch(InterruptedException e){ } } } public class Test { public static void main(String argv[]) throws Exception{ A a = new A(); Thread t = new Thread(a,”A”); Thread t1 = new Thread(a,”B”); t.start(); t.join(); t1.start(); } }

    • A.

      A.A A A A B B B B

    • B.

      B.A B A B A B A B

    • C.

      C.Output order is not guaranteed

    • D.

      D.Compilation succeed but Runtime Exception

    Correct Answer
    A. A.A A A A B B B B
    Explanation
    The correct answer is a.A A A A B B B B. This is because the code creates two threads, t and t1, both using the same instance of class A as the Runnable object. When t starts, it enters the run() method of class A and executes the for loop, printing "A" four times with a 100ms delay between each print. After t finishes executing, t1 starts and also enters the run() method of class A, printing "B" four times with the same delay. Therefore, the output will be "A A A A B B B B".

    Rate this question:

  • 22. 

    What is the output for the below code ? class A extends Thread{ int count = 0; public void run(){ System.out.println(“run”); synchronized (this) { for(int i =0; i < 50 ; i++){ count = count + i; } notify(); } } } public class Test{ public static void main(String argv[]) { A a = new A(); a.start(); synchronized (a) { System.out.println(“waiting”); try{ a.wait(); }catch(InterruptedException e){ } System.out.println(a.count); } } }

    • A.

      A.waiting run 1225

    • B.

      B.waiting run 0

    • C.

      C.waiting run and count can be anything

    • D.

      D.Compilation fails

    Correct Answer
    A. A.waiting run 1225
    Explanation
    The code creates a class A that extends Thread and overrides the run() method. In the run() method, it prints "run" and then enters a synchronized block using "this" as the lock. Inside the synchronized block, it runs a loop from 0 to 49 and adds the value of "i" to the "count" variable. After the loop, it calls notify() to notify any waiting threads.

    In the main method of the Test class, it creates an instance of class A and starts the thread. Then it enters a synchronized block using the instance "a" as the lock. Inside the synchronized block, it prints "waiting" and then calls a.wait() to wait for the thread "a" to complete. Once the thread "a" completes and calls notify(), the main thread continues and prints the value of "a.count", which is 1225.

    Therefore, the output of the code is "waiting run 1225".

    Rate this question:

  • 23. 

    Which of the following statements about this code are true? class A extends Thread{ public void run(){ for(int i =0; i < 2; i++){ System.out.println(i); } } } public class Test{ public static void main(String argv[]){ Test t = new Test(); t.check(new A(){}); } public void check(A a){ a.start(); } }

    • A.

      A.0 0

    • B.

      B.Compilation error, class A has no start method

    • C.

      C.0 1

    • D.

      D.Compilation succeed but runtime exception

    Correct Answer
    C. C.0 1
    Explanation
    The code provided defines a class A that extends the Thread class and overrides its run() method. In the main method of the Test class, an object of Test class is created and its check() method is called with an anonymous inner class that extends class A as an argument. The check() method then calls the start() method on the passed object, which starts the execution of the run() method in class A. The run() method prints the values of i (0 and 1) using the System.out.println() method. Therefore, the correct answer is c.0 1.

    Rate this question:

  • 24. 

    The following block of code creates a Thread using a Runnable target: Runnable target = new MyRunnable(); Thread myThread = new Thread(target); Which of the following classes can be used to create the target, so that the preceding code compiles correctly?

    • A.

      A.public class MyRunnable extends Runnable{public void run(){}}

    • B.

      B.public class MyRunnable extends Object{public void run(){}}

    • C.

      C.public class MyRunnable implements Runnable{public void run(){}}

    • D.

      D.public class MyRunnable implements Runnable{void run(){}}

    • E.

      E.public class MyRunnable implements Runnable{public void start(){}}

    Correct Answer
    C. C.public class MyRunnable implements Runnable{public void run(){}}
    Explanation
    The correct answer is c because it defines a class called MyRunnable that implements the Runnable interface and provides an implementation for the run() method, which is required by the interface. This allows the MyRunnable object to be used as a target for creating a new Thread.

    Rate this question:

  • 25. 

    Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)

    • A.

      Public int read(){return a+b;} a.public void set(int a, int b){this.a=a;this.b=b;}

    • B.

      Public synchronized int read(){return a+b;} b.public synchronized void set(int a, int b){this.a=a;this.b=b;}

    • C.

      C.public int read(){synchronized(a){return a+b;}} public void set(int a, int b){synchronized(a){this.a=a;this.b=b;}}

    • D.

      Public int read(){synchronized(a){return a+b;}} public void set(int a, int b){synchronized(b){this.a=a;d.this.b=b;}}

    • E.

      Public synchronized(this) int read(){return a+b;} public synchronized(this) void set(int a, int b){this.a=a;e.this.b=b;}

    • F.

      Public int read(){synchronized(this){return a+b;}} public void set(int a, int b){synchronized(this){this.a=a;f.this.b=b;}}

    Correct Answer(s)
    B. Public synchronized int read(){return a+b;} b.public synchronized void set(int a, int b){this.a=a;this.b=b;}
    F. Public int read(){synchronized(this){return a+b;}} public void set(int a, int b){synchronized(this){this.a=a;f.this.b=b;}}
    Explanation
    The correct answers are the methods that use the "synchronized" keyword to ensure exclusive access to the variables "a" and "b". By synchronizing the methods, concurrent access problems can be prevented because only one thread can access the variables at a time. The first correct answer is "public synchronized int read(){return a+b;}" because it synchronizes the read method, and the second correct answer is "public synchronized void set(int a, int b){this.a=a;this.b=b;}" because it synchronizes the set method. The third option, "public int read(){synchronized(this){return a+b;}} public void set(int a, int b){synchronized(this){this.a=a;f.this.b=b;}}", is incorrect because it synchronizes the methods using the "this" reference, which does not provide exclusive access to the variables.

    Rate this question:

  • 26. 

    Given: 1. public class WaitTest { 2. public static void main(String [] args) { 3. System.out.print("1 "); 4. synchronized(args){ 5. System.out.print("2 "); 6. try { 7. args.wait(); 8. } 9. catch(InterruptedException e){} 10. } 11. System.out.print("3 "); 12. } } What is the result of trying to compile and run this program?

    • A.

      It fails to compile because the IllegalMonitorStateException of wait() is not dealt a.with in line 7

    • B.

      B.2 3

    • C.

      C.1 3

    • D.

      D.1 2

    • E.

      At runtime, it throws an IllegalMonitorStateException when e.trying to wait

    • F.

      It will fail to compile because it has to be synchronized on the f.this object

    Correct Answer
    D. D.1 2
    Explanation
    The program will print "1 2" and then terminate successfully. The reason is that the code is synchronized on the "args" object, which means that only one thread can execute the synchronized block at a time. The "wait()" method is called on the "args" object, which causes the current thread to wait until another thread notifies it. However, since there are no other threads in this program to notify the waiting thread, it will simply continue executing after the wait() method and print "3". Therefore, the output will be "1 2 3".

    Rate this question:

  • 27. 

    Assume the following method is properly synchronized and called from a thread A on an object B: wait(2000); After calling this method, when will the thread A become a candidate to get another turn at the CPU?

    • A.

      A.After object B is notified, or after two seconds

    • B.

      B.After the lock on B is released, or after two seconds

    • C.

      C.Two seconds after object B is notified

    • D.

      D.Two seconds after lock B is released

    Correct Answer
    A. A.After object B is notified, or after two seconds
    Explanation
    The correct answer is a. After object B is notified, or after two seconds.

    In this scenario, the wait(2000) method is called, which causes the thread A to wait for a maximum of 2000 milliseconds (2 seconds) or until it is notified by another thread. Once object B is notified, the thread A becomes a candidate to get another turn at the CPU. However, if the 2-second time limit is reached before the notification occurs, the thread A will also become a candidate to get another turn at the CPU.

    Rate this question:

  • 28. 

    Which are true? (Choose all that apply.)

    • A.

      A.The notifyAll() method must be called from a synchronized context

    • B.

      B.To call wait(), an object must own the lock on the thread

    • C.

      C.The notify() method is defined in class java.lang.Thread

    • D.

      When a thread is waiting as a result of wait(), it releases its d.lock

    • E.

      The notify() method causes a thread to immediately release its e.lock

    • F.

      The difference between notify() and notifyAll() is that notifyAll() notifies all f.waiting threads, regardless of the object they're waiting on

    Correct Answer
    A. A.The notifyAll() method must be called from a synchronized context
    Explanation
    The notifyAll() method must be called from a synchronized context because it is used to wake up all threads that are waiting on the same object's monitor. In order to access an object's monitor and call notifyAll(), the calling thread must first acquire the lock on that object by entering a synchronized block or method. This ensures that only one thread at a time can call notifyAll() and prevent any race conditions or conflicts between threads.

    Rate this question:

  • 29. 

    Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message: public class Logger { private StringBuilder contents = new StringBuilder(); public void log(String message) { contents.append(System.currentTimeMillis()); contents.append(": "); contents.append(Thread.currentThread().getName()); contents.append(message); contents.append("\n"); } public String getContents() { return contents.toString(); } } How can we ensure that instances of this class can be safely used by multiple threads?

    • A.

      A.This class is already thread-safe

    • B.

      Replacing StringBuilder with StringBuffer will make this class b.thread-safe

    • C.

      C.Synchronize the log() method only

    • D.

      D.Synchronize the getContents() method only

    • E.

      E.Synchronize both log() and getContents()

    • F.

      F.This class cannot be made thread-safe

    Correct Answer
    E. E.Synchronize both log() and getContents()
    Explanation
    In order to ensure that instances of this class can be safely used by multiple threads, both the log() and getContents() methods should be synchronized. Synchronizing the log() method will prevent multiple threads from accessing and modifying the contents StringBuilder object simultaneously, ensuring thread safety while writing messages. Synchronizing the getContents() method will prevent multiple threads from accessing the contents StringBuilder object while retrieving its contents, ensuring thread safety while reading the messages. By synchronizing both methods, we can ensure that the class can be safely used by multiple threads.

    Rate this question:

  • 30. 

    Public static synchronized void main(String[] args) throws InterruptedException { Thread t = new Thread(); t.start(); System.out.print("X"); t.wait(10000); System.out.print("Y"); } What is the result of this code?

    • A.

      A.It prints X and exits

    • B.

      B.It prints X and never exits

    • C.

      C.It prints XY and exits almost immeditately

    • D.

      D.It prints XY with a 10-second delay between X and Y

    • E.

      E.The code does not compile

    • F.

      F.An exception is thrown at runtime

    Correct Answer
    F. F.An exception is thrown at runtime
    Explanation
    The code will throw an exception at runtime because the wait() method can only be called on an object that is currently being synchronized, and in this case, the object being synchronized is the main thread. Since the main thread is not currently in a synchronized block, calling wait() on it will result in an IllegalMonitorStateException.

    Rate this question:

  • 31. 

    What is the output for the below code ? public class B extends Thread{ public static void main(String argv[]){ B b = new B(); b.run(); } public void start(){ for (int i = 0; i < 10; i++){ System.out.println("Value of i = " + i); } } }

    • A.

      A compile time error indicating that no run method is defined a.for the Thread class

    • B.

      A run time error indicating that no run method is defined for b.the Thread class

    • C.

      C.Clean compile and at run time the values 0 to 9 are printed out

    • D.

      D.Clean compile but no output at runtime

    Correct Answer
    D. D.Clean compile but no output at runtime
    Explanation
    Explanations : This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread.
    If the for loop were defined in a method called public void run() and the call in the main method had been to b.start() The list of values from 0 to 9
    would have been output.

    Rate this question:

  • 32. 

    What is the output for the below code ? public class Test extends Thread{ static String sName = "good"; public static void main(String argv[]){ Test t = new Test(); t.nameTest(sName); System.out.println(sName); } public void nameTest(String sName){ sName = sName + " idea "; start(); } public void run(){ for(int i=0;i < 4; i++){ sName = sName + " " + i; } } }

    • A.

      A.good

    • B.

      B.good idea

    • C.

      C.good idea good idea

    • D.

      D.good 0 good 0 1

    Correct Answer
    A. A.good
    Explanation
    Explanations : Change value in local methods wouldn’t change in global in case of String ( because String object is immutable).

    Rate this question:

  • 33. 

    What is the output for the below code ? public class Test{ public static void main(String argv[]){ Test1 pm1 = new Test1("One"); pm1.run(); Test1 pm2 = new Test1("Two"); pm2.run(); } } class Test1 extends Thread{ private String sTname=""; Test1(String s){ sTname = s; } public void run(){ for(int i =0; i < 2 ; i++){ try{ sleep(1000); }catch(InterruptedException e){} yield(); System.out.println(sTname); } } }

    • A.

      A.Compile error

    • B.

      B.One One Two Two

    • C.

      C.One Two One Two

    • D.

      D.One Two

    Correct Answer
    B. B.One One Two Two
    Explanation
    Explanations : If you call the run method directly it just acts as any other method and does not return to the calling code until it has finished. executing

    Rate this question:

  • 34. 

    What is the output for the below code ? class A implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName()); } } public class Test { public static void main(String... args) { A a = new A(); Thread t = new Thread(a); Thread t1 = new Thread(a); t.setName("t"); t1.setName("t1"); t.setPriority(10); t1.setPriority(-3); t.start(); t1.start(); } }

    • A.

      A.t t1

    • B.

      B.t1 t

    • C.

      C.t t

    • D.

      D.Compilation succeed but Runtime Exception

    Correct Answer
    D. D.Compilation succeed but Runtime Exception
    Explanation
    Thread priorities are set using a positive integer, usually between 1 and 10. t1.setPriority(-3); throws java.lang.IllegalArgumentException.

    Rate this question:

  • 35. 

    What is the output for the below code ? class A implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName()); } } 1. public class Test { 2. public static void main(String... args) { 3. A a = new A(); 4. Thread t = new Thread(a); 5. t.setName("good"); 6. t.start(); 7. } 8. }

    • A.

      A.good

    • B.

      B.null

    • C.

      C.Compilation fails with an error at line 5

    • D.

      D.Compilation succeed but Runtime Exception

    Correct Answer
    A. A.good
    Explanation
    Thread.currentThread().getName() return name of the current thread.

    Rate this question:

  • 36. 

    What is the default priority of a newly created thread?

    • A.

      A.MIN_PRIORITY (which is defined as 1 in the Thread class.)

    • B.

      B.NORM_PRIORITY (which is defined as 5 in the Thread class.)

    • C.

      C.MAX_PRIORITY (which is defined as 10 in the Thread class.)

    • D.

      D.A thread inherits the priority of its parent thread

    Correct Answer
    D. D.A thread inherits the priority of its parent thread
    Explanation
    When a new thread is created, it inherits the priority of its parent thread. This means that the new thread will have the same priority as the thread that created it. The priority of a thread determines the order in which threads are executed by the thread scheduler. Higher priority threads are given preference over lower priority threads, but the exact behavior depends on the underlying operating system.

    Rate this question:

  • 37. 

    What should be done to invoke the run() method on a thread for an object derived from the Thread class. Select the one correct answer,

    • A.

      A.The run() method should be directly invoked on the Object.

    • B.

      B.The start() method should be directly invoked on the Object.

    • C.

      C.The init() method should be directly invoked on the Object.

    • D.

      The creation of the object using the new operator would create a d.new thread and invoke its run() method.

    Correct Answer
    B. B.The start() method should be directly invoked on the Object.
    Explanation
    To invoke the run() method on a thread for an object derived from the Thread class, the start() method should be directly invoked on the Object. This is because the start() method is responsible for creating a new thread and then calling the run() method on that thread. If the run() method is directly invoked, it will run on the current thread instead of creating a new thread. Therefore, the correct way to invoke the run() method on a thread is by calling the start() method on the object.

    Rate this question:

  • 38. 

    Which of the following statements are true. Select the two correct answers.

    • A.

      The wait method defined in the Thread class, can be used to a.convert a thread from Running state to Waiting state

    • B.

      The wait(), notify(), and notifyAll() methods must be executed b.in synchronized code.

    • C.

      The notify() and notifyAll() methods can be used to signal and c.move waiting threads to ready-to-run state.

    • D.

      D.The Thread class is an abstract class.

    Correct Answer(s)
    B. The wait(), notify(), and notifyAll() methods must be executed b.in synchronized code.
    C. The notify() and notifyAll() methods can be used to signal and c.move waiting threads to ready-to-run state.
    Explanation
    The wait(), notify(), and notifyAll() methods must be executed in synchronized code because these methods are used for inter-thread communication and synchronization. By executing these methods in synchronized code, we ensure that only one thread at a time can access and modify the shared data, preventing any potential race conditions or inconsistencies. The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state, allowing them to continue their execution once the necessary conditions are met.

    Rate this question:

  • 39. 

    1. What methods are declared in java.lang.Thread class?

    • A.

      A.public static void sleep(long millis, int nanos)

    • B.

      B.public static native void sleep(long millis, int nanos)

    • C.

      C.public static native void sleep(long millis)

    • D.

      D.public static void sleep(long millis)

    Correct Answer(s)
    A. A.public static void sleep(long millis, int nanos)
    C. C.public static native void sleep(long millis)
    Explanation
    The correct answer includes two methods declared in the java.lang.Thread class. The first method is "public static void sleep(long millis, int nanos)" which allows the thread to sleep for the specified number of milliseconds and nanoseconds. The second method is "public static native void sleep(long millis)" which also allows the thread to sleep for the specified number of milliseconds.

    Rate this question:

  • 40. 

    Invoking yield() on a running thread cause following effect(s):

    • A.

      A.A running thread will be placed in suspended state.

    • B.

      B.A running thread will be placed in sleeping state.

    • C.

      C.A running thread will be placed in ready state.

    • D.

      D.Neither of the above.

    Correct Answer
    B. B.A running thread will be placed in sleeping state.
    Explanation
    When the yield() method is invoked on a running thread, it will be placed in a sleeping state. This means that the thread voluntarily gives up its current execution and allows other threads to run. The sleeping state is a state in which the thread is not actively executing, but it is still eligible to be scheduled and resume its execution later. This allows for fair scheduling of threads and can help prevent starvation.

    Rate this question:

Quiz Review Timeline +

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

  • Current Version
  • Mar 21, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Dec 21, 2011
    Quiz Created by
    Dhaya315
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.