0% found this document useful (0 votes)
175 views35 pages

Pra MCQ

The document contains multiple-choice questions (MCQs) related to Java programming, JDBC, SQL, and JSP. Each question is followed by the correct answer, providing insights into exception handling, database connectivity, and various programming concepts. The content serves as a study guide for individuals preparing for exams or interviews in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views35 pages

Pra MCQ

The document contains multiple-choice questions (MCQs) related to Java programming, JDBC, SQL, and JSP. Each question is followed by the correct answer, providing insights into exception handling, database connectivity, and various programming concepts. The content serves as a study guide for individuals preparing for exams or interviews in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 35

PRA MCQ

Which method is used to obtain the textual description of an exception in Java?


getMessage()
printStackTrace()
toString()
getDescription()

-> getMessage()

What is output of this code ?


public class DemoClass {
static void test() throws RuntimeException {
throw new ArithmeticException();
}

public static void main(String args[]) {


try {
test();
} catch (RuntimeException re) {
System.out.println("Exception Handled");
}
}
}

RuntimeException
CompilationError
ExceptionHandled
None of the above

-> Exception Handled

class MethodOverloading{
void display(int a,float b) { // Method 1
System.out.println("Method 1");
System.out.println(a+b);
}
void display(int a,int b) { // Method 2
System.out.println("Method 2");
System.out.println(a+b);
}
void display(int a,long b) { // Method 3
System.out.println("Method 3");
System.out.println(a+b);
}
void display(int a,double b) {
System.out.println("Method 4");
System.out.println(a+b); // Method 4
}
}
public class DemoClass{
public static void main(String[] args) {
MethodOverloading mo=new MethodOverloading();
mo.display(10, 10.5); // Statement 1
}
}
Method 1
Method 2
Method 3
Method 4

-> Method 4

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Lion extends Animal {


void makeSound() {
System.out.println("Lion roars");
}
}

class Dog extends Animal {


void makeSound() {

System.out.println("Dog Barks");
}
}

public class DemoClass {


public static void main(String[] args) {
Animal animal1 = new Lion();
Animal animal2 = new Dog();
animal1.makeSound();
animal2.makeSound();
}
}

Lion roars
Dog Barks

Dog Barks
Lion roars

Animal makes a sound


Lion roars
Dog Barks

Lion roars
Dog Barks
Animal makes a sound

->
Lion roars
Dog Barks

class DemoClass {
public static void main(String[] args) {
Stack<Integer> stk = new Stack<>();
stk.push(1000);
stk.pop();
stk.push(2000);
stk.push(3000);
stk.pop();
stk.push(4000);
System.out.println(stk.size());
}
}

2
3
5
4

-> 2

Sameer is trying to execute following code . what will be the output after
execution ?
public class DemoClass {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Chennai");
list.add("Mumbai");
list.add("Kolkata");
list.add("Bangalore");
int a = (int) list.get(0);
System.out.println(list);
}
}

ArrayIndexOutOfBoundException
ClassCastException
InputMismatchException
[Chennai, Mumbai, Kolkata, Bangalore]

->ClassCastException

public class LinkedListCollection {


public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("Google");
ll.add("TCS");
ll.add("Meta");
ll.add("Microsoft");
LinkedList<String> ll2 = new LinkedList<String>();
ll2.add("Twitter");
ll2.add("Tencent");
ll2.addAll(ll);
System.out.println(ll2);
}
}

[Google, TCS, Meta, Microsoft, Twitter, Tencent]


[Twitter, Tencent, Google, TCS, Meta, Microsoft]
[Google, Meta, Microsoft, TCS, Tencent, Twitter]
[Twitter, Tencent, TCS, Microsoft, Meta, Google]
-> [Twitter, Tencent, Google, TCS, Meta, Microsoft]

The most common exceptions are NullPointerException,


ArrayIndexOutOfBoundsException, ClassCastException, InvalidArgumentException

Which of the following is a runtime exception on java ?

NullPointerException
FileNotFoundException
ClassNotFoundException
IOException

->NullPointerException

Which method is used to retrieve the auto-generated keys after executing an INSERT
statement in JDBC ?
executeUpdate()
executeQuery()
getGeneratedKeys()
getResultSet()

->getGeneratedKeys()

Which JDBC interface is used to execute a parameterized SQL query to retrieve data
from a database?

Statement
ResultSet
PreparedStatement
CallableStatement

->PreparedStatement

Which of these obtains a Connection?


Connection.getConnection(url)
Driver.getConnection(url)
DriverManager.getConnection(url)
new Connection(url)

