Home » Java MCQ (Multiple Choice Questions)

Java MCQ (Multiple Choice Questions)

by Online Tutorials Library

Java Multiple Choice Questions

1) Which of the following option leads to the portability and security of Java?

  1. Bytecode is executed by JVM
  2. The applet makes the Java code secure and portable
  3. Use of exception handling
  4. Dynamic binding between objects

Answer: (a) Bytecode is executed by the JVM.

Explanation: The output of the Java compiler is bytecode, which leads to the security and portability of the Java code. It is a highly developed set of instructions that are designed to be executed by the Java runtime system known as Java Virtual Machine (JVM). The Java programs executed by the JVM that makes the code portable and secure. Because JVM prevents the code from generating its side effects. The Java code is portable, as the same byte code can run on any platform.

Hence, the correct answer is option (a).


2) Which of the following is not a Java features?

  1. Dynamic
  2. Architecture Neutral
  3. Use of pointers
  4. Object-oriented

Answer: (c) Use of pointers

Explanation: The Java language does not support pointers; some of the major reasons are listed below:

  • One of the major factors of not using pointers in Java is security concerns. Due to pointers, most of the users consider C-language very confusing and complex. This is the reason why Green Team (Java Team members) has not introduced pointers in Java.
  • Java provides an effective layer of abstraction to the developers by not using pointers in Java.

Java is dynamic, architecture-neutral, and object-oriented programming language.

Hence, the correct answer is option (c).


3) What should be the execution order, if a class has a method, static block, instance block, and constructor, as shown below?

  1. Instance block, method, static block, and constructor
  2. Method, constructor, instance block, and static block
  3. Static block, method, instance block, and constructor
  4. Static block, instance block, constructor, and method

Answer: (d) Static block, instance block, constructor, and method

Explanation: The order of execution is:

  1. The static block will execute whenever the class is loaded by JVM.
  2. Instance block will execute whenever an object is created, and they are invoked before the constructors. For example, if there are two objects, the instance block will execute two times for each object.
  3. The constructor will execute after the instance block, and it also execute every time the object is created.
  4. A method is always executed at the end.

Hence, the correct answer is an option (d).


4) What will be the output of the following program?

  1. 10, 5, 0, 20, 0
  2. 10, 30, 20
  3. 60, 5, 0, 20
  4. 60, 30, 0, 20, 0

Answer: (d) 60, 30, 0, 20, 0

Explanation: In the above code, there are two values of variable a, i.e., 10 and 60. Similarly, there are two values of variable b, i.e., 5 and 30. But in the output, the values of a and b are 60 and 30, respectively. It is because of the execution order of the program.

The execution order of the program is that the static block executes first, then instance block, and then constructor. Hence, the JVM will consider the value of a and b as 60 and 30 concerning the execution order. The value of a = 10 and b = 5 are of no use. And the value of variables c and m is 0 as we have not assigned any value to them.

Hence, the correct answer is an option (d).


5) The u0021 article referred to as a

  1. Unicode escape sequence
  2. Octal escape
  3. Hexadecimal
  4. Line feed

Answer: (a) Unicode escape sequence

Explanation: In Java, Unicode characters can be used in string literals, comments, and commands, and are expressed by Unicode Escape Sequences. A Unicode escape sequence is made up of the following articles:

  • A backslash ” (ASCII character 92)
  • A ‘u’ (ASCII 117)
  • One or more additional ‘u’ characters that are optional.
  • A four hexadecimal digits (a character from 0 – 9 or a-f or A-F)

Hence, the correct answer is the option (a).


6) _____ is used to find and fix bugs in the Java programs.

  1. JVM
  2. JRE
  3. JDK
  4. JDB

Answer: (d) JDB

Explanation: The Java Debugger (JDB or jdb) is a command-line java debugger that debugs the java class. It is a part of the Java Platform Debugger Architecture (JPDA) that helps in the inspections and debugging of a local or remote Java Virtual Machine (JVM).

The JVM (Java Virtual Machine) enables a computer to run Java or other language (kotlin, groovy, Scala, etc.) programs that are compiled to the Java bytecode. The JRE (Java Runtime Environment) is a part of JDK that contains the Java class libraries, Java class loader, and the Java Virtual Machine. The JDK (Java Development Kit) is a software development environment used to develop Java applications and applets.

