0% found this document useful (0 votes)
609 views

pra mcq tcs

The document consists of multiple-choice questions (MCQs) related to Java programming, JDBC, and JSP concepts. It covers topics such as JDBC connection establishment, method overloading, exception handling, and collection framework. Each question presents four options, testing the reader's knowledge on various Java programming principles and practices.

Uploaded by

jaideep10801
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
609 views

pra mcq tcs

The document consists of multiple-choice questions (MCQs) related to Java programming, JDBC, and JSP concepts. It covers topics such as JDBC connection establishment, method overloading, exception handling, and collection framework. Each question presents four options, testing the reader's knowledge on various Java programming principles and practices.

Uploaded by

jaideep10801
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Mcq

1. Which of the following is required to establish a


connection to a database using JDBC?

 A valid SQL query.


 The JDBC driver class name
 PreparedStatement.
 ResultSet

2. What does the "Class.forName()" method do in JDBC?

 Executes an SQL query.


 Establishes a database connection.
 Loads the JDBC driver class.
 Fetches results from a database table.

3. Which of the following methods is used to execute an


SQL query that does not return any data (e.g.,
INSERT, UPDATE, DELETE)?

 executeQuery()
 execute()
 executeUpdate()
 executeInsert()

4. Consider the following line of code:


PreparedStatement ps =
conn.prepareStatement("INSERT INTO table_name
VALUES(?, ?)");
What do the "?" symbols represent?
 Wildcards for any value.
 Placeholders for input values.
 Indications of a syntax error.
 Symbols to denote optional values.

5. What does the "ResultSet" object in JDBC represent?

 A table in the database.


 A single row of data.
 The result of a SELECT query.
 A database connection string.

6. In JDBC, which method is used to execute a SELECT


query?

 executeInsert()
 execute()
 executeUpdate()
 executeQuery()

7. If you want to insert a new record into a table using


JDBC, which of the following is the most appropriate to
use?

 Statement
 PreparedStatement
 ResultSet
 DriverManager
8. Consider the following code snippet:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
Students");
What will the "rs" object contain after executing the
above lines?

 The first row of the Students table.


 All rows from the Students table.
 The SQL query as a string.
 The metadata of the Students table.

9. In the given code:


insertStudent.setInt(1, 2);
What does the number "1" represent?

 The column number in the database table.


 The value to be inserted.
 The first parameter in the SQL query .
 The data type of the value.

10. How can you fetch the value of the second column
as a string from a "ResultSet" object named "rs"?

 rs.getString(2);
 rs.getInt("column_name");
 rs.getColumn(2);
 rs.getValue(2);

11. Given the code:


class Vehicle {
void run(){
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle{
void run(){
System.out.println("Bike is running");
}
}
public class Test{
public static void main(String args[]){
Vehicle obj = new Bike();
obj.run();
}
}
What will be the output?

 Vehicle is running
 Bike is running
 Compilation error
 None of the above

12. Consider the following code snippet:


void display(int a, double b){
System.out.println("A");
}
void display(double a, int b){
System.out.println("B");
}
If we call "display(10, 20);", which method gets
executed?

 A
 B
 Both A and B
 Compilation error due to ambiguity

13. Given the code:


ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
What will "colors.get(1)" return?

 Red
 Green
 Blue
 An IndexOutOfBoundsException

14. Examine the following code:


HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
What will be the output of "map.get(2)"?

 One
 Two
 Three
 Null

15. Consider the code:


try {
System.out.println(10/0);
}catch(ArithmeticException e){
System.out.println("Arithmetic Exception Caught");
}
What will be the output?

 10/0
 An unhandled exception message
 Arithmetic Exception Caught
 No output

16. Which of the following keywords is used in Java to


derive a class from another class?

 imports
 implements
 extends
 inherits

17. Which of the following is not an access modifier in


Java?

 public
 restricted
 protected
 private
18. When is a method said to be overloaded?

 When it is defined in both superclass and subclass.


 When it exists in multiple classes in the same package.

 When there are multiple methods in a class with the


same name but
different parameters

 When a method has more than one return type.

19. In Java's collection framework, which class


provides a dynamic array for storing elements?

 HashSet
 LinkedList
 Array
 ArrayList

20. In a Java HashMap, what must be unique?

 Values
 Keys
 Both keys and values
 Neither keys nor values

21. Which JSP scripting element is used to evaluate a


single Java expression and insert its value into the
output?
 JSP Expression
 JSP Scriptlet
 JSP Declaration
 JSP Comment

22. In a JSP page, which scripting element allows you


to define methods or variables that can be used
throughout the JSP page?

 JSP Expression
 JSP Scriptlet
 JSP Declaration
 JSP Comment

23. If you want to include another Java class, for


instance, com.javaclasses.Car in your JSP page, which
irective would you use?

 <% import com.javaclasses.Car; %>


 <jsp:import class="com.javaclasses.Car" />
 <%@ page import="com.javaclasses.Car" %>
 <include class="com.javaclasses.Car" />

24. How can you include a file, say "header.html", in a


JSP page?

 <jsp:insert file="header.html" />


 <jsp:add page="header.html" />
 <jsp:include file="header.html" />
 <jsp:include page="header.html" />

25. Given a form input with the name "username",


which of the following JSP code snippets correctly
retrieves
its value?

 ${param.username}
 ${request.getParameter.username}
 <%= request.getParameter("username") %>
 Both A and C

26. What method is invoked in a Servlet when an


HTML form uses the GET method?

 doGet()
 doPost()
 doExecute()
 doRequest()

27. Given the Servlet code snippet:


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?

 Welcome
 Welcome to Servlets
 An error message
 The current date and time

28. In which directory structure of a Dynamic Web


Project in Eclipse would you typically place your Servlet
classes?

 /WebContent
 /src
 /lib
 /META-INF

29. Which annotation is used to map a servlet to a


specific URL?

30. Which of the following is not a lifecycle method of


a servlet?

31. What will be the output for following code ?


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

32. Which method is used to obtain the textual


description of an exception in Java?

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

33. Jane is trying to run the following code on method


overloading , she is
confused while executing the code that the statement
she has
written calls which method . Help jane to understand
theconcept by
choosing correct option
class MethodOverloading{
void display(int a,float b) { // Method1
System.out.println(a+b);
}
void display(int a,int b) { //Method 2
System.out.println(a+b);
}
void display(int a,long b) { // Method 3
System.out.println(a+b);
}
void display(int a,double b) {
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
34. what will be the output of following code after
Execution ?
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

35. What will be the output of following code after


execution ?
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

36. 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]

37. what will be the output of following code


afterexecution ?
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

38. 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
 InputMismatchExceptio
 [Chennai, Mumbai, Kolkata, Bangalore]

39. what will be the output of following code after


execution ?
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]

40. Which of the following is a runtime exception on


java ?
 NullPointerException
 FileNotFoundException
 ClassNotFoundException
 IOException

41. Which method is used to retrieve the auto-


generated keys after executing an INSERT statement in
JDBC ?
 executeUpdate()
 executeQuery()
 getGeneratedKeys()
 getResultSet()

42. Which JDBC interface is used to execute a


parameterized SQL query to retrieve data from a
database?
 Statement
 ResultSet
 PreparedStatement
 CallableStatement

43. Which of these obtains a Connection?


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

44. Jay is trying to connect with database. help jay by


selecting correct method to connect with Database ?

 connect( )
 openConnection( )
 getConnection( )
 createConnection( )

45. 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
46. Rahul is trying to end the database connection.
helprahul to end the database connection by using
proper
method

 shutdown()
 close()
 endconnection()
 disconnect()

47. Ram is learning about a JDBC. help ram to


understand the Steps of connecting with Database by
choosing correct option

 Register the driver class


Creating connection
Creating statements
Executing queries
Closing connection

 Register the driver class


Creating connection
Executing queries
Creating statements
Closing connection

 Register the driver class


Creating connection
Closing connection
Creating statements
Executing queries

 Register the driver class


Creating connection
Creating statements
Closing connection
Executing queries

48. 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

49. 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:\\Us
er\\MyDB;create=true");
 Class.forName("org.apache.derby.jdbc.EmbeddedDrive
r");
con=DriverManager.getConnection("jdbc:derby:C:\\Us
er\\MyDB;create=true");
 Class.forName("org.apache.derby.jdbc.EmbeddedDrive
r");
con=DriverManager.getConnection("derby:C:\\User\\
MyDB;create=true");
 Class.forName("org.apache.derby.jdbc.EmbeddedDrive
r");
con=DriverManager.getConnection("jdbc:C:\\User\\My
DB;create=true");

50. 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

51. 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

52. 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

53. 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.

54. What will be the output for the following code?


<html><body>
<% int i = 20 ;%>
<% while(i>=15) { %>
out.print(i);
<% } %>
</body></html>

 2.02E+11
 20
 15
 None of the above

55. 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)
56. Which of the following is stored at client side?

 URL rewriting
 Hidden form fields
 SSL sessions
 Cookies

57. What temporarily redirects response to the


browser?

<jsp:forward>

<%@directive%>

response.sendRedirect(URL)

response.setRedirect(URL)

Which of the following is not a directive in JSP?

 page directive
 include directive
 taglib directive
 command directive

58. “request” is instance of which one of the following


classes?
 Request
 HttpRequest
 HttpServletRequest
 ServletRequest
59. 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()

60. Which of the collection classes will be helpful when


we need to store unique elements and their insertion
order is maintained?

 HashSet
 LinkedHashSet
 TreeSet
 PriorityQueue

61. Which of these keywords must be used to monitor


for exceptions?

 try
 finally
 thrown
 catch

62. Siddhant 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]

63. Which of the following is an unchecked exception


in Java?

 NullPointerException
 ArithmeticException
 ClassNotFoundException
 IOException

64. How do you define a Manager class that inherits


from the Employee class in java?

 class Employee extends Manager{// fields and


methods}
 class Employee inherits Manager{// fields and
methods}
 class Manager extends Employee{// fields and
methods}
 class Manager inherits Employee{// fields and
methods}

65. What is the type of inheritance for the following ?


class Company{
// some code
}
class Employee extends Company{
// some code
}
class Programmer extends Employee{
// some code
}
class Tester extends Employee{
// some code
}

 Hybrid Inheritance
 Simple Inheritance
 Multi level Inheritance
 Multiple Inheritance

66. Which of the following statement(s) is/are true for


compile time Polymorphism in java?
(A) The call is resolved by the compiler.
(B) It provides fast execution.

 Only (A) is true.


 Both (A) and (B) are true.
 Only (B) is true.
 Both (A) and (B) are false.

67. Suppose you are developing a Java application for


an online bookstore. When a user tries to purchase
a book, your code encounters an unexpectedsituation
where the book they want is out of stock. To
handle this scenario, you decide to use exception
handling.
What type of exception handling mechanism in Javawould
be most suitable for handling the
situation when a user attempts to purchase an out-of-
stock book?

 FileNotFoundException
 OutOfMemoryError
 NullPointerException
 CustomOutOfStockException

68. Manish Reddy wants to create a list of Student


names that allows duplicate entries, and the insertion
order is maintained. Which java collection should he will
use?

 HashSet
 ArrayList
 TreeSet
 HashMap
69. Which of the following is a valid way to create a
new file in Java?
 File myfile = new File("myfile.txt");
 FileWriter myfile = new FileWriter("myfile.txt");
 PrintWriter myfile = new PrintWriter("myfile.txt");
 Scanner myfile = new Scanner("myfile.txt");

70. Which of the following method is used to perform


DML statements in JDBC?

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

71. Subhajit is trying to establish the connection with


the SQLite Database. Help Subhajit to choose correct
code snippet.

 Class.forName("org.mysql.jdbc.EmbeddedDriver");
con=DriverManager.getConnection("jdbc:derby:C:\\
User\\MyDB;create=true");
 Class.forName("org.sqlite.JDBC");
con=DriverManager.getConnection("jdbc:sqlite:C:\\
User\\MyDB");
 Class.forName("org.apache.derby.jdbc.EmbeddedDr
iver")
con=DriverManger.getConnection("derby:C:\\User\\
MyDB;create=true")
 Class.forName("org.apache.derby.jdbc.EmbeddedDi
ver");
con=DriverManager.getConnection("jdbc:C:\\User\
MyDB;create=true");

72. Which of these obtains a Connection in JDBC?


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

73. Ritik is learning about a JDBC.Help Ritik to


understand the Steps of connecting with Database by
choosing correct option
 Register the driver class 2. Creating connection 3.
Creating statements 4. Executing queries 5. Closing
connection

 Register the driver class 2. Creating connection 3.


Executing queries 4.Creating statements 5. Closing
connection

 Register the driver class 2. Creating connection 3.


Closing connection 4.Creating statements 5.
Executing queries

 Register the driver class 2. Creating connection 3.


Creating statements 4.Closing connection 5.
Executing queries
74. 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

75. The executeQuery() method is used to execute SQL


statements that:
 Update existing records in the database.
 Query the database and return a result set.
 Commit pending transactions.
 None of the given

76. What is the return type of the executeUpdate()


method in JDBC?
 int
 ResultSet
 boolean
 number

77. In a web application, you need to insert user


registration data into a database table called users. The
user data includes username, email, and password.
Which JDBC interface is most suitable for
executing this kind of query to prevent SQL injection
attacks ?
 Statement
 ResultSet
 CallableStatement
 PreparedStatement

78. 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 =
?;

79. You are developing an e-commerce application in


Java that needs to fetch product information including
name, price, and availability from a database. Which
method of ResultSet would you use to retrieve the
availability of a product?
 getString()
 getInt()
 getDouble()
 getBoolean()

80. Which is not a directive?


 include
 page
 export
 useBean

81. 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)

82. Which of the following is stored at client side ?


 URL rewriting
 Hidden form fields
 SSL sessions
 Cookies

83. Which of the following is stored at client side ?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()
84. What is the output of the following Code Snippet ?

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

85. Which of the following method exposes the Data in


the URL ?
 doGet
 doPost
 doDisplay
 None of the above

86. In JavaServer Pages (JSP), what is the purpose of


the <%@ page import="..." %> directive?
 To include external JavaScript files
 To import Java packages and classes
 To define custom tag libraries
 To set the content type of the response

87. JSP expressions begin with <%= ...%> tags and do


not include semicolons.
 TRUE
 FALSE

88. You are developing a web application for an online


quiz platform using Java technologies. The application
involves displaying questions dynamically and collecting
user responses. As you work with JavaServer Pages (JSP)
and Servlets, you encounter a scenario related to user
authentication and session management.When a user
successfully logs in to the quiz platform, what Java
technology is commonly used to maintain their session
information throughout their interaction with the
application?
 JDBC (Java Database Connectivity)
 JavaBeans
 HttpSession
 JPA (Java Persistence API)

89. How do we identify an expression tag in JSP web


pages?
 <% %>
 <%! %>
 <%@ %>
 <%= %>

You might also like