->Driver.getConnection(url)

Jay is trying to connect with database. help jay by selecting correct method to
connect with Database ?
connect( )
openConnection( )
getConnection( )
createConnection( )

->getConnection()

What is the purpose of the 'ResultSet' interface in JDBC ?


It represents a precompile SQL statement
It provides method for executing SQL queries
It handles database operations
It respresents the resultset of database Query
->It respresents the resultset of database Query

Rahul is trying to end the database connection. help rahul to end the database
connection by using proper method?
shutdown()
close()
endconnection()
disconnect(

-> close()

Ram is learning about a JDBC. help ram to understand the Steps


of connecting with Database by choosing correct option

->
1. Register the driver class
2. Creating connection
3. Creating statements
4. Executing queries
5. Closing connection

in JDBC which exception is thrown when there is an error in database


connectivity such as a failed connection or authentication ?
SQLException
DatabaseException
ConnectionException
ConnectivityException

->SQLException

Hritik is trying to establish the connection with the Apche derby database.
Help Hritik to choose correct code snippet

Class.forName("org.mysql.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("jdbc:derby:C:\\User\\MyDB;create=true");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("jdbc:derby:C:\\User\\MyDB;create=true");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("derby:C:\\User\\MyDB;create=true");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("jdbc:C:\\User\\MyDB;create=true");

->
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("jdbc:derby:C:\\User\\MyDB;create=true");

Which of the following statements about the PreparedStatement interface in JDBC is


True ?
It is used for executing parameterised SQL Query
it is used for executing stored procedure
it is used to execute batch updates
it is an alternative for Statement interface

-> It is used for executing parameterised SQL Query

Which of the following is true about HTTP Get method?


The GET method sends the encoded user information appended to the page request.
The GET method is the defualt method to pass information from browser to web
server.
Both the above
None of the above

-> Both the above

Which of the following code is used to get a HTTP Session object in servlets?

request.getSession()
response.getSession();
new Session()
None of the above

->request.getSession()

Which statement about jspInit() is true?


It does not have access to ServletConfig.
It does not have access to ServletContext.
It is called only once.
It cannot be overridden.

->It is called only once.

What will be the output for the following code?


<html><body>
<% int i = 20 ;%>
<% while(i>=15) { %>
out.print(i);
<% } %>
2.02E+11
20
15
None of the above

-> None of the above

Which of the following code is used to get an attribute in a HTTP Session object in
servlets?
session.getAttribute(String name)
session.alterAttribute(String name)
session.updateAttribute(String name)
session.setAttribute(String name)

->session.getAttribute(String name)

Which of the following is stored at client side?

URL rewriting
Hidden form fields
SSL sessions
Cookies

-> Cookies

What temporarily redirects response to the browser?

<jsp:forward>
<%@directive%>
response.sendRedirect(URL)
response.setRedirect(URL)

-> response.sendRedirect(URL)

Which of the following is not a directive in JSP?


page directive
include directive
taglib directive
command directive

-> command directive

“request” is instance of which one of the following classes?


Request
HttpRequest
HttpServletRequest
ServletRequest

-> HttpServletRequest

The doGet() method in the example extracts values of the parameter’s type and
number by using __________
request.getParameter()
request.setParameter()
response.getParameter()
response.getAttribute()

-> request.getParameter()

The value of Primary key


can be duplicated
can be null
cannot be null
None of these

->cannot be null

To remove a relation from an SQL database, we use the ______command

Delete
Purge
Remove
Drop table

->Drop table

which of the following is the query to get Orderdetails whose OrderPrice is


1500,2500 ?
OId OrderDate OrderPrice

SELECT * FROM Orders WHERE OrderPrice=1500 or OrderPrice=2500;


SELECT * FROM Orders WHERE OrderPrice BETWEEN(1500,2500);
SELECT * FROM Orders WHERE OrderPrice=1500 and OrderPrice=2500;
SELECT * FROM Orders WHERE OrderPrice IN(1500,2500);

-> SELECT * FROM Orders WHERE OrderPrice IN(1500,2500);

Which is NOT an aggregate function in SQL?


LENGTH()
Count()
SUM()
MIN()

-> LENGTH()

With SQL, how do you select all the records from a table named "Toddler" where the
value of the column "Name" starts with "A"?
SELECT * FROM Toddler WHERE Name LIKE '%A'
SELECT * FROM Toddler WHERE Name='A'
SELECT * FROM Toddler WHERE Name LIKE 'A%'
SELECT * FROM Toddler WHERE Name='%A%'

-> SELECT * FROM Toddler WHERE Name Like 'A%';

Select the correct SQL query syntax to add a column to a table ?


ALTER TABLE table_name
ADD COLUMN column_name datatype;
ALTER table_name
ADD column_name datatype;
ALTER TABLE table_name
ADD column_name datatype;
ALTER table_name
ADD COLUMN column_name datatype;

-> ALTER TABLE table_name


Add column_name data_type

Write a sql query to update the designation as 'ITA' when location is null?

update Employee set designation='ITA'


update Employee set designation ='ITA' where location is null
update Employee modify designation='ITA' where location=null
None of these

-> update Employee SET designation='ITA' where location is null;

Inserting any value in the wrong index as shown below will result in
int A[]=new int[3];
A[5]=5;

NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
Program executes successfully

-> ArrayIndexOutOfBoundsException

To use a package , keyword used is


package
packagename
import
None of the options
-> import

public class Test {


public static void main(String[] args){
String str[] = {"Array","is","easy to learn"};
System.out.println(str[2]);
}
}
What is the output of the above code?

is
easy
error
easy to learn

->easy to learn

public class Test {


public static void main(String[] args)
{
String str = "Welcome to TCS";
System.out.println(str.contains("Welcome"));
}
}
What is the output of the above code?

TRUE
FALSE

-> TRUE

class Demo {
public static void main(String[] args)
{
Short a=365;
System.out.println(a++);
}}
What is the output of the above code?

366
TRUE
365
error

->365

A JSP is transformed into a(n)

Java servlet
Java applet
Both A and B
None of the above

-> Java servlet


What is the output of the following Code Snipper ?
out.println("Hi Welcome to Validate Servlet");
RequestDispatcher rd = req.getRequestDispatcher("Welcome.html");
rd. Forward(req, resp);
"Hi Welcome to Validate Servlet"
Contents of Welcome.html
"Hi Welcome to Validate Servlet"
Contents of Welcome.html
None of the above

-> None of the above

What should be present in blank for the below SQL statement ?


PreparedStatement ps = con.prepareStatement("select * from student");
ResultSet rs = ps.execute____();

query
update
statement
None of the above

->query

“out” is implicit object of which class?

javax.servlet.jsp.PrintWriter
javax.servlet.jsp.SessionWriter
javax.servlet.jsp.SessionPrinter
javax.servlet.jsp.JspWriter

-> javax.servlet.jsp.PrintWriter

Which of the following method exposes the Data in the URL ?


doGet
doPost
doDisplay
None of the above

-> doGet

Which is mandatory in <jsp:useBean /> tag ?


id, class
id, type
type, property
type,id

-> id,class

How to create a cookie in servlet?

Use new operator.


Use request.getCookie() method
Use response.getCookie() method
None of the above

-> Use new operator.

When service method of servlet gets called?


The service method is called when the servlet is first created
The service method is called whenever the servlet is invoked
Both of the above.
None of the above

->The service method is called whenever the servlet is invoked

Which of the following is true about init method of servlet?


the init method simply creates or loads some data that will be used throughout the
life of the servlet
The init method is not called again and again for each user request
Both of the above.
None of the above

->Both of the above

What is the ouput of the following code snippet?


public class Demo {
public static void main(String[] args) {
try {
int x=10/0;
System.out.println("Success");
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
}
}

Arithmetic Exception

Success
Arithmetic Exception

Arithmetic Exception
Success

Arithmetic Exception : Division by zero

->Arithmetic Exception

what will be the ouput of following coding snippet ?


public class Demo {
public static void main(String args[]) {
ArrayList<String> list=new ArrayList<String>();
list.add("India");
list.add("USA");
list.add("Japan");
list.add("China");
list.add(2,"Germany");
System.out.println(list);
}
}

[India, Germany, USA, Japan, China]


[India, USA, Japan, China, Germany]
[Germany, India, USA, Japan, China]
[India, USA, Germany, Japan, China]

->[India, USA, Germany, Japan, China]

Which of the following is the correct order of blocks when using exception Handling
in java ?

catch -> try ->finally


finally -> catch -> try
try -> catch -> finally
finally -> try -> catch

->try -> catch -> finally

Dominik is implementing a resource cleanup opeartion and want to


ensure that the cleanup code is executed regardless of wheqather there
is exception or not . what type of exception handling mechnism dominik should use ?
try-catch'Block
throws' Clause
catch-throw' Block
finally' Block

->finally' Block

Anil is confused on which method he should use to establish connection


with database . help anil to choose the correct method ?

ResultSet.next()
Statement.executeQuery()
Connection.prepareStatement()
DriverManager.getConnection()

-> DriverManager.getConnection()

which of the following is a superclass of all exception classes ?


RuntimeException
Exception
Throwable
Error

-> Throwable

java.lang.Object
└── java.lang.Throwable <-- (Superclass of all exceptions)
├── java.lang.Exception <-- (For checked and unchecked exceptions)
│ ├── java.io.IOException
│ ├── java.sql.SQLException
│ ├── java.lang.RuntimeException <-- (Superclass of unchecked exceptions)
│ ├── java.lang.ArithmeticException
│ ├── java.lang.NullPointerException
│ ├── java.lang.ArrayIndexOutOfBoundsException
└── java.lang.Error <-- (For serious system-level errors)
├── java.lang.OutOfMemoryError
├── java.lang.StackOverflowError

Which exception will the following throw?


Public class Test {

public static void main(String[] args) {


Object obj = new Integer(3);
String str = (String) obj;
System.out.println(str);
}
}

ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
NumberFormatException

-> ClassCastException

what is the purpose of throws keyword in java method declaration ?


It indicates that the method may throw certain types of exceptions
It is used to handle Exceptions within method
It is used to specify custom exception class
It is used to Explicitly catch expressions with the method

->It indicates that the method may throw certain types of exceptions

Which among them is/are the following ways to declare 1-d/2-d arrays in Java?
(1)int[][] arr={{1,2,3},{11,12,13},{21,22,23}};
(2)int b[][]={{1,2,3},{11,12,13},{21,22,23}};
(3)int ar[]={1,2,3};
(4)int[] br={11,22,33};

(1),(2),(3),(4)
(1) and (4) only
(2) and (4) only
(2) and (3) only

->(1),(2),(3),(4)

Jane wants to create a list if Student name that allows duplicate entries and the
insertion order .
which java collection should she use ?
HashSet
LinkedHashSet
ArrayList
LinkedList

-> ArrayList
What is the type of inheritance demonstrated below?
public class Vehicles {
......
}
public class Cars extends Vehicles {
......
}
public class Trucks extends Vehicles {
......
}
public class Bus extends Vehicles {
......
}

Single
Multiple
Multilevel
Hierarchical

-> Hierarchical

In the statement : import java.util.Scanner; what does Scanner represent?


package
class
library
interface

-> class

Consider that we have declared a priority queue of type String-queue that contains
the following elements that are added to the queue in the following
order: Amrita,Vijay,Jaikar,Raj.Assuming the code is syntactically correct,What will
be ouput if the following statement?
System.out.println(queue.element());

Amrita

Raj

Amrita
Raj
Jaikar
Vijay

-> Amrita

Consider we have created an ArrayList of type String . The following elements are
added to the list in the following order-Ravi,Vijay,Chavi,Ajay,Mani.Assuming
the code is syntactically correct,What will be the output if the following code ?
import java.util.*;
............
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
..........

Ravi
Mani
Vijay
Chavi

Ajay
Ravi
Vijay
Mani

Chavi
Ajay
Ravi
Vijay

Chavi
Mani
Ajay
Ravi

Vijay
Chavi
Ajay
Mani

->
Vijay
Chavi
Ajay
Mani

Consider we have created a List of integers which consists of number 1,2,3 which
are added to the list in the same order.Assuming the code is written
syntactically correct,What is the output of the following code?
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);

Removed Element: 1
Removed Element: 3
Removed Element: 2
Error is displayed

-> Removed Element: 2

Predict the output : class Vehicle {


void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car started");
}
}
class Bike extends Vehicle {
void start() {
System.out.println("Bike started");
}
}
public class Test {
public static void main(String[] args) {
Vehicle v;
v = new Car();
v.start();
v = new Bike();
v.start();
}
}

Vehicle started Vehicle started

Car started
Bike started

Bike started
Car started

Compilation error

->
Car started
Bike started

What will be the expected output of the following snippet : Set<String> set = new
TreeSet<>();
set.add("banana");
set.add("apple");
set.add("mango");
System.out.println(set);

[banana, apple, mango]


[apple, banana, mango]
[mango, banana, apple]
[apple, mango, banana]

->[apple, banana, mango]

public class Demo {


public static void main(String[] args) {
int[] arr = new int[5];
try {
arr[10] = 10;
arr[4]=11;
System.out.println("Value inserted successfully!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} finally {
System.out.println(arr[4]);
System.out.println("Finally block executed.");
}
}
}
What will be the output of the above code ?

Array index out of bounds: 10


Finally block executed.

Array index out of bounds: Index 10 out of bounds for length 5


11
Finally block executed.

Array index out of bounds: Index 10 out of bounds for length 5


0
Finally block executed

Array index out of bounds: No message


Finally block executed.

->
Array index out of bounds: Index 10 out of bounds for length 5
0
Finally block executed

What will be the output for following code Snippet ?


public class Demo {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4,
5));
List<Integer> list2 = new ArrayList<>(Arrays.asList(4, 5, 6, 7,
8));
list1.retainAll(list2);
System.out.println(list1);
}
}

