Java Mcq

Java Multiple Choice Questions

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

  • Bytecode is executed by JVM
  • The applet makes the Java code secure and portable
  • Use of exception handling
  • Dynamic binding between objects

The Java compiler generates bytecode as its output, ensuring the security and portability of Java code. Bytecode comprises a sophisticated series of instructions intended for execution by the Java Virtual Machine (JVM), the Java runtime system. When JVM executes Java programs, it enhances their portability and security by preventing code from causing side effects. This portability is achieved as the identical bytecode can run on various platforms.

Hence, the correct answer is option (a).

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

  • Dynamic
  • Architecture Neutral
  • Use of pointers
  • Object-oriented

Java language does not include support for pointers for various significant reasons as outlined:

  • Security concerns are a primary factor in the exclusion of pointers in Java. The complexity and confusion often associated with C-language usage of pointers have been a decisive reason for the Green Team (Java Team members) to opt out of incorporating pointers in Java.
  • By abstaining from the use of pointers, Java offers developers a robust layer of abstraction for more effective programming.

Java is a versatile programming language that is known for its dynamism, architecture neutrality, and object-oriented approach.

Hence, the correct answer is option (c).

3) In the scenario where a class contains a method, static block, instance block, and constructor, the order of execution should follow the sequence listed below:

Example

public class First_C {

      public void myMethod() 

	{

	System.out.println("Method");

	}

	

	{

	System.out.println(" Instance Block");

	}

		

	public void First_C()

	{

	System.out.println("Constructor ");

	}

	static {

		System.out.println("static block");

	}

	public static void main(String[] args) {

	First_C c = new First_C();

	c.First_C();

	c.myMethod();

  }

}
  • Instance block, method, static block, and constructor
  • Method, constructor, instance block, and static block
  • Static block, method, instance block, and constructor
  • Static block, instance block, constructor, and method

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

Explanation: The order of execution is:

  • The static block will execute whenever the class is loaded by JVM.
  • 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.
  • The constructor will execute after the instance block, and it also execute every time the object is created.
  • A method is always executed at the end.

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

4) What is the expected output of the program provided below?

Example

public class MyFirst {

      public static void main(String[] args) {

         MyFirst obj = new MyFirst(n);

 }

 static int a = 10;

 static int n;

 int b = 5;

 int c;

 public MyFirst(int m) {

       System.out.println(a + ", " + b + ", " + c + ", " + n + ", " + m);

   }

// Instance Block

  {

     b = 30;

     n = 20;

  } 

// Static Block

  static 

{

          a = 60;

     } 

 }
  • 10, 5, 0, 20, 0
  • 10, 30, 20
  • 60, 5, 0, 20
  • 60, 30, 0, 20, 0

In the provided code snippet, the variable a holds two values: 10 and 60, while the variable b contains 5 and 30. However, the output displays the values of a and b as 60 and 30, respectively. This outcome is a result of the program's execution sequence.

The program follows a specific order of execution where the static block is executed initially, followed by the instance block, and finally, the constructor. Consequently, based on this sequence, the JVM will recognize the values of a and b as 60 and 30. The initial values of a = 10 and b = 5 do not impact the final outcome. Variables c and m remain at a value of 0 since they have not been assigned any specific values.

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

5) The \u0021 article referred to as a

  • Unicode escape sequence
  • Octal escape
  • Hexadecimal
  • Line feed

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.

The Java Debugger, also known as JDB or jdb, is a Java debugger tool that operates through the command line to debug Java classes. It is an integral component of the Java Platform Debugger Architecture (JPDA) designed to facilitate the examination and debugging of a Java Virtual Machine (JVM) either locally or remotely.

The Java Virtual Machine (JVM) facilitates the execution of programs written in Java or other languages (such as Kotlin, Groovy, Scala, etc.) that have been compiled into Java bytecode. Within the Java Development Kit (JDK), the Java Runtime Environment (JRE) encompasses the Java class libraries, Java class loader, and the Java Virtual Machine. Developers utilize the JDK as a software development platform for creating Java applications and applets.

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

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

  • char ch = '\utea';
  • char ca = 'tea';
  • char cr = \u0223;
  • char cc = '\itea';