Hence, the correct answer is an option (d).


7) Which of the following is a valid declaration of a char?

  1. char ch = ‘utea’;
  2. char ca = ‘tea’;
  3. char cr = u0223;
  4. char cc = ‘itea’;

Answer: (a) char ch = ‘utea’;

Explanation: A char literal may contain a Unicode character (UTF-16). We can directly use these characters only if our file system allows us, else use a Unicode escape (u) such as “u02tee”. The char literals are always declared in single quotes (‘).

The option b, c, and d, are not valid because:

  • In the option b), to make a String valid char literal, we should add prefix “u” in the string.
  • In the option c), single quotes are not present.
  • In the option d), “i” is used in place of “u.”

Hence, the correct answer is the option (a).


8) What is the return type of the hashCode() method in the Object class?

  1. Object
  2. int
  3. long
  4. void

Answer: (b) int

Explanation: In Java, the return type of hashCode() method is an integer, as it returns a hash code value for the object.

Hence, the correct answer is the option (b).


9) Which of the following is a valid long literal?

  1. ABH8097
  2. L990023
  3. 904423
  4. 0xnf029L

Answer: (d) 0xnf029L

Explanation: For every long literal to be recognized by Java, we need to add L character at the end of the expression. It can be either uppercase (L) or lowercase (l) character. However, it is recommended to use uppercase character instead of lowercase because the lowercase (l) character is hard to distinguish from the uppercase (i) character.

For example,

  1. Lowercase l: 0x466rffl
  2. Uppercase L: 0nhf450L

Hence, the correct answer is an option (d).


10) What does the expression float a = 35 / 0 return?

  1. 0
  2. Not a Number
  3. Infinity
  4. Run time exception

Answer: (c) Infinity

Explanation: In Java, whenever we divide any number (double, float, and long except integer) by zero, it results in infinity. According to the IEEE Standard for Floating-Point Arithmetic (IEEE 754), if we divide 1/0 will give positive infinity, -1/0 will give negative infinity, and 0/0 will give NaN. But on dividing an integer by zero, it throws a runtime exception, i.e., java.lang.ArithmeticException.

Hence, the correct answer is an option (c).


11) Evaluate the following Java expression, if x=3, y=5, and z=10:

++z + y – y + z + x++

  1. 24
  2. 23
  3. 20
  4. 25

Answer: (d) 25

Explanation: In the above expression, ++z means that the value will first increment by 1, i.e. 12. Now, evaluate the statement by putting the values of x, y, and z. On evaluating the expression, we get 25, as shown below.

++z +y -y +z + x++
11 + 5 – 5 + 11 + 3 = 25

Hence, the correct answer is option (d).


12) What will be the output of the following program?

  1. 15 times ***
  2. 15 times +++++
  3. 8 times *** and 7 times +++++
  4. Both will print only once

Answer: (c) 8 times *** and 7 times +++++

Explanation: In the above code, we have declared count = 1. The value of count will be increased till 14 because of the while (count<=15) statement. If the remainder is equal to 1 on dividing the count by 2, it will print (***) else print (+++++). Therefore, for all odd numbers till 15 (1, 3, 5, 7, 9, 11, 13, 15), it will print (***), and for all even numbers till 14 (2, 4, 6, 8, 10, 12, 14) it will print (+++++).

Hence, an asterisk (***) will be printed eight times, and plus (+++++) will be printed seven times.


13) Which of the following tool is used to generate API documentation in HTML format from doc comments in source code?

  1. javap tool
  2. javaw command
  3. Javadoc tool
  4. javah command

Answer: (c) Javadoc tool

Explanation: The Javadoc is a tool that is used to generate API documentation in HTML format from the Java source files. In other words, it is a program (tool) that reads a collection of source files into an internal form.

The Javadoc command line syntax is,
Javadoc [options] [packagenames] [sourcefiles] [@files]

The javap tool is used to get the information of any class or interface. It is also known as a disassembler. The javaw command is identical to java that displays a window with error information, and the javah command is used to generate native method functions.

Hence, the correct answer is option (c).