[4,5]
[1,2,3,4,5]
[4,5,4,5]
[6,7,8]

->[4,5]

What will be the output?


public class Test{
public static void main(String args[]) {
Map m = new HashMap();
m.put(null, "Test");
m.put(null, "Fest");
System.out.println(m);
}
}

{null=Fest}
{null=Test}
compilation error at 7 and 8
compilation error at 8, about can't override the value "Test"

-> {null=Fest}

what will be the output of following code ?


class Animal {
void eat() {

System.out.println("Eating");
}
}
class Bird extends Animal {
void eat() {
System.out.println("Bird eating");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Bird();
a.eat();
}
}

Eating
Bird eating
Compilation Error
Runtime Error

-> Bird eating

import java.util.*;
class Main {
public static void main(String[] args)
{
LinkedList<String> list = new LinkedList<>();
list.add("First");
list.add("Second");
list.addFirst("Third");
list.addFirst("Zero");
System.out.println(list.getFirst());
}
}

First
Second
Third
Zero
->Zero

import java.util.*;
class Main {
public static void main(String[] args)
{
try {

int[] arr = new int[2];


arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught");
} finally {
System.out.println("Finally block executed");
}
}
}

What will be the output?


ArrayIndexOutOfBoundsException caught

Finally block executed

ArrayIndexOutOfBoundsException caught
Finally block executed