Char literals are capable of accommodating a Unicode character, specifically in UTF-16 format. Should our file system permit, these characters can be utilized directly; otherwise, resort to employing a Unicode escape (\u) like "\u02tee". It is essential to note that char literals are consistently defined within single quotation marks (').

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?

  • Object
  • long
  • void

The return type of the hashCode method in Java is an integer. This method is used to generate a hash code value for an object.

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

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

  • ABH8097
  • L990023
  • 904423
  • 0xnf029L

In Java, to ensure that long literals are identified correctly, it is essential to append the expression with the character 'L'. This character can be in uppercase (L) or lowercase (l). Nevertheless, it is advisable to opt for the uppercase character to avoid confusion with the lowercase (l) that closely resembles the uppercase (I) character.

As an illustration:

  • Using lowercase letter L: 0x466rffl
  • Using uppercase letter L: 0nhf450L

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

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

  • Not a Number
  • Infinity
  • Run time exception

When working with Java, dividing a number by zero (except for integers) results in infinity for double, float, and long data types. The IEEE Standard for Floating-Point Arithmetic (IEEE 754) specifies that dividing 1 by 0 yields positive infinity, -1 by 0 yields negative infinity, and 0 by 0 yields NaN. However, dividing an integer by zero in Java throws a runtime exception specifically java.lang.ArithmeticException.

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

11) Assess the Java expression below when x equals 3, y equals 5, and z equals 10:

++z + y - y + z + x++

In the provided expression, the operator ++z indicates that the value will be incremented by 1 first, resulting in 12. Subsequently, the statement is assessed by substituting the values of x, y, and z. Upon evaluation, the expression yields 25, as demonstrated.

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

Hence, the correct answer is option (d).

12) What output will the program below produce?

Example

public class Test {

public static void main(String[] args) {

	int count = 1;

	while (count <= 15) {

	System.out.println(count % 2 == 1 ? "***" : "+++++");

	++count;

		}      // end while

	}       // end main 

 }
  • 15 times ***
  • 15 times +++++
  • 8 times *** and 7 times +++++
  • Both will print only once

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?

  • javap tool
  • javaw command
  • Javadoc tool
  • javah command

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?

  • new List(false, 3)
  • new List(3, true)
  • new List(true, 3)
  • new List(3, false)

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?

  • for ( int i = 99; i >= 0; i / 9 )
  • for ( int i = 7; i <= 77; i += 7 )
  • for ( int i = 20; i >= 2; - -i )
  • for ( int i = 2; i <= 20; i = 2* i )

In this scenario, the initial option is invalid due to the incorrect declaration of i/9. A proper declaration should be specified as follows: for (int i = 99; i >= 0; i = i / 9)

Subsequently, the code would run successfully. However, if the value of i/9 is not assigned to a variable, the code will not execute, and an exception will be thrown, as demonstrated below.

An error has occurred in the "main" thread of the Java program. The error is a java.lang.Error indicating an unresolved compilation issue. The specific problem is a syntax error related to the use of the "/" character as an invalid AssignmentOperator.

The remaining three statements are considered valid and will be executed successfully. Therefore, the accurate choice is 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?

  • getClass
  • intern
  • getName
  • toString

The method getName from the Class class retrieves the name of the entity, such as a class or interface, represented by the specific Class object. This method is not static and can be accessed within the java.lang package.

The getClass function in the Object class retrieves the actual class of the current object during runtime. Meanwhile, the String class contains the intern and toString functions.

Hence, the correct answer is option (c).

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

  • Serialization
  • Variable Shadowing
  • Abstraction
  • Multi-threading

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?

  • It has only methods
  • Objects can't be created
  • It has a fixed class name
  • It has no class name

