Friday, 10 November 2017

TCS Tech Lounge JAVA Final-1

import java.util.*;
class hashtable{
            public static void main(String args[]){
                        Hashtable obj = new Hashtable();
                        obj.put("A",new Integer(3));
                        obj.put("B",new Integer(2));
                        obj.put("C",new Integer(8));
                        obj.remove(new String("A"));
                        System.out.print(obj);
            }
}

Ans: {C=8, B=2}

Consider the following Schema?
STUDENTS(student_code, first_name,last_name, email, phone_no, date_of_birth, honours_subject, percentage_of_marks); Which of the following query would display names and percentage of marks of all  students stored by honours subject,and then order by percentage of marks?
Ans: (a) Select first_name, lastname, hours_subject, percentage_of_marks from students order by honours_subject,percentage_of_marks.


Which of the following statements are incorrect?
Ans: Strings in java are mutable.


Which statements is true for request.getSession(true) method?
Ans:  getSession(true) method always returns a new session


In HTTP Request method Get request is secured because data is exposed in URL bar?
Ans: False



JDK stands for
Java Development Kit


import java.util.*;
public class Test{
            public static void main(String args[]){
                        System.out.println(new Test().mystery("DELIVER"));
            }
            public String mystery(String s){
                        String s1 = s.substring(0,1);
                        String s2 = s.substring(1,s.length()-1);
                        String s3=s.substring(s.length()-1);
                        if(s.length()<=3)
                                    return s3+s2+s1;
                        else return s1+mystery(s2)+s3;
            }
}

Ans: DEVILER


import java.util.*;
public class Test{
            public static int intValue;
            public static void main(String args[]){
            System.out.println(intValue);
            }
           
}
Ans: 0


FileOutputStream is meant for writing streams of_ _ _ _ _  _
Ans: raw bytes
                

What is the return type of reverse() method in StringBuffer class?
Ans: StringBuffer


Which of these is an incorrect array declaration?
Ans:  (d) int arr[] = int [5] new


_ _ _ _ is used to compare equality of two Strings
Ans: equals() method of Strong class


Which of these statements can skip processing remaining of code in this its body for a particular iteration?
Ans: continue

New drivers can be plugged-in to the JDBC API without changing the client code.
Ans: TRUE


What exception is thrown by read() method of InputStreamReader?
Ans: IOException

JAVA_HOME points to which directory?
Ans: JDK Installation directory.

In which package can we found DataInputStream class?
Ans: java.io

Is write() method in BufferedWriter Class overloaded?
Ans: TRUE

Which of the following is implemented by OutputStream class?
Ans: All of the mentioned. (closeable, flushable,autocloseable)

import java.util.*;
public class Test{
            public static void main(String args[]){
            int num=10;
            switch(num);
            }
           
}
Ans: Compiler Error

JDk7 introduced a new version of the try statement known as____
Ans: try-with-resources statement

Which of these exception is thrown in cases when the file specified for writing it not found?
Ans: FileNotFoundExcepion

public void foo(boolean a, boolean b){
                        if(a)
                        {
                                    System.out.println("A"); // line 5
                        }else if(a&&b){ //line 7
                                    System.out.println("A&&B");
                        }else{ // line 11
                                    if(!b){
                                                System.out.println("notB");
                                    }else{
                                                System.out.println("ELSE");
                                    }
                        }
            }
ANS: If a is false and b is true then the output is “ELSE”
                                                                                                                                           

TCS Tech Lounge Web Development With Java

What is the output of the following code
The value is <%=””%>
Ans: The value is

Which of the following is not an attribute of Page Directive
Ans: name

Select valid expression tag from the following
Ans: <%=new java.util.Date().toString()%>

Comments in Jsp file can be written by
Ans: <%--  ……….. --%> and <!--  ……….. -->

Why RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?
Ans:  The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.
In JSP, how can you know that HTTP method (GET or POST) is used by client request?
Ans:  request.getMethod()

Select the correct scopes in JSp
Ans: page,request,session,application
What is a benefit of using JavaBeans to separate business logic from presentation markup within the JSP environment?      Ans:
Which of the following are correct. Select the one correct answer.
Ans:  To use the character %> inside a scriptlet, you may use %\> instead.

 What gets printed when the following JSP code is invoked in a browser. Select the one correct answer.
    <%= if(Math.random() < 0.5) %>
      hello
    <%= } else { %>
      hi
    <%= } %>
Ans: The JSP file will not compile.

