Best Advanced Java Multiple Choice Questions (MCQ) for Testing Your Skills

Overview of Java Development

Java, initially developed by Sir James Gosling at Sun Microsystems, was born in early 1996 with its first major version released as Java 1 or JDK 1.0. Today, Java is a popular programming language with many major releases, including Java 8 or JDK 8.0 in 2014. Java is divided into two main parts: Core Java (J3SE) and Advanced Java (JEE).

Core Java (J3SE)

Core Java consists of all the fundamentals of the Java programming language, such as data types, functions, loops, and threads.

Advanced Java (JEE)

Advanced Java simplifies the complexity of building an n-tier application. JEE application server and containers provide Framework services. Some advantages of Advanced Java include the concept of client-server architecture, many Advanced Java frameworks such as Spring Hibernate states, and various web application servers such as Apache Tomcat and Glassfish.

Abstract Window Toolkit (AWT)

AWT stands for Abstract Window Toolkit, which is a collection of classes and interfaces that help to include various graphical components in the Java program. It provides a platform-independent and device-independent interface to develop graphic programs that run on all platforms, including Windows, Mac OS, and Unix.


Servlets in Java programs run on the Java-enabled web server or application server. They handle requests obtained from the web server, process the request, produce the response, and send the response back to the server. Servlets work on the server-side and are capable of handling complex requests obtained from a web server. They solve the problem due to the Common Gateway Interface implementation.

JavaServer Pages (JSP)

JSP is an extension to Servlet that provides more functionality than Servlet, such as Expression Language and JSTL. JSP pages consist of HTML tags and JSP tags providing more functionality and easier maintenance.

Model View and Controller (MVC)

MVC stands for Model View and Controller, which is a design pattern that separates the business logic presentation logic and data.

Advanced Java MCQs

Advanced Java MCQs can help you test and improve your knowledge of the various components of the Java programming language, including AWT, Servlets, JSP, and MVC.

JDBC Connection Pool Advantages

One advantage of using a JDBC connection pool is improved performance. This is because establishing a connection to a database is a time-consuming process, and a connection pool makes it possible to reuse existing connections instead of creating new ones for each user request. As a result, database access becomes faster and more efficient.


//Example code for using a JDBC connection pool
DataSource dataSource = new MysqlDataSource();

//Set the connection pool properties
PoolProperties p = new PoolProperties();

//Create the connection pool
org.apache.tomcat.jdbc.pool.DataSource pool = new org.apache.tomcat.jdbc.pool.DataSource();

//Use the connection pool to get a connection
Connection conn = pool.getConnection();

Identifying Date Information in Java

In Java programming language, there are several classes that can be used to handle date and time information. Among the options listed, the class that contains date information is java.sql.TimeStamp.

It is important to note that and classes do not contain date information.

Therefore, if you want to work with date information, you should opt for java.sql.TimeStamp.

//Example usage:

import java.sql.Timestamp;
import java.util.Date;