Compilation error

_>

ArrayIndexOutOfBoundsException caught
Finally block executed

import java.util.*;
class Main {
public static void main(String[] args)
{
HashSet<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("A");
set.add("C");
set.add("A");
set.add("C");
set.add("B");
set.add("D");
System.out.println(set.size());
}
}

8
4
3
2
->4

import java.util.*;

class Parent {
void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
void display() {
System.out.println("Child");
}
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
p.display();
}
}

->
Parent
Compilation Error
Runtime Error
Child

->Child

import java.util.*;

public class Main {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add(1, "C");
System.out.println(list);
}
}

[A, C, B]
[A, B, C]
[C, A, B]
[A, B]

->[A, C, B]

What will happen if an exception is not caught in a Java program?

The program will continue executing.


The program will terminate.
The program will ignore the exception
The exception will be handled by the JVM and the program will continue.
->
The program will terminate.

Consider the following code snippet. What type of exception will be thrown?
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[5]);
}
}

ArrayIndexOutOfBoundsException
NullPointerException
IndexOutOfBoundsException
ArithmeticException

->ArrayIndexOutOfBoundsException

import java.util.*;
class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound();
}
}
Animal makes sound
Dog barks
Compilation error
Runtime error

->Dog barks

What is polymorphism in Java?