What gets printed when the following is compiled. Select the one correct answer.

    <% int y = 0; %>

    <% int z = 0; %>

 

    <% for(int x=0;x<3;x++) { %>

    <% z++;++y;%>

    <% }%>

    <% if(z<y) {%>

    <%= z%>

    <% } else {%>

    <%= z - 1%>

    <% }%>

 

Ans: 3

 

Which of the following is not implicit object in JSP?

Ans: pageConfig

 

Which of the following code is used to set the session timeout in servlets?

Ans: session.setMaxInactiveInterval(interval)

What is the return type of getParameter(String name) in ServletRequest
Ans:  String

Which of the following code is used to set auto refresh of a page after 5 seconds?
Ans: response.setIntHeader(“Refresh”,5)

How to create a cookie in a servlet?
Ans: Use new Operator

Which of the following code retrieves the MIME type of the body of the request?
Ans: request.getContentType()

Which of the following code delete a cookie in servlet?
Ans: cookie.setMaxAge(0);
Select the right options which second.jsp can be included in first.jsp
Ans:  <%@include file=”second.jsp”%> , <jsp:include page=”second.jsp”/>

Which of the below methods returns a string containing information about the servlet, such as its author, version, and copyright.
Ans: getServletInfo()

A JSP page called test.jsp is passed a parameter name in the URL using “http://localhost:8080/projectName/test.jsp?
Ans:
Which of the following code used to get session in servlet?
Ans: request.getSession()
In HTTp request which asks for the loopbacks of the request message, for testing or troubleshooting?
TRACE
What is the return type of getAttribute(String name) in ServletRequest
Ans: Object
Select the right method to include welcome file in a web application
Which of the following code can be used to set the character encoding for the body of the response?
ANS: response.setCharacterEncoding(charset)
Which of the following package contains servlet classes?
ANS: javax.servlet, javax.servlet.http
Select a valid declaration from the following
Ans: <%! String orgName=”TCS”;%>
What is the return type of getAttribute(String name) in ServletRequest
ANS: Object
A JSP needs to generate an XML file. Which attribute of page directive may be used to specify that JSP is generating an XML file?
ANS: contentType
How can you make jsp page as error page
ANS: isErrorPage=”true”
String name = request.getAttribute(“name”); Select the correct option from below for this code statement.
Ans: It gives compilation error as we need to use the casting of (String)
Which of the following code can be used to clear the content of the underlying buffer in the response without clearing headers or status code.
Ans: response.resetBuffer()
Java Declaration tag is used to declare
ANS: both variables and methods
Which of the following is true about javax.servlet.error.exception_type?
Ans: This attribute gives information about exception type which can be stored and analyzed after storing in a java.lang.Class data type
Which of the following is legal JSP syntax to print the value of i.select the one correct answer

Jsp is used for
ANS: Server Side Programming
Which is not a JSP directive ?
ANS: scriptlet
Which of the following code sends a cookie in servlet?
ANS: response.addCookie(cookie);
 Web Development With Java mcqs
1. Error Message displayed when the page is not found at current location?
Ans: 404

2. What is the output of the following code. The value is <%=""%>

Ans: The value is

3. What gets printed when the following JSP code is invoked in a browser. Select the one correct answer. <%=if(Math.random()<0.5%)>hello<%=}else{%>hi<%=}%>

Ans: The JSP file will not compile

4. Select the right option to set session expiry after 1 minute of inactiveness

Ans: <session-config><session-timeout>1</session-timeout></session-config>

5. JSP is used for

Ans: Server Side Programming

6. Which of the following is true about javax.servlet.error.exception_type?

Ans: This attribute gives information about exception type which can be stored and analyzed after storing in a java.lang.Class data type

7. Which is not a JSP directive

Ans: scriptlet

8. Which of the following package contains servlet classes?

Ans: (a) javax.servlet
         (b) javax.servlet.http

9. JSP is 

Ans: Java Server Pages

10. Select the correct scopes in JSP

Ans: page, request, session, application

11. Select a valid declaration from the following

Ans: <%! String orgName="TCS";%>

12. How to create a cookie in servlet?

Ans: Use new operator

13. How many implicit objects are there in JSP

Ans: 9

14. In JSP, how can you know what HTTP method (GET or POST) is used by client request?

Ans: request.getMethod()

16. Comments in JSP can be written by

Ans: Both a and b (a. <%--comments--%>, b. <!--comments-->)



19. Which of the following tags can be used to print the value of an expression to the output stream?