14) Which of the following creates a List of 3 visible items and multiple selections abled?

  1. new List(false, 3)
  2. new List(3, true)
  3. new List(true, 3)
  4. new List(3, false)

Answer: (b) new List(3, true)

Explanation: From the above statements, the new List(3, true) is the correct answer; this is because of the constructor type. To create a list of 3 visible items along with the multiple selections abled, we have to use the following constructor of the List class.

List (int rows, boolean multipleMode): It creates a new list initialized to display the described number of rows along with the multiple selection mode.

Therefore, in the statement new List (3, true), three (3) refers to the number of rows and true enables the multiple selections.

Hence, the correct answer is option (b).


15) Which of the following for loop declaration is not valid?

  1. for ( int i = 99; i >= 0; i / 9 )
  2. for ( int i = 7; i <= 77; i += 7 )
  3. for ( int i = 20; i >= 2; – -i )
  4. for ( int i = 2; i <= 20; i = 2* i )

Answer: (a) for ( int i = 99; i>=0; i / 9)

Explanation: The first option is not a valid declaration as i/9 is not declared correctly. The correct statement will be:
      for ( int i= 99; i>=0; i= i/9)

Then the code would execute. But without assigning the value of i/9 to a variable, it would not execute, and an exception is thrown, as shown below.

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      Syntax error on token “/”, invalid AssignmentOperator

The other three statements are valid and will execute. Hence, the correct answer is the option (a).


16) Which method of the Class.class is used to determine the name of a class represented by the class object as a String?

  1. getClass()
  2. intern()
  3. getName()
  4. toString()

Answer: (c) getName()

Explanation: The getName() method of the Class class returns the name (as String) of the entity (class, interface) represented by this Class object. It is a non-static method, and available in the java.lang package.

The getClass() method of the Object class returns the runtime class of this object. The intern() and toString() methods are of String class.

Hence, the correct answer is option (c).


17) In which process, a local variable has the same name as one of the instance variables?

  1. Serialization
  2. Variable Shadowing
  3. Abstraction
  4. Multi-threading

Answer: (b) Variable Shadowing

Explanation: There are following reasons for considering a variable shadowing, they are listed below:

  • When we define a variable in a local scope with a variable name same as the name of a variable defined in an instance scope.
  • When a subclass declares a variable with the same name as of the parent class variable.
  • When a method is overridden in the child class.

Hence, the correct answer is option (b).


18) Which of the following is true about the anonymous inner class?

  1. It has only methods
  2. Objects can’t be created
  3. It has a fixed class name
  4. It has no class name

Answer: (d) It has no class name

Explanation: Anonymous inner classes are the same as the local classes except that they don’t have any name. The main use of it is to override methods of classes or interfaces. And the rest three options are false about the anonymous inner classes as it can have both methods and objects. It does not have any fixed came name.

Hence, the correct answer is option(d).


19) Which package contains the Random class?

  1. java.util package
  2. java.lang package
  3. java.awt package
  4. java.io package

Answer: (a) java.util package

Explanation: The Random class is available in the java.util package. An object of the Random class is used to generate a series of pseudorandom numbers. And the object of this class is a thread-safe and cryptographically insecure object. The Random class provides a variety of methods that are used to create random numbers of type integers, float, long, double, etc.

Hence, the correct answer is option (a).


20) What do you mean by nameless objects?

  1. An object created by using the new keyword.
  2. An object of a superclass created in the subclass.
  3. An object without having any name but having a reference.
  4. An object that has no reference.

Answer: (d) An object that has no reference.

Explanation: The nameless objects are basically referred to as anonymous objects. The anonymous objects do not have any names. We can also say that, when an object is initialized but is not assigned to any reference variable, it is called an anonymous object. For example, new Employee();.

If we assign it to a reference variable like,

Employee emp = new Employee();

In the above code, emp is a reference variable. Therefore, the above object is not anonymous, as it is assigned to a reference variable.

Hence, the correct answer is option (d).


21) An interface with no fields or methods is known as a ______.

  1. Runnable Interface
  2. Marker Interface
  3. Abstract Interface
  4. CharSequence Interface

Answer: (b) Marker Interface