In essence, anonymous inner classes are akin to local classes, but they lack a specific name. They are primarily utilized for method overriding in classes or interfaces. The remaining three statements regarding anonymous inner classes are inaccurate, as they are capable of containing both methods and objects and do not possess a predetermined name.

Hence, the correct answer is option(d).

19) Which package contains the Random class?

  • java.util package
  • java.lang package
  • java.awt package
  • java.io package

The Random class can be found in the java.util package. Instances of the Random class are employed to produce a sequence of pseudorandom numbers. It's important to note that objects of this class are both thread-safe and not suitable for cryptographic purposes. Various methods within the Random class enable the generation of random numbers in different data types such as integers, floats, longs, doubles, and more.

Hence, the correct answer is option (a).

20) What do you mean by nameless objects?

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

Definition: Objects without explicit names are commonly known as anonymous objects. These objects are nameless and are created without being assigned to any specific variable. An example of an anonymous object is when an object is initialized without being associated with a reference variable, such as new Employee;.

If we assign it to a reference variable like,

Employee emp = new Employee;

In the provided code snippet, the variable emp serves as a reference. Consequently, the object mentioned is not considered anonymous since 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 ______.

  • Runnable Interface
  • Marker Interface
  • Abstract Interface
  • CharSequence Interface

A label interface, also referred to as a marker interface, is an interface that does not include any methods or fields. In Java, some frequently utilized marker interfaces are Serializable, Cloneable, Remote, and ThreadSafe. These interfaces, which contain no methods or fields, are used as markers to indicate special characteristics of classes to the JVM or compiler. Marker interfaces are alternatively called Tag interfaces.

Presented below is a code snippet showcasing a maker interface:

Example

public interface Cloneable 

{

    // empty 

}

Hence, the correct answer is option (b).

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

  • Applet class
  • Window class
  • Frame class
  • Dialog class

In the Java Swing class hierarchy, the Applet class is positioned as a direct subclass of the Panel class. For a more comprehensive view of this class hierarchy diagram, you can refer to the following link: java-swing. Additionally, the Panel class and Window class are descended from the Container class, while the Frame and Dialog classes are further subclasses of the Window class.

Hence, the correct answer is option (a).

23) Which option is false about the final keyword?

  • A final method cannot be overridden in its subclasses.
  • A final class cannot be extended.
  • A final class cannot extend other classes.
  • A final method can be inherited.

Solution: (c) In Java, it is not permissible for a final class to be extended by 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?

  • RuntimeException and Error class
  • Exception and VirtualMachineError class
  • Error and Exception class
  • IOException and VirtualMachineError class

The Error and Exception classes are immediate subclasses of the Throwable class, following the class hierarchy of the Throwable class.

The Exception and Error classes are parent classes for the RuntimeException, IOException, and VirtualMachineError classes.

Hence, the correct answer is option (c).

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

  • Exceptions occurred by the VirtualMachineError
  • An exception caused by other exceptions
  • Exceptions occur in chains with discarding the debugging information
  • None of the above

Solution: (b) An exception that arises due to the presence of other exceptions.

In Java programming, a chained exception refers to an exception that is triggered by another exception. Typically, the initial exception leads to the occurrence of a subsequent exception. This chaining mechanism aids in pinpointing the root cause of the exceptional situation. By utilizing chained exceptions, valuable debugging details are retained and not lost in the process.

Hence, the correct answer is option (b).

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

  • Stack
  • String memory
  • Heap memory
  • Random storage space

When a String is generated with the new operator, it is always stored in the heap memory. Conversely, when a string is formed using double quotes, the program verifies if a string with the same value exists in the string constant pool. If a match is located, a reference to it is returned; otherwise, a new string is generated in the string constant pool.

Hence, the correct answer is option (c).

27) What is the use of the intern method?

  • It returns the existing string from memory
  • It creates a new string in the database
  • It modifies the existing string in the database
  • None of the above

Solution: (a) The function retrieves the current string stored in memory.