The ability to have multiple constructors in a class.


The ability of different classes to be treated as instances of the same class
through inheritance.
The ability to write a class that can be used with any data type.
The ability to use multiple interfaces in a class

->The ability of different classes to be treated as instances of the same class


through inheritance.
Which among the following is the correct way to create a Statement object "sta"
inside the Connection object "conn"?

Statement sta = conn.createStatement();


Statement sta = conn.Statement();
Statement sta = createStatement();
Statement sta = conn.Statementcreation();

->
Statement sta = conn.createStatement();

public static void selectData(Connection c, String sql) throws SQLException{


Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
}
In the above code, what does "rs.getString(2)" do?

Inserts a string into the second column of the ResultSet


Updates a string in the second column of the ResultSet
Deletes a string from the second column of the ResultSet
Retrieves a string from the second column of the ResultSet

->Retrieves a string from the second column of the ResultSet

Which of the following method is used to perform DML statement-INSERT in JDBC?


executeResult()
executeQuery()
executeUpdate()
execute()

->executeUpdate()

What is the purpose of a PreparedStatement in JDBC? Not confirm check once


To execute SQL queries and retrieve results
To insert, update, or delete data in a database
To retrieve metadata about a database
To handle exceptions in JDBC operations

->
To insert, update, or delete data in a database