Explanation: An interface with no methods and fields is known as the marker interface. In other words, an empty interface (containing no fields and methods) is called a marker interface. In Java, the most commonly used marker interfaces are Serializable, Cloneable, Remote, and ThreadSafe interfaces. Marker interfaces are also known as the Tag interface. It is used to tell the JVM or compiler that the particular class has special behavior.

Following is the code snippet of a maker interface:

public interface Cloneable   {      // empty   }  

Hence, the correct answer is option (b).


22) Which of the following is an immediate subclass of the Panel class?

  1. Applet class
  2. Window class
  3. Frame class
  4. Dialog class

Answer: (a) Applet class

Explanation: According to the class hierarchy of Java Swing, the Applet class is the direct subclass of the Panel class. You can go through the link, (https://tutoraspire.com/java-swing) to deeply understand the class hierarchy diagram. The Panel class and Window class are the child classes of the Container class, and Frame and Dialog classes are the subclasses of the Window class.

Hence, the correct answer is option (a).


23) Which option is false about the final keyword?

  1. A final method cannot be overridden in its subclasses.
  2. A final class cannot be extended.
  3. A final class cannot extend other classes.
  4. A final method can be inherited.

Answer: (c) A final class cannot extend other classes.

Explanation: The final is a reserved keyword in Java that is used to make a variable, method, and class immutable. The important features of the final keyword are:

  • Using the final keyword with a variable makes it constant or immutable. We can’t reassign the values of it.
  • A final variable must be a local variable and cannot be used in other classes.
  • Using the final keyword with a method makes it constant, and we can’t override it in the subclass.
  • Using final with a class makes the class constant, and we cannot extend a final class. But a final class can extend other classes.

Hence, the correct answer is option (c).


24) Which of these classes are the direct subclasses of the Throwable class?

  1. RuntimeException and Error class
  2. Exception and VirtualMachineError class
  3. Error and Exception class
  4. IOException and VirtualMachineError class

Answer: (c) Error and Exception class

Explanation: According to the class hierarchy of Throwable class, the Error and Exception classes are the direct subclasses of the Throwable class, as shown below.

Java Multiple Choice Questions

The RuntimeException, IOException, and VirtualMachineError classes are the subclasses of the Exception and Error classes.

Hence, the correct answer is option (c).


25) What do you mean by chained exceptions in Java?

  1. Exceptions occurred by the VirtualMachineError
  2. An exception caused by other exceptions
  3. Exceptions occur in chains with discarding the debugging information
  4. None of the above

Answer: (b) An exception caused by other exceptions.

Explanation: In Java, an exception caused by other exceptions is known as a chained exception. Generally, the first exception causes the second exception. It helps in identifying the cause of the exception. In chained exceptions, the debugging information is not discarded.

Hence, the correct answer is option (b).


26) In which memory a String is stored, when we create a string using new operator?

  1. Stack
  2. String memory
  3. Heap memory
  4. Random storage space

Answer: (c) Heap memory

Explanation: When a String is created using a new operator, it always created in the heap memory. Whereas when we create a string using double quotes, it will check for the same value as of the string in the string constant pool. If it is found, returns a reference of it else create a new string in the string constant pool.

Hence, the correct answer is option (c).


27) What is the use of the intern() method?

  1. It returns the existing string from memory
  2. It creates a new string in the database
  3. It modifies the existing string in the database
  4. None of the above

Answer: (a) It returns the existing string from the memory

Explanation: The intern() method is used to return the existing strings from the database. In other words, the intern() method returns a reference of the string. For example, if the string constant pool already has a string object with the same value, the intern() method will return a reference of the string from the pool.

Hence, the correct answer is option (a).


28) Which of the following is a marker interface?

  1. Runnable interface
  2. Remote interface
  3. Readable interface
  4. Result interface

Answer: (b) Remote interface

Explanation: A marker interface is an interface with no fields and methods. In other words, an empty interface (contains nothing) is known as the marker interface. Examples of marker interfaces are Cloneable, Serializable, ThreadSafe, and Remote interface.

The Runnable, Readable, and Result interface are not marker interface as they contain some methods or fields.

Hence, the correct answer is option (b).


29) Which of the following is a reserved keyword in Java?

  1. object
  2. strictfp
  3. main
  4. system