The intern function is employed to retrieve strings that already exist in the database. Essentially, intern provides a reference to the string. When a string object with an identical value already exists in the string constant pool, intern will return a reference to that string from the pool.

Hence, the correct answer is option (a).

28) Which of the following is a marker interface?

  • Runnable interface
  • Remote interface
  • Readable interface
  • Result interface

A marker interface is an interface that does not contain any fields or methods. It is essentially an empty interface and is referred to as a marker interface. Some instances of marker interfaces include Cloneable, Serializable, ThreadSafe, and Remote interface.

The interfaces Runnable, Readable, and Result are not considered marker interfaces because they include methods or fields within their definitions.

Hence, the correct answer is option (b).

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

  • object
  • strictfp
  • main
  • system

In the provided choices, "strictfp" stands out as the singular reserved keyword in Java. It serves as a modifier that confines floating-point computations to ensure consistency across different platforms and was introduced in Java 1.2. The term "objects" pertains to variables generated using the new operator. Within Java, "main" represents the pivotal method serving as the starting point of every program, with "System" denoting a class.

Hence, the correct answer is option (b).

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

  • package
  • import
  • extends
  • export

The import keyword in Java is utilized to bring in classes and interfaces from a specific package into the current file. This action allows the source file to conveniently access both user-defined and built-in classes and interfaces by directly referencing their names. For instance,

Example

import java.awt.*; 

   import java.lang.Object;

The initial import statement brings in all the classes and interfaces from the java.awt package, while the subsequent import statement solely brings in the Object class from the java.lang package.

The package keyword is employed to establish a fresh package in Java. By using the extends keyword, it signifies that the newly created class inherits from the base or parent class through inheritance. It's essential to note that export is not recognized as a keyword within the Java programming language.

Hence, the correct answer is option (b).

31) In java, jar stands for_____.

  • Java Archive Runner
  • Java Application Resource
  • Java Application Runner
  • None of the above

A Java ARchive (JAR) is a specialized file format utilized for consolidating metadata and resources into a singular package file. Essentially, it serves as a container that houses multiple elements, creating a self-sustained, operational JAR capable of running Java applications and deploying Java applets.

Hence, the correct answer is option (d).

32) What is the expected output of the program below?

Example

public class Test2 {

	public static void main(String[] args) {

		StringBuffer s1 = new StringBuffer("Complete");

		s1.setCharAt(1,'i');

		s1.setCharAt(7,'d');

		System.out.println(s1);

	 }

 }
  • Complete
  • Iomplede
  • Cimpletd
  • Coipletd

In the code excerpt provided above, a string with the content "Complete" is manipulated by assigning the characters "i" and "d" to positions 1 and 7. In the original string "Complete," "o" is located at index 1, and "e" is found at index 7. The function setChar is employed to substitute the existing characters with new ones. Consequently, the characters "o" and "e" are substituted with "i" and "d," correspondingly, leading to the altered string "Cimpletd."

Hence, the correct answer is option (c).

33) Which of the following is false?

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

The abbreviation rt.jar refers to the runtime jar, which includes all the compiled essential class files necessary for the Java Runtime Environment. It includes classes such as java.lang.String, java.lang.Object, java.io.Exception, among others. All packages and classes within rt.jar are recognized by the JVM. Every fundamental Java application requires the rt.jar file as it encompasses all core classes essential for operation.

Hence, the correct answer is option (b).

34) What is the use of \w in regex?

  • Used for a whitespace character
  • Used for a non-whitespace character
  • Used for a word character
  • Used for a non-word character

In Java, the regular expression "\w" is employed to identify a word character, which includes the characters [a-zA-Z0-9]. For instance, when using "\w+", it matches a sequence of one or more word characters, which is equivalent to ([a-zA-Z0-9]+).

The regular expressions \W, \s, and \S are employed to represent a non-alphanumeric character, a blank space character, and a non-blank space character, respectively. Consequently, the regex \w is utilized to match a word character.