What should be present in blank for the below SQL statement ?


PreparedStatement ps = con.prepareStatement("select * from student");
ResultSet rs = ps.execute____();
Update
Select
Query
None of the above

->Query
Given the following code snippet, what will be the output?
String query = "SELECT name, age FROM Employees";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getInt("age"));
}
Assume the Employees table has the following data:
| name | age |
| John | 30 |
| Jane | 25 |

John 30
Jane 25

name age
John 30
Jane 25

Jane 25

John 30

->
John 30
Jane 25

What does setAutoCommit(false) do?(IMP)

commits transaction after each query


explicitly commits transaction
does not commit transaction automatically after each query
never commits transaction

->does not commit transaction automatically after each query

Which JDBC interface is responsible for managing transactions in JDBC?


java.sql.Connection
java.sql.Statement
java.sql.ResultSet
java.sql.Transaction

->
java.sql.Connection

In JDBC, the Connection interface is responsible for managing transactions. It


provides methods to:
Enable/disable auto-commit → setAutoCommit(false)
Commit transactions → commit()
Rollback transactions → rollback()

Which of these obtains a Connection?

Connection.getConnection(url)
Driver.getConnection(url)
DriverManager.getConnection(url)
new Connection(url)

->DriverManager.getConnection(url)

How do you set a string parameter in a `PreparedStatement`?


setParameter()
setValue()
setString()
setText()

->setString()

what the following code snippet does ?


if (rs.next()) {
// Process the row
}

set the maximum number of rows that a `Statement` object can return?
handle SQL warnings
check whether a `ResultSet` object contains more rows

->
check whether a `ResultSet` object contains more rows

what will be the output of following code snippet ?


try {
Connection connection = DriverManager.getConnection("jdbc:derby:
:C//MyDB;create=true");
System.out.println("Connected to the database successfully.");
} catch (SQLException e) {
e.printStackTrace();
}

Error: Could not establish a connection.


Exception in thread "main" java.sql.SQLException: No suitable driver found
Connected to the database, but an error occurred.
Connected to the database successfully

->Exception in thread "main" java.sql.SQLException: No suitable driver found

What must be the first characters of a database URL?

jdbc:
jdbc,
db:
db,

->jdbc:

Which class is used to establish a connection to a database in JDBC?

Conncetion
Statement
DriverManager
ResultSet

->DriverManager

What does JDBC stand for?


Java Database Connectivity
Java Data Connectivity
Java Database Command
Java Data Control

->Java Database Connectivity

Which method is used to execute a query that returns a ResultSet object?


executeUpdate()
executeQuery()
execute()
executeResultSet()

->executeQuery()

Consider the following code snippet. What does it do?


String url = "jdbc:derby://localhost:3306/mydatabase";
Connection conn = DriverManager.getConnection(url);

It registers the JDBC driver.


It closes the database connection.
It establishes a connection to the MySQL database.
It executes a SQL query
None Of above

->
None Of above

Which of the following is correct about PreparedStatement?


It is used for batch updates.
It is used to execute stored procedures.
It allows you to set parameters dynamically.
It doesn't support SQL queries

->It allows you to set parameters dynamically.

Which of the following is a valid method to release a database connection in JDBC?


conn.close()
conn.disconnect()
conn.terminate()
conn.shutdown()

->conn.close()

Which method takes responsibility to check the type of request received from the
client and respond accordingly?
init()
service()
destroy()
request()

->service()
When a URL specific to a particular servlet is triggered, the _____________ method
is invoked.

init()
service()
destroy()
request()

->
service()

"init()": is called when the servlet is first loaded and initialized, not on every
request.
"service()": is the primary method that handles each incoming request to the
servlet.
"destroy()": is called when the servlet is being removed from the server and is
about to be unloaded.

________________ method is called by the Servlet when wanting to halt the current
or background threads

init()
service()
destroy()
request()

->destory()

_jspinit() method is invoked in which phase of the JSP Life cycle?

Instantiation
Initialisation
Request Processing
Destroy

->Initialisation

_jspservice() method is invoked in which phase of the JSP Life cycle?


Instantiation
Initialisation
Request Processing
Destroy

->Request Processing

Instantiation:
This is the phase where a JSP page is first loaded and an instance of its servlet
class is created.
Initialization:
After instantiation, the jspInit() method is called to perform any necessary
initial setup.
Request Processing:
This is the phase where the actual processing of a client request happens, and the
_jspService() method is called to handle the request.
Destroy:
When the JSP page is being removed from the server, the jspDestroy() method is
called.

Which of the following code is used to get an attribute in a HTTP Session object in
servlets?
session.getAttribute(String name)
session.alterAttribute(String name)
session.updateAttribute(String name)
session.setAttribute(String name)

->session.getAttribute(String name)

What will be the output for the following code?


<html><body>
<% int i = 20 ;%>
<% while(i>=15) { %>
out.print(i);
<% } %>
</body></html>
20
15
2.02E+0.11
None of the above

-> None of the above

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Welcome to Servlets</h2>");
}
What will be displayed when this Servlet is accessed through a browser?
An Error message
Welcome
Welcome To Servlets
Compilation error

->Welcome To Servlets

What is the purpose of the web.xml file in a servlet-based web application?


To define the HTML structure of web pages
To configure the servlet container and servlet mappings
To store client-side JavaScript code
To define the database schema

->To configure the servlet container and servlet mappings

How do you set an attribute in a request object from a Servlet?

setAttribute()
addAttribute()
putAttribute()
setParam()

->setAttribute()
what the of following code snippet does? (Not sure)
<form action="submitServlet" method="post">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>

read data from an HTTP request?


access session attributes in a Servlet
handle form submission in a JSP page
create a scriptlet in JSP

->read data from an HTTP request

what the of following code snippet does?


RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
dispatcher.forward(request, response);

include a JSP file in another JSP file


forward a request from a Servlet to a JSP page?
handle form submission in a JSP page
used to read data from an HTTP request

->forward a request from a Servlet to a JSP page?

Which of the following is a JSP declaration?


<%-- code --%>
<% code %>
<%= code %>
<%! code %>

->
<%! code %>

How do you include a JSP file in another JSP file?

<include file="header.jsp"/>
<jsp:forward page="header.jsp"/>
<jsp:include>
<include page="header.jsp"/>

->
<jsp:include>

Which tag is used to create a scriptlet in JSP?


<scriptlet>
<jsp:scriptlet>
<%-- --%>
<% %>

-> <% %>

What is the file extension for a JSP file?


.jsp
.html
.java
.xml
-> .jsp

Consider the following code snippet. What will be the output if the servlet is
accessed with the URL /hello?

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
PrintWriter out = response.getWriter();
out.println("Hello, World!");
}
}

Hello, Servlet!
Hello, World!
Compilation error
Runtime error

->Hello, World

Consider the following code snippet in a JSP page. What will be the output?
<%! int count = 0; %>
<%= ++count %>

0
1
Compilation error
Runtime error

->1

In JSP, which tag is used to forward the request to another resource (such as
another JSP or servlet)?
<jsp:forward page="..."/>
<jsp:include page="..."/>
<%@ forward file="..."%>
<%! include file="..." %>

->
<jsp:forward page=""%>

Which tag is used to insert a Java expression directly into the output in a JSP
page?

<% %> (scriplet tag)


<%= %>(expression tag)
<%! %>(decleration tag)

-> <%= %>

Which of the below statement is incorrect about class name requirements?


Class name must begin with an alphabet.
Class name can contain only letters and cannot have digits,underscore or dollar
sign.
Class name cannot be a Java reserved keyword such as public or void.
None of the above

->Class name can contain only letters and cannot have digits,underscore or dollar
sign.

The doGet() method in the example extracts values of the parameters type
and number by using
request.getParameter()
request.setParameter()
response.getParameter()
response.getAttribute()

->request.getParameter()

Which SQL constraint do we use to set some value to a field whose value has
not been added explicitly?

UNIQUE
Not Null
DEFAULT
CHECK

-> DEFAULT

Which of the following method exposes the Data in the URL ?


doGet
doPost
doDisplay
None of the above

->doGet()

Which of the following is not a valid SQL type?


Float
Numeric
Decimal
Character

JSP expressions begin with <%= ...%> tags and do not include semicolons.
True
False

->True

What is the purpose of the "executeUpdate()" method?


To execute SELECT statements
To execute INSERT, UPDATE, and DELETE statements
To establish a connection to the database
To create a new Statement object

->To execute INSERT, UPDATE, and DELETE statements

Which of the following statements are true for Final keword in java ?
Prevents method overriding
Prevents Inheritance
Once a variable is declared with final , it can be assigned value only once
None of the options

->
Prevents method overriding
Prevents Inheritance
Once a variable is declared with final , it can be assigned value only once

Which of these packages contain all the collection classes ?


java.lang
java.util
java.net
java.awt

-> java.util

Can <!-comment-> and <%-comment-%> be used alternatively in JSP?