Answer: (b) strictfp

Explanation: In the above options, strictfp is the only reserved keyword of Java. The strictfp keyword is a modifier that restricts the floating-point calculations to assure portability and it was added in Java version 1.2. The objects are referring to those variables that are created using the new operator. In Java, main is the method that is the entry point of any program, and the System is a class.

Hence, the correct answer is option (b).


30) Which keyword is used for accessing the features of a package?

  1. package
  2. import
  3. extends
  4. export

Answer: (b) import

Explanation: The import keyword is used to access the classes and interfaces of a particular package to the current file. In other words, it is used to import the user-defined and built-in classes and interfaces into the source file of java so that the current file can easily access the other packages by directly using its name. For example,

   import java.awt.*;      import java.lang.Object;  

The first import statement imports all the classes and interfaces of java.awt package. Whereas, the second import statement only imports the Object class of the java.lang package.

The package keyword is used to create a new package. The extends keyword indicates that the new class is derived from the base or parent class using inheritance, and export is not a keyword in Java.

Hence, the correct answer is option (b).


31) In java, jar stands for_____.

  1. Java Archive Runner
  2. Java Application Resource
  3. Java Application Runner
  4. None of the above

Answer: (d) None of the above

Explanation: A Java ARchive (JAR) is a package file format used to combine all the metadata and resources into a single file. In other words, it is a file that contains several components, which make up a self-contained, executable, and deployable jar used to execute Java applications and deploy Java applets.

Hence, the correct answer is option (d).


32) What will be the output of the following program?

  1. Complete
  2. Iomplede
  3. Cimpletd
  4. Coipletd

Answer: (c) Cimpletd

Explanation: In the above code snippet, we have passed a string with value “Complete” and set character “i” and “d” at the index position 1 and 7, respectively. According to the string “Complete,” “o” is at position 1, and “e” is at the position 7. The setChar() method is used to replace the original string values with the new one. Hence, the “o” and “e” are replaced by the characters “i” and “d,” respectively, which results in “Cimpletd.”

Hence, the correct answer is option (c).


33) Which of the following is false?

  1. The rt.jar stands for the runtime jar
  2. It is an optional jar file
  3. It contains all the compiled class files
  4. All the classes available in rt.jar is known to the JVM

Answer: (b) It is an optional jar file.

Explanation: The rt.jar stands for the runtime jar that comprises of all the compiled core class files for the Java Runtime Environment. It generally consists of classes like java.lang.String, java.lang.Object, java.io.Exception, etc., and all packages and classes available in the rt.jar are known to the JVM. The rt.jar is the mandatory jar file for every core java application as it contains all the core classes.

Hence, the correct answer is option (b).


34) What is the use of w in regex?

  1. Used for a whitespace character
  2. Used for a non-whitespace character
  3. Used for a word character
  4. Used for a non-word character

Answer: (c) Used for a word character

Explanation: In java, the “w” regex is used to match with a word character consists of [a-zA-Z_0-9]. For example, w+ matches one or more word character that is same as ([a-zA-Z_0-9] +).

The regex W, s, and S are used for a non-word character, a whitespace character, and a non-whitespace character, respectively. Hence, the w regex is used for a word character.

Hence, the correct answer is option (c).


35) Which of the given methods are of Object class?

  1. notify(), wait( long msecs ), and synchronized()
  2. wait( long msecs ), interrupt(), and notifyAll()
  3. notify(), notifyAll(), and wait()
  4. sleep( long msecs ), wait(), and notify()

Answer: (c) notify(), notifyAll(), and wait()

Explanation: The notify(), notifyAll(), and wait() are the methods of the Object class. The notify() method is used to raise a single thread that is waiting on the object’s monitor. The notifyAll() method is similar to the notify() method, except that it wakes up all the threads that are waiting on the object’s monitor. The wait() method is used to make a thread to wait until another thread invokes the notify() or notifyAll() methods for an object.

Hence, the correct answer is option (c).


36) Given that Student is a class, how many reference variables and objects are created by the following code?

  1. Three reference variables and two objects are created.
  2. Two reference variables and two objects are created.
  3. One reference variable and two objects are created.
  4. Three reference variables and three objects are created.

Answer: (a) Three reference variables and two objects are created.