Hence, the correct answer is option (c).

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

  • notify, wait( long msecs ), and synchronized
  • wait( long msecs ), interrupt, and notifyAll
  • notify, notifyAll, and wait
  • sleep( long msecs ), wait, and notify

The methods notify, notifyAll, and wait belong to the Object class in Java. The notify function is employed to awaken a single thread that is in a waiting state on the object's monitor. In contrast, notifyAll is akin to notify, but it rouses all threads that are waiting on the object's monitor simultaneously. On the other hand, wait is utilized to pause a thread until another thread triggers either the notify or notifyAll methods for a specific object.

Hence, the correct answer is option (c).

In the scenario where "Student" is defined as a class, the code will result in the creation of reference variables and objects.

Example

Student studentName, studentId;

studentName = new Student();

Student stud_class = new Student();
  • Three reference variables and two objects are created.
  • Two reference variables and two objects are created.
  • One reference variable and two objects are created.
  • Three reference variables and three objects are created.

Solution:

(a) The code snippet initializes three reference variables and instantiates two objects in memory.

In the provided code snippet, there are three reference variables and two objects. The reference variables include studentName, studentId, and studclass. Objects are instances created using the new operator, like studentName and studclass. Unlike studentName and studclass, studentId is solely a reference variable since it was not instantiated using the new operator. Both studentName and studclass serve as both reference variables and objects in this context.

Therefore, there exist three reference variables and a pair of objects.

Hence, the correct answer is option (a).

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

  • Map m = hashMap.synchronizeMap;
  • HashMap map =hashMap.synchronizeMap;
  • Map m1 = Collections.synchronizedMap(hashMap);
  • Map m2 = Collection.synchronizeMap(hashMap);

Solution: Use the Collections utility class to create a synchronized map from an existing HashMap. This is achieved by calling the synchronizedMap method and passing the original HashMap as an argument, which will return a synchronized map stored in the variable m1.

The HashMap class is inherently non-synchronized. Synchronization is necessary for ensuring thread safety when working with the class. To explicitly synchronize the HashMap class, the Collections.synchronizedMap(hashMap) method should be employed, which provides a thread-safe map object as a result.

Hence, the correct answer is option (c).

38) Given,

Example

ArrayList list = new ArrayList();

What is the starting size of the ArrayList named list?

When an ArrayList is created without specifying a capacity, it automatically sets the initial quantity to 10 by default. This implies that the ArrayList will have a capacity of 10 to store values. Therefore, an ArrayList with the default capacity can accommodate ten (10) values.

Hence, the correct answer is option (b).

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

  • java.lang.String
  • java.lang.Byte
  • java.lang.Short
  • java.lang.StringBuilder

A mutable class allows modifications to be made after it has been instantiated. It permits adjustments to its internal state and fields. An example of a mutable class is the StringBuilder class, which supports alterations post-creation.

Instances of the classes String, Byte, and Short are considered immutable because they cannot be modified after their creation.

Hence, the correct answer is option (d).

What is the expected output of the program presented below?

Example

abstract class MyFirstClass

{

     abstract num (int a, int b) {  }

}
  • No error
  • Method is not defined properly
  • Constructor is not defined properly
  • Extra parentheses

Abstract methods are declared without a method body, containing only a method signature. These methods are exclusively found within abstract classes.

Within the provided code snippet, the class MyFirstClass is defined as an abstract class. This class includes a method called num, which is an abstract method lacking a proper implementation. As per the aforementioned guidelines, an abstract method solely consists of a method signature without any method body.

Hence, the correct answer option (b).

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

  • Tight Coupling
  • Cohesion
  • Loose Coupling
  • None of the above

In the concept of tight coupling, there is a strong interdependence among a collection of classes and objects. This form of coupling is applicable in scenarios where an object is responsible for creating other objects that it will subsequently utilize.

The concept of tight coupling is applicable when the functionality of one class is invoked by another class.

Hence, the correct option is (a).

42) Given,

Example

int values[ ] = {1,2,3,4,5,6,7,8,9,10};