Ans: <%=%>

20. Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?

Ans: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state

21. A JSP needs to generate an XML file. Which attribute of page directive may be used to specify that JSP is generating an XML file?

Ans: contentType

22. Select the right method to include welcome file in a web application

Ans: <welcome-file-list><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file-list>

23. Select a valid expression tag from the following

Ans: <%=new java.util.Dat().toString()%>


25. What is the difference between doing an include or a forward with a RequestDispatcher?

Ans: The forward method transfers control to the designated resource, while the include method invokes the designated resource, substitutes its output dynamically in the display, and returns control to the calling page

26. Which of the following is true about javax.servlet.error.exception_type?

Ans: This attribute gives information about exception type which can be stored and analyzed after storing in a java.lang.Class data type

27. What are Servlets?

Ans: Both of the above (Java Servlets are programs that run on a Web or Application server. Java Servlets act as a middle layer between a request coming from a web browser or other HTTP client and databases or applications on the HTTP server)

28. Which of the following is true about servlets?

Ans: All of the above. ((a) Servlets execute within the address space of a Web server. (b) Servlets are platform-independent because they are written in Java. (c)The full functionality of the Java class libraries is available to a servlet.)

29.  Which of the following is the correct order of servlet life cycle phase methods?

Ans: init, service, destroy

30. When init method of servlet gets called?

Ans: The init method is called when the servlet is first created. 

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

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

32. When service method of servlet gets called? 

Ans:  The service method is called whenever the servlet is invoked.

33. Which of the following is true about service method of servlet?

Ans: All of the above ((a) The servlet container i.e.webserver calls the service method to handle requests coming from the client. (b) Each time the server receives a request for a servlet, the server spawns a new thread and calls service. (c) The service method checks the HTTP request type GET,POST,PUT,DELETE,etc. and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. )

34. When doGet method of servlet gets called?

Ans: Both of the above. ((a) A GET request results from a normal request for a URL. (b) The service method checks the HTTP request type as GET and calls doGet method.)

35. When doPost method of servlet gets called?

Ans: Both of the above. ((a) A POST request results from an HTML form that specifically lists POST as the METHOD. (b) The service method checks the HTTP request type as POST and calls doPost method.)

37. How can you make jsp page as error page

Ans: isErrorPage="true"

38. In JSP, how can you know what HTTP method (GET or POST) is used by client request?

Ans: request.getMethod()

39. Which of the following code can be used to set the character encoding for the body of the response? 
Ans: response.setCharacterEncoding(charset) 

40. Which of the following is not an implicit object in JSP? 

Ans: pageConfig 

41. Java declaration tag is used to declare 

Ans: Both variables and methods 

42. What is the return type of getParameter(String name) in ServletRequest? 

Ans: String

What will be the output of the following code?
<% int x=5;%>; <%! Int x =10; %><%! Int y=50;%><%y*x%>
ANS: 250.0

how to get multiple values of selected checkboxes in a servlet?
ANS: String values[]=request.getParameterValues(“hobbies”);

which of the following code is used to get names of the parameters in servlet
ANS: request.getParameterNames()
JSP is
ANS: Java Server Pages
Which of the following code is used to set content type of a page to be serviced using servlet?

ANS: response.setContentType()

TCS Tech Lounge Java Database Connectivity (JDBC)

In the URL jdbc:oracle:thin:@172.25.192.71:1521:javadb, the string jdbc:oracle:thin represents?
Ans: Type of driver

which interface is responsible for transaction management in jdbc
Ans: Connection

what statements are correct about positioned updates(i.e. cursor updates) in ResultSets?
Ans:  Insert statements are only supported when using scrollable cursors.

Which of the following is correct about Class.forName() method call?
Ans:  (c) This method dynamically loads the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.