public class DateExamples {
   public static void main(String[] args) {
      //creating timestamp
      Timestamp timestamp = new Timestamp(new Date().getTime());

      //printing timestamp
      System.out.println("Timestamp: " + timestamp);

Identifying a Method in the JDBC Process

In the JDBC process, the correct method among the following options is:




method is used to add a set of SQL statements to a batch of commands that are executed together as a single unit. This helps to improve the performance of the application.

Java Software's Total JDBC Product Components

The total number of JDBC product components provided by Java software is 3.

// The three JDBC product components are as follows:
2. JDBC Driver Manager
3. JDBC Test Suite

How many JDBC drivers are available?

The total number of JDBC drivers available is 4.

// Code to retrieve the total number of JDBC drivers available
int totalDrivers = 4;

Updating BLOB, CLOB, Array, and REF Type Columns in JDBC

These types of columns can be updated in JDBC 3.0.


In JDBC, there are four types of driver available:
Type 1 driver is the JDBC-ODBC bridge driver
Type 2 driver is known as the Native-API/Partially Java driver
Type 3 driver is known as the Network-Protocol driver
Type 4 driver is known as the Pure Java Driver or Thin Driver
Among these four drivers, the type 4 driver is known as the thin driver in JDBC.

Type 1

is a bridge driver, which means that it connects JDBC to ODBC technology.

Type 2

is a native API driver. A partial Java driver that gets data access through the native libraries of the platform where the database is running.

Type 3

JDBC driver is a network-protocol driver. The application server converts JDBC calls into middleware-specific calls.

Type 4

is a pure Java driver. It is also known as a native-protocol driver. This JDBC driver is written entirely in Java and translates JDBC calls directly into the vendor-specific database protocol. It is called a thin driver because it does not require additional libraries or any middleware to communicate with the database.

Identifying Protocols

In computer networking, protocols are a set of rules that govern the communication between devices. TCP, FTP, SMTP, and Telnet are examples of protocols.

The correct answer is B: TCP, FTP, Telnet, SMTP are examples of protocols.

# Sample code to illustrate protocols
import socket

# Creating a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connecting the socket to a server
server_address = ('localhost', 80)

# Sending data to the server
message = 'Hello, server!'

# Receiving data from the server
data = sock.recv(1024)
print(f'Received from server: {data.decode()}')

# Closing the socket

Class for Connection-less Socket Programming

The classes used for connection-less socket programming in Java are DatagramPacket and DatagramSocket. Both of these classes are used in combination for sending and receiving datagram packets over a network.

DatagramPacket represents a packet of data to be sent or received, whereas DatagramSocket represents a socket for sending and receiving datagram packets. With these classes, it is possible to implement UDP (User Datagram Protocol) communication, which is a connection-less, unreliable protocol for sending and receiving data packets over a network.

To use these classes for connection-less socket programming, you need to:

  1. Create a DatagramPacket object to represent the data packet to be sent or received.
  2. Create a DatagramSocket object to represent the local socket for sending and receiving data packets.
  3. Send or receive the datagram packet using the DatagramSocket object.
  4. Close the DatagramSocket object when done.

Here is an example of how to send a datagram packet using DatagramPacket and DatagramSocket:

byte[] data = "Hello, world!".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), 1234);
DatagramSocket socket = new DatagramSocket();

And here is an example of how to receive a datagram packet using the same classes:

byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(1234);
String message = new String(packet.getData(), 0, packet.getLength());

Note that in the receiving example, we create a DatagramSocket object with a specified port number (1234 in this case) to receive datagram packets that are sent to that port. Also, we use the DatagramPacket object to receive the datagram packet into our buffer, and then convert the buffer to a string to print out the received message.

Number of TCP/IP Ports Reserved for Specific Protocol

The total number of TCP/IP ports reserved for specific protocol is 1024.

// No code required for this question

IP Address Bits

The total number of bits in a single IP address is 32.


# Assuming the IP address is represented in binary

ip_address = "11000000.10101000.00000001.00000001"
num_of_bits = len(ip_address.replace(".", ""))
print(f"The total number of bits in the IP address is {num_of_bits}") 

The Portability and Security of Java

The correct answer that leads to the portability and security of Java is:

C) Bytecode is executed by JVM.

Java is a platform-independent language. The code you write in Java is compiled into bytecode, which can be executed on any machine that has a JVM (Java Virtual Machine) installed. This makes Java code portable and can run on different operating systems.

JVM is responsible for translating the bytecode into machine-specific instructions and also provides security by enforcing a sandbox environment for each Java application running on it. This ensures that Java code cannot access the system resources of the host machine without permission, making Java a highly secure language.

Therefore, the bytecode being executed by JVM is the essential feature that ensures both portability and security in Java.

Major Components of JDBC

In JDBC, the major components are:

  1. DriverManager
  2. Driver
  3. Connection
  4. Statement
  5. ResultSet

So, option B is the correct answer.

Database Connection in Java

In Java, the Driver is responsible for getting a connection to the database. The driver is a class that implements the java.sql.Driver interface. The Driver interface is part of the JDBC API, which provides a standard interface for connecting to a database in Java.

To get a database connection in Java, you first need to load the driver class using the Class.forName() method. Then, you can use the DriverManager.getConnection() method to establish a connection to the database.

Here's an example code snippet to get a database connection using the MySQL driver:

String url = "jdbc:mysql://localhost/mydatabase";
Connection conn = DriverManager.getConnection(url, "username", "password");

In this example, we're loading the MySQL driver class, then specifying the URL of the database we want to connect to ("mydatabase" on the local machine), along with the username and password to use for the connection. The result of the getConnection() method is a Connection object, which we can use to execute SQL queries and other operations on the database.

Overall, getting a database connection in Java is a straightforward process, but it's important to ensure that you have the correct driver class and connection details for your specific database system.

Location of Database Table Configuration

The configuration file for database table is stored in the ".hbm" format.

This file contains the mapping between the database table and the corresponding Java class.

It specifies the properties of the table, such as column names, data types, primary keys, foreign keys, and other constraints. It helps to maintain consistency in the database schema and ensures data integrity.

Therefore, it is important to maintain this file systematically and keep it updated whenever there are changes in the database design.

Using Constructor for a Servlet

In a servlet, a constructor can be used for initialization purposes, just like in any other Java class. When a servlet container creates an instance of a servlet, it first calls the no-argument constructor, and then initializes the servlet by calling the init() method.

You can create a constructor for a servlet by defining a public no-argument constructor in the servlet class. For example:

public class MyServlet extends HttpServlet {
  public MyServlet() {
    // Initialization code goes here

  public void init() {
    // Setup code goes here

In this example, the MyServlet class has a public no-argument constructor that can be used for initialization, and an init() method that can be used for setup. When the servlet container creates an instance of MyServlet, it first calls the constructor and then the init() method.

Overall, using a constructor in a servlet is optional, but it can be useful if you need to initialize instance variables, set up a database connection, or perform any other kind of initialization before the servlet is used.

Method to Start a Server Thread

In Java, the `run()` method is used to define the code that will be executed by a thread. However, to start a server thread, we need to use the `start()` method.

Therefore, the correct option is `D) start()`.

The `start()` method performs the following tasks:

- Allocates memory for the thread. - Initializes the thread. - Calls the `run()` method of the thread.

So, when we call the `start()` method, it executes the code inside the `run()` method on a separate thread.


class MyThread extends Thread {
  public void run() {
    // code to be executed in this thread

// creating and starting a thread
MyThread myThread = new MyThread();

Method to Find URL from Cache in Httpd

In Httpd, the method used to find the URL from the cache is servefromcache(). This method is responsible for serving the content of a requested URL from the cache if it is present and valid. If the requested URL is not present in the cache or the cached content is expired, it will be fetched from the original source and added to the cache for future requests.

Other methods like getfromcache(), findfromcache(), and findcache() are not standard methods in Httpd and not used for finding URLs from the cache. It is important to use the correct method name to ensure proper functionality and avoid errors in your code.

Using the servefromcache() method can help improve the performance and speed of your web application by reducing the time taken to fetch content from the original source.

Instance Variable of Class httpd

In the class httpd, all of the following are instance variables:


Therefore, the correct answer is D) All of the above.

Method to Retrieve Host of a URL

In order to retrieve the host of a given URL, the correct method to be used is 'gethost()'.

Therefore, option B is the correct answer.

Communication between Applets and Servlets

There are multiple ways to communicate from an applet to a servlet:

  1. HTTP communication
  2. Socket communication
  3. RMI communication
  4. All of the above

The correct answer is D) All of the above can be used to communicate from an applet to a servlet.

// Example code for HTTP communication between an applet and servlet

// In the applet: URL url = new URL(getCodeBase(), "servletURL"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = in.readLine(); in.close();

// In the servlet: // Get data from the applet request String data = request.getParameter("data");

// Process data

// Send response back to the applet PrintWriter out = response.getWriter(); out.println("Response data"); out.close();

Executing Java Source Code in JSP using Scriptlet Tag

In JSP, scriptlet tags are used to embed java code within HTML content.

   // Java code goes here

To execute java source code in JSP, we use the scriptlet tag.

Identification of Date Information in Java

In Java, the


class contains date information.

Identifying Date Information from Java Classes

Out of the given java classes, only the class "java.sql.Timestamp" contains date information.

// Sample code to demonstrate the usage of Timestamp
import java.sql.Timestamp;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
      Date date= new Date();
      long time = date.getTime();
      Timestamp ts = new Timestamp(time);
      System.out.println("Current date and time: " + ts);

In the above code, we create a Timestamp object by converting a Date object into a long value, which represents the milliseconds since January 1, 1970, 00:00:00 GMT. The Timestamp object contains both the date and time information.

Total Ways for Exception Handling in JSP

The answer to this question is option A, which states that there are 2 ways to perform exception handling in JSP.

    <%@ page errorPage="error.jsp" %>
        int result = 0;
        try {
            result = 10/0;
        catch (Exception e) {

The above code block shows one of the ways to handle exceptions in JSP. The


directive is used to specify the JSP page that should be displayed when an exception occurs. The


block is used to catch the exception and redirect the user to the error page.

Another way to handle exceptions in JSP is by using


attribute of the


directive. This attribute is used to declare whether or not the current JSP page is capable of handling exceptions.

    <%@ page language="java" isErrorPage="true" %>
    <%@ page import="java.sql.*" %>
    <%  try {
            // Code that may throw an exception
        } catch(SQLException e) {
        // Code to handle the exception
        } %>

The above code block shows another way to handle exceptions in JSP. Here, the


attribute is set to


, which tells the container that the current JSP page is capable of handling exceptions. The


block is used to catch any SQL exceptions that may occur within the page.

JSP Page Tags

In JSP pages, we can use both HTML and JSP tags. HTML tags are used to design web pages and JSP tags are used to insert dynamic content. By including JSP tags in an HTML page, we can create dynamic web pages that can display different content for each request.

Java Database Connectivity (JDBC)

In Java programming, JDBC stands for Java Database Connectivity, which is a standard API (Application Programming Interface) that enables Java programs to access databases, such as MySQL, Oracle, MS SQL Server, and PostgreSQL. The correct answer to the given question is: option C) Java Database Connectivity.

Resource Comparison: Process vs Thread

In computing, both processes and threads are used to execute code concurrently. A process is an independent unit of execution, while a thread is a subset of a process. Threads require fewer resources than processes. One process can have multiple threads. Threads share the same memory space, open files, and system resources. Because of this, threads are faster to create and terminate than processes, and they use less memory. This results in smoother and more efficient execution of code.

//Example of creating a new thread in Java
Thread thread = new Thread(new Runnable() {
    public void run() {
        //code to be executed
thread.start(); //start the thread execution

What Determines Thread Priority?

The priority of a thread is determined by the thread scheduler, which is responsible for managing and coordinating the execution of multiple threads within a process. The scheduler assigns each thread a priority level based on various factors such as the thread's importance, the amount of resources it requires, and its urgency.

It's important to note that the priority of a thread does not override the priority of the parent process. The scheduler takes both the process and thread priorities into account when making scheduling decisions.

Overall, the thread scheduler plays a critical role in determining the execution order of threads in a multithreaded application, and can greatly impact the performance and responsiveness of the system.

// Example code showcasing the use of thread priorities

Types of Multitasking

There are two types of multitasking: Thread-based and Process-based.


Thread-based multitasking is where individual threads are created in a single process to perform multiple tasks simultaneously. Each thread works independently and shares the parent process's resources. This type of multitasking is more efficient and cost-effective than process-based multitasking.


Process-based multitasking is where multiple processes are created to perform multiple tasks simultaneously. Each process acts independently and has its memory space, which is isolated from other processes. This type of multitasking requires more overhead as each process requires its resources to operate.

Therefore, the correct option is (C) Both A and B are types of multitasking.

Responsibilities of RMI Server

The RMI server is responsible for:

  1. Exporting remote objects
  2. Creating an instance of the remote object
  3. Binding an instance of the remote object to the RMI registry

Therefore, the correct answer is option D) as the RMI service is responsible for all of the given options.

// No code to show as this is a theoretical question

RMI Meaning

RMI stands for Remote Method Invocation.

// No code to optimize in this case

Act like API.

Technology built on top of socket programming

RMI (Remote Method Invocation) is a technology built on top of socket programming. It allows a Java program to invoke a method in a remote object located on another Java Virtual Machine (JVM).

Identification of Connectionless Service

Out of the given options, UDP follows the connectionless service.

    // UDP Example in Python

    import socket

    # creating a socket object
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # get local machine name
    host = socket.gethostname()

    port = 9999

    # bind the socket to a public host, and a well-known port
    s.bind((host, port))

    print("Waiting for client request...")

    # Receive data from the client and send the response
    while True:

        data, addr = s.recvfrom(1024)

        response = "Received Message: " + data.decode()

        s.sendto(response.encode(), addr)

Protocols used for splitting and sending packets across a network

There are several protocols used for splitting and sending packets across a network, but among them, the most commonly used protocol is TCP/IP.

// TCP/IP Example
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

TCP (Transmission Control Protocol) breaks data into packets, reassembles them at the destination, and guarantees data delivery. IP (Internet Protocol) is responsible for routing packets between different networks.

Other protocols like SMTP (Simple Mail Transfer Protocol), UDP (User Datagram Protocol), and FTP (File Transfer Protocol) have their own specific uses.

Total Number of ResultSets Available with JDBC 2.0 Core API

The JDBC 2.0 core API provides three ResultSets in total.

// Code example
// resultSet1, resultSet2, resultSet3 are the three ResultSets provided by JDBC 2.0 core API
ResultSet resultSet1 = statement.executeQuery(sqlQuery1);
ResultSet resultSet2 = statement.executeQuery(sqlQuery2);
ResultSet resultSet3 = statement.executeQuery(sqlQuery3); Method in Java

The statement "The method is used to move the next row of the ResultSet, making the current row" is true.

    ResultSet resultSet = statement.executeQuery(query);
        //iterate through rows of ResultSet

Here, we can see that the


method is used to move to the next row of the ResultSet in each iteration of the while loop.

JDBC: Java Database Connectivity

JDBC is a Java API that provides a standard interface for communicating with relational databases.

// Example code for connecting to a database using JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
  public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/mydb";
    String user = "username";
    String password = "password";
    try {
      // Connect to the database
      Connection conn = DriverManager.getConnection(url, user, password);
      System.out.println("Connected to the database!");
    } catch (SQLException e) {
      System.err.println("Failed to connect to the database.");

The above code demonstrates how to connect to a MySQL database using JDBC.

In summary, the given statement is true.

Java Servlet API Packages Containing Interfaces and Classes:

In Java Servlet API, both javax.servlet.http and javax.servlet contain packages that represent interfaces and classes. Therefore, the correct answer is C) Both A and B.

javax.servlet.http // contains interfaces and classes for HTTP servlets
javax.servlet // contains interfaces and classes for servlets and the servlet container

Non-Idempotent HTTP Request Methods

Both POST and GET methods are non-idempotent. When a non-idempotent request is made to a server, the state of the server or the resource being requested can change with each request.

// Example of a POST request in JavaScript using fetch API

fetch('', {
  method: 'POST',
  body: JSON.stringify({
    username: 'JohnDoe',
    password: 'password123'
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Application Servers

Out of the given options, JBoss is an example of an application server.


Number of Techniques in Session Tracking

There are a total of four techniques used in session tracking.

The correct answer is B) 4.

Microsoft Solution for Dynamic Web Content

The Microsoft solution for providing dynamic web content is ASP, which stands for Active Server Pages. It is a server-side scripting technology that enables developers to create dynamic and interactive web pages with ease. ASP allows you to combine HTML, scripts, and server-side components to build web applications that can access databases, manipulate data, and respond to user input. With ASP, you can create powerful web applications that are both efficient and scalable.

Difference between Servlet and JSP

Servlets and JSPs are both Java technologies used for web development. The main difference between servlets and JSPs lies in their syntax:

  • Servlets use Java code inside an HTML file
  • JSPs use HTML inside a Java file

Servlets and JSPs are both compiled by the Java compiler:

  • Servlets are compiled into Java byte code
  • JSPs are compiled into servlets

Therefore, both servlets and JSPs need a Java compiler installed on the web server.

Not a Directive

Out of the following, which one is not a directive?


The answer is Export since it is not a directive.

True or False: JDBC API for Accessing Data Source from Java Middle Tier

The statement is true.


Configuring ViewResolver for Facelet Views

In order to resolve Facelet views in a Java web application, the


needs to be configured. This class is responsible for finding the appropriate view template to render for a given request. It can be configured via XML or Java annotations, depending on the web framework being used.

It's important to note that the class name is case-sensitive, and should be written as


(with no underscores or hyphens).

Once the


is properly configured, it will be able to locate the necessary Facelet views for rendering in the web application.

Method that Returns a Proxy Object

In the given methods,


returns a proxy object.

//Example code for load() method
public class MyClass {
  private HeavyObject heavyObj;

  public HeavyObject load() {
    if (heavyObj == null) {
      heavyObj = new HeavyObjectProxy();
    return heavyObj;

In the above example code, the


method returns a new instance of


class which is a proxy object.

Java Bean Class Attribute

The correct answer is B) class which is used to specify the class name of a Java Bean.

To define a Java Bean in XML configuration file, we use


tag. One of the most important attribute of this tag is the Class attribute. It is used to define the fully qualified class name of the bean being defined.

Here's an example:

<bean id="studentBean" class="com.example.model.Student"/>

Understanding Web Servers and Servlet Init() Method

The web server is responsible for loading the `init()` method of a servlet. Therefore, the statement "The web server is used for loading the init() method of the servlet" is True.

The `init()` method is called by the container when the servlet is first initialized, and it is used for any one-time setup required by the servlet. The `init()` method can be overridden by the servlet to extend or customize its functionality.

In summary, web servers facilitate the loading of the `init()` method in servlets.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.