for(int i=0;i< Y; ++i)

System.out.println(values[i]);

Determine the value stored in value[i].

  • Not any of the options mentioned above

In the code provided, the variable Y has not been declared. The code cannot run successfully without assigning a value to Y, which leads to an exception being thrown, as demonstrated in the following example.

An error occurred in the "main" thread of the Java program. The error is a java.lang.Error caused by an unresolved compilation issue where the variable Y is not recognized.

Consequently, the values stored in variable i will not be displayed, resulting in the exception being 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?

  • CallableStatement cs = connection.prepareCall("{call.getPassword}"); cs.executeQuery;
  • CallabledStatement callable = conn.prepareCall("{call getPassword}"); callable.executeUpdate;
  • CallableStatement cab = con.prepareCall("{call getPassword}"); cab.executeQuery;
  • Callablestatement cstate = connect.prepareCall("{call getpassword}"); cstate.executeQuery;

Solution: In this code snippet, a CallableStatement object named cab is created by invoking the prepareCall method on the Connection con. The prepareCall method takes a SQL query "{call getPassword}" as its argument. Subsequently, the executeQuery method is called on the cab object to execute the stored procedure defined by the SQL query.

The java.sql.CallableStatement interface in Java is utilized for invoking SQL stored procedures in a database. These stored procedures, akin to functions, execute specific tasks but are exclusive to the database environment. A CallableStatement is capable of returning either a solitary ResultSet object or multiple ResultSet objects.

Hence, the correct answer is option (c).

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

  • Only one thread
  • Multiple threads
  • Only main (main method) thread
  • Two threads

In Java, it is possible to run multiple threads concurrently. Every Java standalone program initiates with a primary thread, called the main thread, linked to the main function.

Within the operating system, only a single thread is processed at any given moment.

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?

  • Time-Lapse
  • Critical situation
  • Race condition
  • Recursion

When multiple threads attempt to access a shared resource simultaneously, it leads to a scenario known as a race condition. This phenomenon typically arises when running a multi-threaded program and can be attributed to a programming error or glitch caused by the thread scheduler switching between threads during execution.

Hence, the correct answer is option (c).

46) If a thread goes to sleep

  • It releases all the locks it has.
  • It does not release any locks.
  • It releases half of its locks.
  • It releases all of its lock except one.

The sleep function does not relinquish any object locks for a set duration or until an interruption takes place. This behavior can result in decreased thread performance or potential deadlock situations. In contrast, the wait function also maintains the locks of an object without releasing them.

Hence, when a thread enters a sleeping state, it retains all locks it holds without releasing them.

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?

  • global
  • transient
  • volatile
  • default

In Java, the ability to alter the values of a variable is facilitated by the utilization of a special keyword called volatile. This serves as an alternative method to ensure the thread safety of a class. Thread safety refers to the condition where the methods and properties of a class can be utilized concurrently by multiple threads.

The volatile keyword does not serve as a substitute for a synchronized block or method since it does not eliminate the necessity for synchronization between atomic actions.

In Java, it's important to note that "global" is not a keyword reserved by the language. On the other hand, "transient" and "default" are keywords in Java, however, they do not serve the purpose of enabling access to a variable by a thread from any section of the program.

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

48) What is the result of the following program?

Example

public static synchronized void main(String[] args) throws