Explanation: In the above code, there are three reference variables and two objects. The studentName, studentId, and stud_class are the three reference variables. The objects are those variables that are created using the new operator, i.e., studentName and stud_class. The studentId is only a reference variable as it is not declared using the new operator. Both studentName and stud_class are reference variables as well as objects.

Hence, there are three reference variables and two objects.

Hence, the correct answer is option (a).


37) Which of the following is a valid syntax to synchronize the HashMap?

  1. Map m = hashMap.synchronizeMap();
  2. HashMap map =hashMap.synchronizeMap();
  3. Map m1 = Collections.synchronizedMap(hashMap);
  4. Map m2 = Collection.synchronizeMap(hashMap);

Answer: (c) Map m1 = Collections.synchronizedMap(hashMap);

Explanation: By default, the HashMap class is a non-synchronized collection class. The need for synchronization is to perform thread-safe operations on the class. To synchronize the HashMap class explicitly, we should use the Collections.synchronizedMap(hashMap) method that returns a thread-safe map object.

Hence, the correct answer is option (c).


38) Given,

What is the initial quantity of the ArrayList list?

  1. 5
  2. 10
  3. 0
  4. 100

Answer: (b) 10

Explanation: The initial or default quantity of an ArrayList is 10. It means when we create an ArrayList without specifying any quantity, it will be created with the default capacity, i.e., 10. Hence, an ArrayList with the default capacity can hold ten (10) values.

Hence, the correct answer is option (b).


39) Which of the following is a mutable class in java?

  1. java.lang.String
  2. java.lang.Byte
  3. java.lang.Short
  4. java.lang.StringBuilder

Answer: (d) java.lang.StringBuilder

Explanation: A mutable class is a class in which changes can be made after its creation. We can modify the internal state and fields of a mutable class. The StringBuilder class is a mutable class, as it can be altered after it is created.

The String, Byte, and Short are immutable classes as they cannot be altered once they are created.

Hence, the correct answer is option (d).


40) What will be the output of the following program?

  1. No error
  2. Method is not defined properly
  3. Constructor is not defined properly
  4. Extra parentheses

Answer: (b) Method is not defined properly.

Explanation: Following are some rules for declaring an abstract method:

  • Abstract methods do not specify a method body, but they only have a method signature.
  • Abstract methods are always defined inside an abstract class.

In the above code, MyFirstClass is an abstract class. It contains an abstract method named num() that is not defined properly. According to the rules discussed above, an abstract method only has a method signature, not the method body.

Hence, the correct answer option (b).


41) What is meant by the classes and objects that dependents on each other?

  1. Tight Coupling
  2. Cohesion
  3. Loose Coupling
  4. None of the above

Answer: (a) Tight Coupling

Explanation: In tight coupling, a group of classes and objects are highly dependent on each other. Tight coupling is also used in some cases, like when an object creates some other objects that are going to be used by them.

Tight coupling is the correct answer as it is used when the logic of one class is called by the logic of another class.

Hence, the correct option is (a).


42) Given,

Find the value of value[i]?

  1. 10
  2. 11
  3. 15
  4. None of the above

Answer: (d) None of the above

Explanation: In the above code, we have not defined the variable Y. The code will not execute without any specific value for Y; it results in exception, as shown below.

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
        Y cannot be resolved to a variable

So, the values of i will not be printed, and the above exception is thrown.

Hence, the correct answer is (d).


43) Which of the following code segment would execute the stored procedure “getPassword()” located in a database server?

  1. CallableStatement cs = connection.prepareCall(“{call.getPassword()}”);
    cs.executeQuery();
  2. CallabledStatement callable = conn.prepareCall(“{call getPassword()}”);
    callable.executeUpdate();
  3. CallableStatement cab = con.prepareCall(“{call getPassword()}”);
    cab.executeQuery();
  4. Callablestatement cstate = connect.prepareCall(“{call getpassword()}”);
    cstate.executeQuery();

Answer: (c) CallableStatement cab = con.prepareCall(“{call getPassword()}”);
cab.executeQuery();

Explanation: In Java, java.sql.CallableStatement interface is used to call the SQL stored procedures in the database. The stored procedures are similar to functions as they perform some specific tasks, except that they are only available in the database. The CallableStatement can return either a single ResultSet object or multiple ResultSet objects.

Hence, the correct answer is option (c).


44) How many threads can be executed at a time?

  1. Only one thread
  2. Multiple threads
  3. Only main (main() method) thread
  4. Two threads

Answer: (b) Multiple threads

Explanation: In Java, multiple threads can be executed at the same time. A Java standalone application always starts with a single thread known as the main thread that is associated with the main() method.

In the operating system, only one thread is executed at a time.

Hence, the correct answer is option (b).


45) If three threads trying to share a single object at the same time, which condition will arise in this scenario?

  1. Time-Lapse
  2. Critical situation
  3. Race condition
  4. Recursion

Answer: (c) Race condition

Explanation: If two or more threads are trying to access a common resource at the same time. This situation is known as race condition. It generally occurs during the execution of multi-threaded application. It also refers to a programming bug or issue that occurs when the thread scheduler swaps the threads at any time between the process.

Hence, the correct answer is option (c).


46) If a thread goes to sleep

  1. It releases all the locks it has.
  2. It does not release any locks.
  3. It releases half of its locks.
  4. It releases all of its lock except one.

Answer: (b) It does not release any locks.

Explanation: The sleep() method does not release any locks of an object for a specific time or until an interrupt occurs. It leads to the poor performance or deadlock of threads. Whereas, the wait() method does not release the locks of an object.

Therefore, when a thread goes to sleep, it does not release any locks.

Hence, the correct answer is the option (b).


47) Which of the following modifiers can be used for a variable so that it can be accessed by any thread or a part of a program?

  1. global
  2. transient
  3. volatile
  4. default

Answer: (c) volatile

Explanation: In Java, we can modify the values of a variable with the help of a reserved keyword known as volatile. It is a different way of making a class thread-safe. Thread-safe means that the methods and objects of a class are accessible by multiple threads at the same time.

The volatile keyword is not a replacement of a synchronized block or method as it does not remove the need for synchronization among the atomic actions.

Global is not a reserved keyword in Java. The transient and default are keywords in Java, but they are not used for accessing a variable by a thread from any part of the program.

Hence, the correct answer is an option (c).


48) What is the result of the following program?

  1. It prints A and B with a 1000 seconds delay between them
  2. It only prints A and exits
  3. It only prints B and exits
  4. A will be printed, and then an exception is thrown.

Answer: (d) A will be printed, and then an exception is thrown.

Explanation: The InterruptedException is thrown when a thread is waiting, sleeping, or occupied. The output of the above code is shown below:

A  Exception in thread "main" java.lang.IllegalMonitorStateException  at java.lang.Object.wait(Native Method)  at com.app.java.B.main(B.java:9)  

In the above code, we have created a thread “f,” and when started, A will be printed. After that, the thread will wait for 1000 seconds. Now, an exception is thrown instead of printing B. It is because the wait() method must be used inside a synchronized block or try-catch block unless it will throw an exception, as shown above.

Hence, the correct option is option (d).


49) In character stream I/O, a single read/write operation performs _____.

  1. Two bytes read/write at a time.
  2. Eight bytes read/write at a time.
  3. One byte read/write at a time.
  4. Five bytes read/ write at a time.

Answer: (a) Two bytes read/write at a time.

Explanation: There are two types of I/O stream. One is a byte stream, and the other is the character stream. The Byte stream is used to perform input or output 8-bit (equals to 1 byte) Unicode bytes whereas, the Character stream is used to read or write a 16-bit (equals to 2 bytes) Unicode character.

Therefore, a single operation of character stream performs two bytes read/ write at a time.

Hence, the correct answer is option (a).


50) What is the default encoding for an OutputStreamWriter?

  1. UTF-8
  2. Default encoding of the host platform
  3. UTF-12
  4. None of the above

Answer: (b) Default encoding of the host platform

Explanation: The OutputStreamWriter class translates Unicode character into bytes by using the character encoding. The character encoding can be either a default encoding dependent on the system or encoding that is explicitly defined. If no external encoding is specified, it will use the default encoding of the host platform.

Hence, the correct answer is option (b).


Next TopicJava Tutorial

You may also like