True
False

->False

How is a new record inserted into the database in JDBC with a parameterized
(dynamic) SQL query?
Using a Statement object
Using a ResultSet object
Using a PreparedStatement object
Using a Connection object

->Using a PreparedStatement object

lass DemoClass {
static void test() throws RuntimeException {
throw new ArithmeticException();
}
public static void main (String args[]){
try {
test();
}
catch (RuntimeException re) {
}
}
}

what is output of above code


RuntimeException
CompilationError
ExceptionHandled
None of the above

->ExceptionHandled

Which class can be used to print the dynamic content of HTML ?

SystemWriter
OutWriter
PrintWriter
None of the above
->PrintWriter

What will be the output of the following code?


public class SampleWhile {
public static void main(String[] args) {
// declare variables
inti=1,n=5;
while(i <= n) {
System.out.printin(i);
}
}
}
1 2 3 4 5
In�nite Loop
1 2 3 4
Error

->Error

How do you set the content type of a response in a Servlet?


Using “response.setContentType("text/html")"
With “request.setContentType("text/html")"
By setting a header in the HTML content
Content type is set automatically

->response.setContentType("text/html")

In method overloading, methods must have the same name and different
signatures.
True
False

->True

What is the role of the "Statement" object in JDBC?


To establish a database connection
To execute a SQL query
To handle the result set
To load the JDBC driver

->To execute a SQL query

Shreya has a Java application that needs to update the salary of an employee
with a specific ID in the database. Help Shreya in writing the SQL query
template that would she use with a PreparedStatement to achieve this ?
UPDATE employees SET salary = ? WHERE employee_id = ?;
MODIFY employees SET salary = ? WHERE employee_id = ?;
CHANGE employees SET salary = ? WHERE employee_id = ?;
ALTER employees SET salary = ? WHERE employee_id = ?;

->UPDATE employees SET salary = ? WHERE employee_id = ?;

Java code is embedded under which tag in JSP?


Declaration
Scriptlet
Expression
Comment
->Scriptlet

Which of the following is not an advantage of trigger?

Various column values are automatically generated by triggers


validating transactions and preventing them from being invalid
Tables are replicated asynchronously
Maintains the integrity of referential

->Tables are replicated asynchronously


How do you define a Manager class that inherits from the Employee class in
java?
class Employee extends Manager{// �elds and methods}
class Employee inherits Manager{// �elds and methods}
class Manager extends Employee{// �elds and methods}
class Manager inherits Employee{// �elds and methods}
->class Manager extends Employee { // fields and methods }

What is the correct way to define a URL mapping for a Servlet using
annotations?
@WebServiet("/ServletPath”)
@URLMapping("/ServletPath")
@HttpServiet("/ServletPath”)
@RequestMapping("/ServletPath")

->@WebServiet("/ServletPath”)

What will happen if you try to get the value of a key that does not exist in a
“HashMap

It returns ‘null’.
It returns a default value if provided with 'getOrDefault’ method.
It throws an exception.
lt automatically adds the key to the map.

->It ruturns 'null'

Which method is used to execute a SQL SELECT query?


executeUpdate()
executeQuery()
executeinsert()
execute()

->executeQuery()

What do Collections.sort internally uses if the number of elements are more


than 7?
Insertion sort
Merge sort
Quick sort

->Merge sort

The Collections.sort(List<T> list) method in Java internally uses TimSort, which is


a hybrid sorting algorithm combining Merge Sort and Insertion Sort.
If the number of elements is ≤ 7, Insertion Sort is used because it's efficient for
small datasets.
If the number of elements is > 7, Merge Sort is used because it's more efficient
for larger datasets.

Which file is created to configure the servlet container and servlet mappings
?
META-INF
web.xml
mapping.xml
WEB-INF

->web.xml

Which JDBC component is used for establishing a connection with the


specific database in JDBC?
ResultSet
Statement
PreparedStatement
DriverManager

->DriverManager

What is the primary purpose of a JDBC driver?


To execute SQL queries
To establish a connection between Java applications and databases
To create a database schema
To display the Result Set objects

->To establish a connection between Java applications and databases

In method overloading, methods must have the same name and different
signatures.

True
False

->True

Select the valid URL mapping of servlet in web.xml


/SampleServlet
*.do
*/*
SampleServiet

->
/SampleServlet
*.do

Which of the following code is used to get a HTTP Session object in servlets
?
request.getSession()
response.getSession()
new Session()
None of the above

->request.getSession()

Which of the following is a valid way to create a new file in Java?

You might also like