InterruptedException {

     Thread f = new Thread();

      f.start();

      System.out.print("A");

      f.wait(1000);

      System.out.print("B");

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

Solution: The output of the given code snippet will be the letter 'A' printed to the console, followed by the occurrence of an exception being thrown.

The InterruptedException is raised when a thread is in a waiting, sleeping, or blocked state. The following code produces the output displayed below:

Example

A

Exception in thread "main" java.lang.IllegalMonitorStateException

	at java.lang.Object.wait(Native Method)

	at com.app.java.B.main(B.java:9)

Within the provided code snippet, a thread named "f" has been instantiated. Upon initiation, it will display A. Subsequently, the thread will pause for 1000 milliseconds. However, an error occurs instead of displaying B. This issue arises because the wait function necessitates being enclosed within a synchronized or try-catch block; otherwise, it triggers an exception, as evidenced in the aforementioned code.

Hence, the correct option is option (d).

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

  • Two bytes read/write at a time.
  • Eight bytes read/write at a time.
  • One byte read/write at a time.
  • Five bytes read/ write at a time.

In the realm of I/O streams, two distinct types exist: byte streams and character streams. Byte streams are utilized for handling the input and output of 8-bit Unicode bytes, equivalent to one byte. On the other hand, character streams are employed for the manipulation of 16-bit Unicode characters, which amount to two bytes.

Consequently, each operation of the character stream involves reading or writing two bytes simultaneously.

Hence, the correct answer is option (a).

50) What is the default encoding for an OutputStreamWriter?

  • UTF-8
  • Default encoding of the host platform
  • UTF-12
  • None of the above

The OutputStreamWriter class converts Unicode characters into bytes through character encoding. The character encoding could be the system's default encoding or a specifically defined encoding. In the absence of a specified external encoding, the default encoding of the host platform will be utilized.

Hence, the correct answer is option (b).

Java MCQ

  1. Which of the following statements about Java threads is correct?
  • A thread can be created by extending the Thread class or implementing the Runnable interface.
  • Java does not support multithreading.
  • Every Java program runs as a single thread by default.
  • Threads in Java can only be synchronized manually using locks.

Explanation: In Java, threads can be created either by extending the Thread class or by implementing the Runnable interface. This flexibility allows developers to define the behavior of a thread either by subclassing Thread or by separating the thread's behavior from the object's behavior using Runnable.

  1. What is the purpose of the transient keyword in Java?
  • It is used to declare a method that cannot be overridden.
  • It indicates that a variable should not be serialized.
  • It specifies that a class cannot be subclassed.
  • It is used to define a variable that cannot be modified.

Explanation: In Java, the transient keyword is used to indicate that a variable should not be serialized when the object containing that variable is serialized. This is useful for variables that contain sensitive data or transient state that should not persist during serialization and deserialization processes.

  1. Which of the following is true about the compareTo method of the Comparable interface?
  • It returns true if two objects are equal in value.
  • It is used to compare the memory addresses of two objects.
  • It returns an integer value indicating the comparison result between two objects.
  • It can only be used to compare numeric data types.

Explanation: The compareTo method in Java is defined in the Comparable interface and is used to compare the current object with another object of the same type. It returns an integer value:

  • Negative value, if the current object is less than the other object.
  • Zero, if both objects are equal.
  • Positive value, if the current object is greater than the other object.
  • This method enables natural ordering of objects and is commonly used in sorting algorithms like Collections.sort.
  1. Which of the following statements regarding Java generics is correct?
  • Generics in Java allow classes to have static methods.
  • Generics provide compile-time type safety and prevent type casting issues.
  • Generics are only applicable to collections and not to other types of objects.
  • Generics are implemented using the generic keyword in method signatures.

Explanation: Java generics allow classes and methods to be parameterized by type. They provide compile-time type safety by enabling developers to specify the type of objects that can be stored in collections or used with classes and methods. This prevents runtime type errors and eliminates the need for explicit type casting in many cases, enhancing code clarity and reliability.

  1. What is the purpose of the volatile keyword in Java?
  • It ensures that a variable cannot be changed after initialization.
  • It prevents a method from being overridden in subclasses.
  • It specifies that a variable's value may be modified by multiple threads.
  • It indicates that a method should be executed in a single thread.

In Java programming, the volatile keyword is employed to designate variables that could be altered by numerous threads concurrently. This keyword guarantees that the value of the variable is consistently retrieved from the primary memory and not from the local cache of the thread. By doing so, it helps to avert problems related to visibility and synchronization in environments where multiple threads are operating simultaneously.

Input Required

This code uses input(). Please provide values below: