Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

1

CA-603 : ADVANCED JAVA

a) What is the use of cookies?

Class Cookie. Creates a cookie, a small amount of information sent by a servlet to a


Web browser, saved by the browser, and later sent back to the server. A cookie's value
can uniquely identify a client, so cookies are commonly used for session management.

b) What is the use of Runnable interface?

The runnable interface is used to write applications which can run in a separate thread.
Any class that implements the runnable interface is called a thread. The code of the
thread is executed by the interpreter after the thread is started.

c) Explain thread priority.

Thread priority in Java is a number assigned to a thread that is used by Thread
scheduler to decide which thread should be allowed to execute. In Java, each thread is
assigned a different priority that will decide the order (preference) in which it is
scheduled for running.

d) What is the use of HQL?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL,
but instead of operating on tables and columns, HQL works with persistent objects and
their properties. HQL queries are translated by Hibernate into conventional SQL
queries, which in turns perform action on database.

e) What are the directives in JSP?

S.No. Directive & Description

<%@ page ... %>


1 Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.

<%@ include ... %>


2
Includes a file during the translation phase.

<%@ taglib ... %>


3
Declares a tag library, containing custom actions, used in the page
2

f) What is networking?

Java networking is the concept of connecting two or more computing devices to share
resources. The application layer of a Java program communicates with the network.
The java.net package contains all of the Java networking classes and interfaces.

g) Write the method for creating connection?

A Connection is a session between a Java application and a database. It helps to


establish a connection with the database.

The Connection interface is a factory of Statement, PreparedStatement, and


DatabaseMetaData, i.e., an object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.

h) What is the yield ( ) method?

The yield() method of thread class causes the currently executing thread object to


temporarily pause and allow other threads to execute.

i) What is the use of socket class?

The java.net package in the Java platform provides a class, Socket , that implements
one side of a two-way connection between your Java program and another program on
the network. The Socket class sits on top of a platform-dependent implementation,
hiding the details of any particular system from your Java program.

j) What is servlet?

A servlet is a Java programming language class that is used to extend the capabilities
of servers that host applications accessed by means of a request-response
programming model. Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web servers.
3

a) Explain in details directives in JSP

JSP directives are the elements of a JSP source code that guide the web container on
how to translate the JSP page into its respective servlet. 
Syntax :
<%@ directive attribute = "value"%>
Directives can have a number of attributes that you can list down as key-value pairs and
separate by commas. The blanks between the @ symbol and the directive name, and
between the last attribute and the closing %>, are optional. 

There are three different JSP directives available. They are as follows: 
 Page Directives : JSP page directive is used to define the properties applying the JSP
page, such as the size of the allocated buffer, imported packages, and
classes/interfaces, defining what type of page it is, etc. The syntax of JSP page
directive is as follows: 
<%@page attribute = "value"%>
 Different properties/attributes : 
The following are the different properties that can be defined using page directive :
 import: This tells the container what packages/classes are needed to be
imported into the program.
Syntax:
<%@page import = "value"%>
b) Explain inter thread communication with an example.

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running


in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()
4

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.

c) Differentiate between statement and prepared statement interface.

Statement PreparedStatement
It is used when SQL query is to be It is used when SQL query is to be executed
executed only once. multiple times.
You can not pass parameters at
runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP Used for the queries which are to be
statements. executed multiple times.
Performance is very low. Performance is better than Statement.
It is base interface. It extends statement interface.
Used to execute normal SQL queries. Used to execute dynamic SQL queries.
We can not use statement for reading We can use Preparedstatement for reading
binary data. binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for writing We can use Preparedstatement for writing
binary data. binary data.
No binary protocol is used for
communication. Binary protocol is used for communication.
5

d) Explain the life cycle of thread.


Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1.New
2.Active
3.Blocked / Waiting
4.Timed Waiting
5.Terminated

Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other is running.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A)
has entered the critical section of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which leads to starvation.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
6

e) Explain methods of serversocket class with syntax.

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2) public synchronized void closes the server socket.


close()

a) What is the difference between execute ( ), executeQuery ( ) and executeupdate ( )?

executeQuery() executeUpdate() execute()

executeQuery() method used to executeUpdate() method used for execute() use for any SQL


retrieve some data from database. update or modify database. statements.
It returns an object of the class It returns an integer value. It returns a boolean value.
ResultSet executeQuery (String sql) int executeUpdate(String sql) int executeUpdate(String sql)
throws SQLException throws SQLException throws SQLException
This method is normally used This method Is used to execute This method can be used to
to execute SELECT queries. non SELECT queries. execute any type of SQL
DML as INSERT, DELETE, statement.
UPDATE or
DDL as CREATE. DROP

Example: Example: Example:


ResultSet Ts= int i= stmt.executeUpdate(query); Boolean b=
stmt.executeQuery(query); stmt.execute(query);
7

b) Explain an architecture of hibernate?

The Hibernate architecture includes many objects such as persistent object, session factory,
transaction factory, connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

o Java application layer


o Hibernate framework layer
o Backhand api layer
o Database layer

Let's see the diagram of hibernate architecture:

This is the high level architecture of Hibernate with mapping file and configuration file.
8

c) Explain methods of socket class with example.

Java Socket Class

The Socket class acts as an endpoint for communication between two machines. It implements .

Methods

Method Description

bind(SocketAddress bindpoint) This method binds the given socket to the specified
local address.

close() This method closes the socket.

connect(SocketAddress endpoint) The connect() method connects this socket to the


connect(SocketAddress endpoint, int server.
timeout) This method connects this socket to the server with a
specified timeout value.

getChannel() It returns a unique SocketChannel object associated


with this socket.

getInetAddress() It returns the address to which the socket is


connected.

getInputStream() It returns an input stream for the specified socket.

getKeepAlive() This method tests if the SO_KEEPALIVE option is


enabled or not.

getLocalAddress() It returns the local address to which the given socket


is bound.

getLocalPort() It gets the local port number to which the specified


socket is bound.

getLocalSocketAddress() This method gets the address of the endpoint to


which this socket is bound.

Example 1

1. import java.io.IOException;  
2. import java.net.*;  
9

3. public class JavaSocketExample1  {  
4.     public static void main(String[] args) throws IOException {  
5.         Socket socket = new Socket();  
6.         InetAddress inetAddress=InetAddress.getByName("localhost");  
7.         //the port should be greater or equal to 0, else it will throw an error  
8.         int port=1085;  
9.         //calling the constructor of the SocketAddress class  
10.         SocketAddress socketAddress=new InetSocketAddress(inetAddress, port);  
11.         //binding the  socket with the inetAddress and port number  
12.         socket.bind(socketAddress);  
13.         //connect() method connects the specified socket to the server  
14.         socket.connect(socketAddress);  
15.         //setSendBufferSize() sets the send buffer size or SO_SNDBUF option with the specified valu
e  
16.         socket.setSendBufferSize(67);  
17.         //getSendBufferSize() method returns the buffer size(SO_SNDBUF) used by the platform for 
output  
18.         System.out.println("Send Buffer size: "+socket.getSendBufferSize());  
19.         //enabling the boolean value true  
20.         boolean on=false;  
21.         //setKeepAlive() method either enables or disables the SO_KEEPALIVE option  
22.         socket.setKeepAlive(on);  
23.         //getKeepAlive() returns  a boolean indicating whether SO_KEEPALIVE option is enabled or 
not  
24.         if(socket.getKeepAlive()){  
25.             System.out.println("SO_KEEPALIVE option is enabled");  
26.         }  
27.         else{  
28.             System.out.println("SO_KEEPALIVE option is disabled");  
29.         }  
30.         //getRemoteSocketAddress() returns the address of the endpoint of the specified socket if t
he socket is connected  
31.         System.out.println("Remote socket address: "+socket.getRemoteSocketAddress());  
32.     }  }
Output:
Send Buffer size: 67
SO_KEEPALIVE option is disabled
Remote socket address: localhost/127.0.0.1:1085
10

d) Write a JSP program to accept Name & age of voter and check whether he/she is eligible
for voting or not.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="Slip29.jsp" method="post">
Name : <input type="text" name="name">

Age : <input type="text" name="age">

<input type="submit" value="Check">


</form>
</body>
</html>

JSP FILE:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
if(age >=18)
{
out.println(name + "\nAllowed to vote");
}
else
{
out.println(name + "\nNot allowed to vote");
}
%>
11

e) Write a JDBC program to delete the records of employees whose names are starting with
‘A’ character.

with �A�character.
importjava.sql.*;
class Slip9_1
{
public static void main(String args[])

Connection con;
Statement stmt;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:dsn");
if(con==null)
{
System.out.println("Connection Failed....");
System.exit(1);
}
System.out.println("Connection Established...");
stmt=con.createStatement();
int no = stmt.executeUpdate("Delete from employee where name like 'A
%'");
if(no!=0)
System.out.println("Delete Data sucessfully.....");
else
System.out.println("Data NOT Deleted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
12

a) Write advantages and disadvantages of spring.

Java Spring

There are a lot of tools that come with the Spring framework and allows us to reap the benefit
of the out of box solutions. We do not require to write thousands of lines of code. It saves both
time and energy. Let's discuss the advantages and disadvantages of the Spring framework.

Spring Pros

There are the following advantages of the Spring framework:

1. Light Weight: Spring is a lightweight framework because of its POJO implementation. It


does not force the programmer to inherit any class and implement any interface. With
the help of Spring, we can enable powerful, scalable applications using POJOs (Plain Old
Java Object).
2. Flexible: It provides flexible libraries trusted by developers all over the world. The
developer can choose either XML or Java-based annotations for configuration options.
The IoC and DI features provide the foundation for a wide-ranging set of features and
functionality. It makes the job simpler.

Spring Cons

1. Complexity: Working with Spring is more complex. It requires a lot of expertise. If you


have not used Spring before, first you will have to learn. The learning curve is also
difficult, so if you have not a lot of development experience, it is difficult to learn.
2. Parallel Mechanism: It provides multiple options to developers. These options create
confusion to developers that which feature to use and which to not and wrong decisions
may lead to significant delays.

b) Explain JSP tags with example.

JSP Tags
JSP scripting language include several tags or scripting elements that
performs various tasks such as declaring variables and methods, writing
expressions, and calling other JSP pages. These are known as JSP
scripting elements.
13

JSP Tags
JSP Tag Brief Description Tag Syntax

Specifies translation time instructions to the JSP


engine.

Directive <%@ directives %>

Declaration Declares and defines methods and


variables.
<%! variable dceclaration & method
Declaration definition %>

Allows the developer to write free-form Java code in


a JSP page.

Scriptlet <% some Java code %>

Used as a shortcut to print values in the output


HTML of a JSP page.

Expression <%= an Expression %>

Provides request-time instructions to the JSP


engine.

Action <jsp:actionName />

Used for documentation and for commenting out


parts of JSP code.

Comment <%– any Text –%>

c) What are the advantages and disadvantages of multithreading?


14

Following are some of the common advantages of multithreading:

 Enhanced performance by decreased development time


 Simplified and streamlined program coding
 Improvised GUI responsiveness
 Simultaneous and parallelized occurrence of tasks
 Better use of cache storage by utilization of resources
 Decreased cost of maintenance
 Better use of CPU resource
Multithreading does not only provide you with benefits, it has its disadvantages too. Let
us go through some common disadvantages:

 Complex debugging and testing processes


 Overhead switching of context
 Increased potential for deadlock occurrence
 Increased difficulty level in writing a program
 Unpredictable results

d) Write servlet program to accept two numbers from user and print addition of that in blue
colour.

package servletjsp;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddServlet extends HttpServlet


{
public void service(HttpServletRequest req,HttpServletResponse res)
{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));

int k=i+j;
System.out.println("the result is "+ k);
}
}
e) Write a JDBC program to display the details of employees (eno,
ename, department, sal) whose department is ‘Computer
Application’.
15

importjava.sql.*;
public class Slip3_1
{
public static void main(String args[])
{
Connection con;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:dsn");
if(con==null)
{
System.out.println("Connection Failed....");
System.exit(1);
}
Statement stmt=con.createStatement();
ResultSetrs=stmt.executeQuery("select * From employee Where
dept='computer science'");
System.out.println("eno\t"+"ename\t"+"department\t"+"sal");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\
t"+rs.getString(3)+""+rs.getI
nt(4));
}
con.close();
rs.close();
stmt.close();
}
catch(Exception e)
{
System.out.println
}
}
}

a) Run method
16

The run() method is available in the thread class constructed using a separate Runnable
object. Otherwise, this method does nothing and returns. We can call the run() method
multiple times. 

The run() method can be called in two ways which are as follows:
1. Using the start() method.
2. Using the run() method itself.

Syntax:
public void run()
{
//statements
}
b) Statement interface

The Statement interface provides the method to execute the database queries. After


making a connection, Java application can interact with database. The Statement interface
contains the ResultSet object.

c) HttpServlet.

HttpServelt is an abstract class, it comes under package


‘javax.servlet.http.HttpServlet‘ . To create a servlet the class must extend the
HttpServlet class and override at least one of its methods (doGet, doPost, doDelete,
doPut). The HttpServlet class extends the GenericServlet class and implements a
Serializable interface. 

You might also like