Statement pstmt = null;
Try{
Pstmt = con.createStatement(query);
ResultSet rs =pstmt.executeQuery(query);

ANS: The method will not compile because createStatement method does not take any input.


How do you use save point?
Ans: A Savepoint is used to mark intermediate points inside a transaction,in order to get a more fine-grained control. Transaction can be rolled back to a previous savepoint without affecting preceding work.

getResultSet or getUpdateCount both methods can be used to Retrieve the Results after execution of queryin JDBC.
Ans: TRUE

What happens if you call method close() on a ResultSet object?
Ans: The result set will be closed, the resource would be released and no more data can be retrieved from the result set.

Which type of driver converts JDBC calls into the network protocol used by the database management system directly?
Ans: type-4

ResultSet.CONCUR_UPDATABLE used with the result set is used to update the rows directly in the database.
Ans: TRUE

What is the correct Sequence in which Most relational databases handles a JDBC / SQL query.
1.      Parse the incoming SQL query.
2.      Compile the SQL query.
3.      Plan/optimize the data acquisition path
4.      Execute the optimized query/acquire and return data
Ans: 1 2 3 4

what statements are correct about jdbc transactions?
Ans: A transaction is finished when commit() or rollback() is called on the Connection object

Loading the driver using Class.forName is not mandatory if we are using a JDBC jar compliant with JDBC API v4
Ans: TRUE

consider the following code statement Class.forName(driverName); where driverName is the name of the driver for the corresponding DB. if the JDBC jar is not specified in the class path, then which ofthe exception is obtained?
Ans: ClassNotFoundException

what statements are correct about batched insert and updates?
Ans: To do a batched update/insert, you call addBatch(String statement) on a Statement object for each statement you want to execute in the batch
Or To execute a batched update/insert, you call the executeBatch() method on a Statement object

are resultsets updateable?
Ans: Yes, but only if you indicate a concurrency strategy when executing the statement, and if the driver and database support this option

Connection is _ _ _ _ _ _ _ _
Ans: interface

JDBC mcqs
1. Which type of driver converts JDBC calls into the network protocol used by the database management system directly?
Ans: Type 3 driver

2. What happens if you call deleteRow() on a ResultSet object?

Ans: The row you are positioned on is deleted from the ResultSet and from the database

3.

PreparedStatement pstmt=null;
try{
//con is Connection Object 
String query="select * from persons where p_id";
pstmt=con.prepareStatement(query);
pstmt.setInt(1,12);
ResultSet rs=pstmt.executeQuery(Query);
while(rs.next())
{
System.out.println(rs.getString("p_name"));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finaly
{
if(pstmt!=null)
{
pstmt.close();
}
}
Assuming the table persons contains two columns p_id and P_name and there is a row with p_id=12
What is the output of the above program?

Ans: The method will throw an SQL Exception because the queryString has been given again in the executeQuery method of the PreparedStatement

4. What is the return type of ResultSet.next()?

Ans: boolean

5. Which JDBC driver Type(s) can you see in a three-tier architecture and if the Web server and the DBMS are running on the same machine?

Ans: All of Type 1,Type2,  Type 3 and Type 4

6. What happens if you call the method close() on a ResultSet object?

Ans: The result set will be closed, the resources would be released and no more data can be retrieved from the result set

7. Which among the following is not a JDBC statement?

Ans: Called Statement

8. How do you use a savepoint?

Ans: A savepoint is used to mark intermediate points inside a transaction, in order to get a more fine-grained control. Transactions can be rolled back to a previous savepoint without affecting preceding work

9. Which statements about JDBC are true?

Ans: JDBC is an API to access relational databases, spreadsheets and flat files


10. try
{
Class.forName("oracle.jdbc.OracleDriver"); 
con=DriverManager.getConnection("jdbc:oracle:thin:@172.23.192.71:1521:javadb","USERID","PASSWORD");
ps=con.prepareStatement("insert into table1 values(?,?,?,?,?,?,?)");
ps.setString(1,cust.getCustName());
ps.setString(2,cust.getPassword());
ps.setLong(3,cust.getPhone());
ps.setString(1,cust.getEmail());
ps.execute();
}
catch
{
//catch block
}
What is the value of ps.execute?
Ans: False

11. What is the meaning of ResultSet.TYPE_SCROLL_INSENSITIVE?

Ans: This means that the ResultSet is sensitive to scrolling, but insensitive to changes made by others

12. How can you execute DML statements(i.e. insert, delete, update) in the database?

Ans: By invoking the execute(...) or executeUpdate(...) method of a normal statement object or a sub-interface object thereof

13. commit() method belongs to which interface?

Ans: Connection

14. Which JDBC driver Type(s) can be used in either applet or servlet code?

Ans: Both Type 3 and Type 4

15. What statements are correct about batched insert and updates?

Ans: To do a batched update/insert, you call addBatch(String statement) on a statement object for each statement you want to execute in the batch

16. Consider the following code statement Class.forName(driverName); where driverName is the name of the driver for the corresponding DB, if the jdbc jar is not specified in class path, then which of the exceptions is obtained?

Ans: ClassNotFoundException

17. How can you retrieve information from a ResultSet?

Ans: By invoking the special getter methods on the ResultSet: getString(...), getBoolean(...), getClob(...)....

18. What is the correct Sequence in which most relational databases handles a JDBC/ SQL query.

      1. Parse the incoming SQL query
      2. Compile the SQL query
      3. Plan/optimize the data acquisition path
      4. Execute the optimized query/acquire and return data
Ans: 1,2,3,4

19. What is the return type of executeUpdate()?

Ans: int

20. Which packages contain the JDBC classes?

Ans: java.sql and javax.sql

21. Which object allows you to execute parameterized queries?

Ans: PreparedStatement

22. What is used to execute parameterized query?

Ans:  PreparedStatement interface

23. How many JDBC driver types are there?

Ans: Four

24. JDBC stands for

Ans: Java Database Connectivity

25. Which of the following is a best practice?

Ans: At the end of the JDBC program, close the ResultSet, Statement and Connection objects one after the other

26. What is the meaning of TRANSACTION_REPEATABLE_READ?

Ans: ( c) Dirty reads and non-repeatable reads are prevented; phantom reads can occur

27. The JDBC API has always supported persistent storage through the methods getObject() and setObject()
Ans: True

28. Return type of ResultSet.next() is
Ans: Boolean

29. What is correct about DDL statements(create,grant…)?

Ans: DDL statements are treated as normal SQL statements



PreparedStatement pstmt=null;
try{
//con is Connection Object 
String query="select * from persons";
pstmt=con.prepareStatement(query);
ResultSet rs=pstmt.executeQuery(Query);
while(rs.next())
{
System.out.println(rs.getString("p_name"));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finaly
{
if(pstmt!=null)
{
pstmt.close();
}
}
Assuming the table persons contains two columns P_name
What is the output of the above program?

ANS: The names of all the persons table would be printed

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers
ANS: TRUE

Which JDBC drivers Type(s) is(are) the JDBC-ODBC brdge?
ANS: Type 1

There  is a table Employee containing the following columns
Emp_ID-integer
Name-varchar

What would be the output of the below piece of code?
Statement pstmt = null;
Try{
//con is Connection Object
String query = “select * from Employee”;
Pstmt = con.crerateStatemet();
ResultSet rs = pstmt.executeQuery(query);
While(rs.next()){
System.out.printkn(rs.getString(“Emp_ID”));
}
}
}catch(SQLException e){
e.printStackTrace();
}finaly{
If(pstmt !=null){
pstmt.close();
}

ANS: The code will not compile because EMp_ID is integer while retrieving the emp_id, the program uses rs.getString(“emp_ID”).

Which JDBC driver Types are for use over communications networks?
Ans: Both type 3 and type 4

 Public static void viewtable() throws SQlException{
Statement stmt = null;
String query  = “select * from table_name”;
Try{
Stmt = con.createStatement();
ResultSet rs = stmt.executeQuery();
While(rs.next())
{
System.out.println(rs.getString(1));
}
}catch(SQlException e){
e.printStackTrace();
}finally{
If(stmt!=null){
Stmt.close();
}
}
What will be the output of this method?
ANS: The method will throw an SQL Exception because the SQL queryString is missing in the execute method

What is Statement & ResultSet in JDBC?
ANS: Interface

Releasing connection resources should always be done in finally block, to make sure that resources are released even if there were exceptions
ANS: TRUE
Which exception has to be handled if close() method is called either on connection or Statement or ResultSet
ANS: SQLException

How can you execute a stored procedure in the database?
Ans: Call method execute() on a CallableStatement object

What is, in terms of JDBC, a DataSource?
Ans: A DataSource is a factory of connections to a physical data source

Which Interface is executed faster and is safe from SQL injection attacks?
ANS: PreparedStatement

What is javadb in the URL jdbc:oracle:thin:@172.25.192.71:1521:javadb?
ANS: service

How can you start a database transaction in the database?
ANS: By setting the autoCommit property of the Connection to false, and execute a statement in the database

Which of the following methods finds the maximum number of connections driver can obtain?
ANS: DatabaseMetaData.getmaxConnections

Which JDBC type represents a “single precision” floating point number that supports seven digits of mantissa?
ANS: REAL

How do you know in your Java Program that a SQL warning is generated as a result of executing a SQL statement in the database?
ANS: You must invoke the getWarnings() method on the Statement object (or a sub interface Thereof)

Which of these drivers are have their implementation in java

ANS: JDBC ODBC DRIVER