Monday, 18 September 2017

Paper Solution Assignment : 1
Q.1.     Solve any Eight of the following :
(1)          List four types of JDBC Drivers.
Ans :
(2)          Define Thread.
Thread : A thread is a single sequential flow of control within a program.
(3)          List any two methods of Vector Class.
Ans : Method of Vector Class are as follows :
                (1)  addElement (Object) : Adds the specified object as the last element of the vector.
                (2)  removeElement (Object) : Removes the element from the vector.
(4)          What is the use of sendError() method?
Ans : The sendError method sends an error response to the client using the specified status.
                Using this method clears the buffer.
                The server creates an HTML-formatted server error page.
                This page contains a default, or the message you provide, as an argument.
                It also sets the content type to "text/html", even if anyone changed this, but leaves cookies and other headers unmodified.
(5)          How comment is given in JSP?
Ans : JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of you JSP page.
                <%--This is JSP comment --%>
(6)          What is Bean?
Ans :
(7)          What is the use of Enumeration?
Ans : It is used to create sets of constants for use with variables and properties.                It is used whenever a procedure accepts a limited set of variables. It is used whenever constants need to be referred in a consistent, expressive and type safe way.
                When there is a need of predefined list of values which do not represent some kind of numeric or textual data enumeration can be used.
                When a variable (especially a method parameter) can only take one out of a small set of possible values enumeration can be used.
(8)          What is the use of Callable Statement?
Callable Statement : The Callable Statement interface can also accept runtime input parameters.
                A Callable Statement is a way to execute stored procedures in a JDBC compatible database.
                By using callable statements we can separate the application logic and the business logic.
(9)          List of the implicit objects in JSP.
Ans :
(10)        Write the syntax of Database URL.
Ans : Following is the syntax for Database URL :
                try
                {
                                Class.forName("oracle.jdbc.driver.OracleDriver");
                }
                Catch (ClassNotFoundException ex)
                {
                                System.out.println("Error : unable to load driver class!");
                                System.exit(1);
                }
Q.2.        Answer the following (any four) :
(1)          Describe Synchoronization with respect to Multithreading.
Ans : When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue.
                So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time.
                Each object in Java is associated with a monitor, which a thread can lock or unlock.
                Only one thread at a time may hold a lock on a monitor.
                Following is the general form of the synchronized statement :
synchronized(objectidentifier)  {
                //  Access shared variables and other shared resources
}
Example :
class SynchronizationDemo         {
                public void printCount(){
                try          {
                                                for(int i=5; i>0; i--)           {
                                                System.out.println("Counter ---- " +i);
                                }
                }              Catch (Exception e)         {
                                System.out.println("Thread interrupted.");
                }
    }
}
class ThreadDemo extends Thread          {
                private Thread t;
                private String threadName;
                SynchronizationDemo SD;
                ThreadDemo(String name, SynchronizationDemo sd)     {
                                threadName = name;
                                SD = sd;
                }
                public void run()               {
                                synchronized(SD)           
                                {
                                                SD.printCount();
                                }
                                System.out.println("Thread" + threadName + "exiting.");
                }
                public void start()
                {
                                System.out.println("Starting" +threadName);
                if(t==null)
                {
                                t=new Thread(this, threadName);
                                t=start();
                }
    }
}
public class TestThraed  {
public static void main(String args[])
                {
                SynchronozationDemo SD=new
SynchronizationDemo();
                ThreadDemo T1=new ThreadDemo ("Thread-1",SD);
                ThreadDemo T2=new ThreadDemo ("Thread-2",SD);
                T1.start();
                T2.start();
                //  wait for threads to end
                try          {
                                T1.join();
                                T2.join();
                                }              catch(Exception e)
                                                {
                                                System.out.println("Interrupted");l
                                                }
                }
}
(2)          State the difference between Statement and PreparedStatement.

Statements
PreparedStatement
(1)
Statement represents the base statements interface.
PreparedStatement extends the Statement interface.
(2)
In terms of efficiency, it is suitable to use Statement only when we know that we will not need to execute the SQL query multiple times.
In most cases it is more efficient (in the context of multiple executions) to use the PreparedStatement because the SQL statement that is sent gets pre-compiled (i.e. query plan is prepared) in the DBMS.
(3)
With respect to PreparedStatement the Statement doesn't offer support for the parameterized SQL queries, which is an important protection from SQL injection attacks.
With respect to Statement the PreparedStatement does offer support for the parameterized SQL queries.
(4)
Statement would be suitable for the execution of the DDL (Data Definition Language) statements, such as CREATE, ALTER, DROP
We can use PreparedStatement to safely provide values to the SQL parameters, through a range of setter methods (i.e. setInt(int,int), setString(int,Strint), etc.)
(5)
Statement stmt=
Con.createStatement();l
Stmt.executeUpdate("DROP TABLE
PRODUCTS IF EXISTS");
PreparedStatement pstmt=
Con.prepareStatement("UPDATE PRODUCTS
SET PRICE = ? WHERE ID = ?");
Pstmt.setFloat(1, 546, 00f);
Pstmt.setInt(2, 7889);

(3)          State the use of Iterator and ListIterator.
Iterator :
(i)            Iterator in Java is nothing but a traversing object, made specifically for collection objects like list and set.
(ii)           It is used for traversing of collection.
(iii)          Iterator in Java support generics.
(iv)         To remove objects from collection use Iterator's remove method to avoid any CocurrentModificationException.
(v)          We can iterate only in one direction.
(vi)         Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator.
(vii)        We can use Iterator to traverse Set and list and also map type of objects.
(viii)       Which iterator you can check only for next element available or not.
ListIterator :
                (i)            ListIterator can only be used to traverse a list.
                (ii)           We can iterate both the direction.
                (iii)          To obtain the index at any point.
                (iv)         To add a new value at any point.
                (v)          To set a new value at that point.
(vi)         ListIterator can be used to traverse for list type objects, but nor for set type of objects.
                (vii)        With list iterator you can check previous and next element available or not.
(4)          Create the Servlet that returns the server information.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServerInfro extends HttpServlet
{
                protected void service (HttpServletRequest request,
                HttpServletResponse response) throws                ServletException,
                IOException
                {
                                printWriter out=response.getWriter();
                                out.println("The server name is " +request.getServerName() + "<br>");
                                out.println("The server port number is " +request.getServerPort()+ "<br>");
                                out.println("The protocol is" +request.getProtocol()+ "<br>");
                                out.println("The scheme used is" +request.getScheme());
                }
}
(5)          Write a Java using JDBC that inserts student information in student table having structure Stud_rno, Stud_Name, Stud_Per. Also handle user defined exception if user enters rno as Zero.
StudentInformation.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
class WrongInputException extends Exception
{
                WrongInputException(String s)
                {
                                super(s);
                }
}
class Input
{
                void method() throws WrongInputException
                {
                throw new WrongInput Exception ("wrong input!!! Roll No. can't be Zero");
                }
}
public class StudentInformation
{
                public static Connection getConnection() throws Exception
                {
                                String driver = "oracle.jdbc.driver.OracleDriver";
                                String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
                                String username = "name";
                                String password = "password";
                                Class.forName (driver);
                                Connection conn = DriverManager.getConnection(url, username, password);
                                return conn;
                }
public static void main(String args) throws Exception
{
                Connection conn = null;
                PreparedStatement pstmt = null;
                try          {
                                conn = getConnection();
                                String query = "insert into Stud_Info(Stud_rno, Stud_Name, Stud_Per) values(?,?,?)";
                                pstmt = conn.prepareStatement(query);
                                                                                //  create a statement
                                pstmt.setInt(1, 1);                                           //  set input parameter 1
                                pstmt.setString(2, "Stud_Name");           //  set input parameter 2
                                pstmt.setString(3, "Stud_Per");                                //  set input parameter 3
                try          {
                                if(Stud_rno==0)
                                {
                                                new Input().method();
                                }
                }
                catch(WrongInputException wie)
                {
                                System.out.println(wie.getMessage());
                }
                                pstmt.executeUpdate();                              //  execute insert statement
                }              catch (Exception e)
                                {
                                                e.printStackTrace();
                                }              finally    {
                                pstmt.close();
                                conn.close();
                                }
                }
}
Q.3.        Attempt any four :
(1)          Why RMI registry is needed?
Ans :
(2)          Explain the directives and actions in JSP?
Directives :

Action in JSP :
(i)            JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
(ii)           JSP action tags are as follows: jsp:forwards, jsp:include, jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:plugin, jsp:param, jsp:fallback
(iii)          jsp:forward action tag : The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another resource.
                Syntax :
                <jsp:forward page="relativeURL |  <% expression %>"  />
                <jsp:forward page="relativeURL |  <% expression %>"  />
                jsp:include action tag : The jsp include action tag includes the resource at request time so it is better for dynamic pages because there might be changes in future.
                Syntax :
                <jsp:include page="relativeURL  |  <%= expression %>"  />
                jsp:useBean action tage : The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it instantiates the bean.
                Syntax :
                                <jsp:useBean id="instanceName" scope="page | request | session | application"
                                class = "packageName.className" type = "packageName.className"
                                beaName = "packageName.className | <%= expression >" >
                </jsp:useBean>
                jsp:setProperty and jsp:getProperty action tags : The setProperty and getProperty action tags are used for developing web application with Java Bean. In web development, bean class is mostly used because it is a reusable software component that represents data.
                Syntax :
                                <jsp:setProperty name = "instanceofBean" property = "*"  |
                                property = "propertyName" param = "parameterName"  |
                                property = "propertyName" value = "{String | <%= expression %>}"
                                />
                                <jsp:getProperty name "instanceofBean"
                property = "propertyName" />
(3)          What is bean? Explain its advantages?
Ans :
(4)          Write a program to print "Welcome TYBCA" for 20 times on screen. Display the message with delay of one second.   (Use Multithreading).
import java.util.*;
import java.io.*;
class mythread implements Runnable
{
                Thread t;
                public mythread(String title)
                {
                                t = new Thread(this, title);
                                t.start();
                }
                public void run()
                {
                                for(int i=0; i<20; i++)
                                {
                                System.out.println((i+1)+ "ThreadName:" + Thread.currentThread().getName());
                                try
                                {
                                                Thread.sleep(100);
                                }
                                catch(Exception e)
                                {              }
                                }
                }
}
public class mythread
{
                public static void main(String a[])
                {
                                System.out.println("ThreadName:" +Thread.currentThread().getName());
                                mythread mt=new mythread("Welcome TYBCA");
                }
}
(5)          Write a program to read n integers into ArrayList collection. Display the elements of collection in reverse order.
import java.util.*;
import java.io.*;
class Collection
{
                public static void main(String ar[]) throws IOException
                {
                                int n;
                                BufferReader br=new BufferReader(new InputStreamReader(System.in));
                                System.out.println("\t Enter size of arrayList");
                                n=Integer.parseInt(br.readLine());
                                ArrayList <string> a = new ArrayList<String> (n);
                                for(int i=0; i<n; i++)
                                {
                                                System.out.println("Enter element"):
                                                a.add(br.readLine());
                                }
                System.out.println("The contents of arraylist using iterator...");
                Iterator <String> it = a.iterator();l
                while(it.jasNext())
                                System.out.println(" \t " +it.next());
                ListIterator <String> lit = a.listIterator():
                while(lit.hasNext())
                lit.next();
                System.out.println(:The contents of arraylist in reverse order ..... ");
                while(lit.hasPrevious))
                System.out.println(" \t "+lit.previous());
                }
}
Q.4.     Answer the following (any four) :
(1)          How we are creating a Thread? Explain Thread Life Cycle?
Ans : Thread can be created in two way :
                (1)  By implementing a Runnable Interface.
                (2)  By extending a Thread class.
Create Thread by Implementing Runnable Interface :
                If your class is intended to be executed as a thread then you can achieve this by implementing Runnable interface.
Step 1 : As a first step implement a run() method provided by Runnable interface. This method provides entry point for the thread and put complete business logic inside this method.
Syntax of run() method :  public void run()
Step 2 : At second step instantiate a Thread object using the following constructor: Thread (Runnable threadObj,String threadName);
                    Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3 :  Once Thread object is created, start it by calling start() method, which executes a call to run() method.
                Syntax of start() method:  void start();
Create Thread by Extending Thread Class :
                The second way to create a thread is to create a new class that extends Thread class using the following two simple steps.
                This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
Step 1 : Override run() method available in Thread class. This method provides entry point for the thread and put you complete business logic inside this method.
                  Syntax of run() method :  public void run()
Step 2 : Once Thread object is created, start it by calling start() method, which executes a call to run() method.
                Syntax of start() method :  void start();
Thread Life Cycle :

(2)          Explain session tracking using Servlet?
Session Tracking :
HTTP is a 'stateless' protocol : Each time a client retrieves a Web page, the client opens a separate connection to the web server and the server does not automatically maintain contextual information about the client.
Session Tracking can be achieved by using following five method :
(1)          User authorization : Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.
(2)          Hidden fields : These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn't need any special configuration from the browser of server.
                Syntax :  <INPUT TYPE = "hidden" NAME = "technology" VALUE = :servlet">
(3)          URL rewriting :  Original URL : http://server:port/servlet/ServletName
                Rewritten URL : http://server:port/servlet/ServletName?sessionid=74
                When a request is made, additional parameter is appended with the url. Disadvantage is, implementing this type of session tracking is tedious. Doing so, developer needs to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn't clash with other application parameters.
(4)          Cookies :  Cookies are mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
                Syntax : Cookie cookie = new Cookie ("userID", "7456");
                                res. addCookie(cookie);
                Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.
(5)          Session tracking API :  Session tracking API is built on top of the first four methods.
                The servlet container manages the session tracking task and the user need not do it explicitly using the java servlets.
                Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session.
(3)          Differentiate between TreeSet and HashSet?

HashSet
TreeSet
(1)
HashSet stores the object in random order. There is no guarantee that the element we inserted first in the HashSet will be printed first in the output.
Elements are sorted according to the natural ordering of its elements in TreeSet. if the objects cannot be sorted in natural order then compareTo() method to sort the elements of TreeSet object.
(2)
HashSet can store null object while HashSet take constant time performance for the basic operations like add, remove contains and size.
TreeSet does not allow null object.
TreeSet guarantees log(n) time cost for the basic operations (add, remove, contains).
(3)
HashSet is much faste than TreeSet.
TreeSet is slower than HashSet.
(4)
HashSet does not have much functions.
TreeSet is rich in functionality as compare to HashSet. Functions like
pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc. makes TreeSet easier to use than HashSet.
(5)
HashSet uses equals() method for comparison in java.
TreeSet uses compareTo() method for maintaining ordering in java.

(4)          Write the JSP program to calculate the factorial of a given number. Also use Include Directive.
index.jsp
<HTML>
                <body>
<br>
<br>
<center>
                <form action = "fact.jsp">
<h1> Enter the no :: <input type = text name = n> <br> <br>
                <input type = submit value = :Submit"> </h1>
</form>
</center>
</body>
</HTML>
fact.jsp
<html>
                <body> <center>
                <h2>
                <%          int n=0, i;
                                int fact = 1;
                                String ns = request.getParameter("n")l
                                n = Intefer.parseInt(ns);
                                if(n>1)
                                {
                                                fact = 1;
                                                for (i=1: i<=n; i++)
                                                {
                                                                fact = fact*i;
                                                }
                                }
                %>
                </h2> </center>
                </body>
</html>
output.jsp
<html>
                <body> <center>
                <h1> The required Factorial value is :: </h1>
                <% include file = "fact.jsp" %>
                out.println("fact = " +fact);
                </body> </center>
</html>
(5)          What is Jar file? State advantages of Jar file.
JAR File :
                A JAR (Java ARchieve) file is a file that contains the class, image, and sound files for a Java application or applet gathered into a single file and possible compressed.
                When a programmer gets a Java program development kit, a small program or utility called 'jar' is included.
                The jar utility lets the programmer create, list, or extract the individual files from a JAR file.
                In an enterprise, a Java application can be started with a set of JAR files for use during execution.
                An off-the-shelf open source package can be delivered as a JAR file and run with XML data.
                On the Web, a JAR file containing an applet may accompany a Web page.
                By putting the applet components in a single file and compressing that file, download time is saved.
                Ordinarily, a browser user will not need to 'open' or view a JAR file directly.
                It is opened when the Web page is received and the applet is in some manner initiated.
                The JAR format is based on the popular zip file format and is somewhat comparable to the Unix tar file.
Advantages :
(1)          Security : You can digitally sign the contents of a JAR file.
(2)          Decreased download time : For Applets and Java Web Start.
(3)          Compression : Efficient storage.
(4)          Packaging for extensions : Extend JVM (example Java3D)
(5)          Package sealing : Enforce version consistency all classes defined in a package must be found in the same JAR file.
(6)          Package versioning : Hold data like vendor and version information.
(7)          Portability : The mechanism for handling JAR files is a standard part of the Java platform's core API.
Q.5.     Answer the following (any four) :
(1)          Write a note on THread Priorities.
Ans :
(2)          Write a program using JDBC that accepts a table name as a command line argument and display information about all columns from that table.
imoport java.sql connection;
imoport java.sql connectionDriverManager;
imoport java.sql ResultSet;
imoport java.sql Statement;
public class JDBCDemo
{
                public static void main (String[] args)
                {
                                Connection connection = null;
                                Statement createStmt = null;
                                Statement insertStmt = null;
                                Statement selectStmt = null;
                                try
                                {
                                                Class.forName("com.mysql.jdbc.Driver");
                                                connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
                                for (String tblName : args)
                                {              System.out.println(tblName);
                                }
                                createStmt.execute("CREATE Table 'tblName' (ID int(5), FIRST_NAME varchar(25),
                                LAST_Name varchar(25, STAT_CD int(5))");
                                /*           insertStmt = connection.createStatement();
                                                insertStmt.execute("INSERT INTO EMPLOYEE
                                (ID, FIRST_NAME, LAST_NAME, STAT_CD) VALUES
                                (1, 'Lokesh', 'Gupta', 5)");
                                insertStmt.execute("INSERT INTO EMPLOYEE
                                (ID, FIRST_NAME, LAST_NAME, STAT_CD)  VALUES
                                (2, 'howtodoinjava', 'com', 5)");  */
                                selectStmt = connection.createStatement();
                                ResultSet rs = selectStmt.executeQuery ("SELECT ID, FIRST_NAME, LAST_NAME,
                                STAT_CD FROM EMPLOYEE WHERE ID < = 10");
                while(rs.next())
{
                System.out.println(rs.getString(1)); //First Column
                System.out.println(rs.getString(2)); //Second Column
                System.out.println(rs.getString(3)); //Third Column
                System.out.println(rs.getString(4)); //Fourth Column
                }
}
catch (Exception e)
{
                e.printStackTrace();
}  finally                                {
                                try          {
                                                selectStmt.close();
                                                insertStmt.close();
                                                connection.close();
                                }              catch (Exception e)
                                {              e.printStackTrace();
                                }
                }
   }
}
(3)          What is the difference between Array and Collection?

Array
Collection
(1)
Arrays are fixed in size and hence once we created an array we are not allowed to increase or decrease the size based on our requirement.
Collections are growable in nature and hence based on our requirement we can increase or decrease the size.
(2)
Memory point of view it is not recommended to use array.
Memory point of view collections are recommended to use.
(3)
Arrays can hold only homogeneous elements.
Collections can hold both homogeneous and heterogeneous elements.
(5)
Arrays can hold primitive data types as well as objects.
Collection can hold only objects.
(6)
In terms of performance Arrays are better. There is no underiying data structure available so ready made data support is not available.
It terms of performance Collections are slower. For each Collection class there is underlying data structure so upon requirement ready made data support is available for collection.

(4)          Write a servlet that displaying current data and time.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
                *  Servlet implementation class ServletDataTimeDemo
*/
public class ServletDataTimeDemo extends HttpServlet
{
                private station final long serialVersionUID = 1L;
                public void doGet(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException
                {
                                printWriter out = response.getWriter();
                                Date today = new Date();
                                out.println("<html>"+"<body><h1> Today Date and Time is </h1>");
                                out.println("<br>"+today+"</b> </body>" + "</html>");
                }
}
(5)          What are JSP scripting elements? Describe each in brief.
Ans : Following three are JSP scripting elements :
(1)          Expression : The Expression element contains a Java expression that returns a value. This value is then written to the HTML page.
                The Expression tag can contain any expression that is valid according to the Java Language Specification.
                This includes variables, method calls than returns values or any object that contains a toString() method.
                Syntax :  <%= Java expression %>
                For example, the following shows the client host name and the date/time that the page was requested :
                <html>
                <body>
                Your hostname                   :             <& = request.getRemoteHost() %> <br>
                Current time        :             <% = java.util.Date() %>
                </body>
                </html>
(2)          Scriptlet : The scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.
                Within a scriptlet, you can do any of the following :
                Declare variables or methods to use later in the JSP page.
                Write expression valid in the page scripting language.
                Use any of the implicit objects or any object declared with a <jsp:useBean> element.
                Write any other statement valid in the scripting language used in the JSP page.
                For example,
                <HTML>
                <BODY>
                <%
                //  This scriptlet declares and initializes "date" java.util.Date date=new java.util.Date();
                %>
                Hello!  The time is now
                <%
                                out.println( date );
                                out.println(" <BR> Your machine's address is ");
                                out.println( requesr.getRemoteHost() );
                %>
                </BODY>
                </HTML>
(3)          Declaration : Adeclaration can consists of either methods or variables.
                The written JSP turns into a class definition. All the scriptlets written are placed inside a single method of this class.
                User can use declarations to declare one or more variables and methods at the class level of the compiled servlet.
                Syntax :   <%  declaration; [declaration;] + ...... %>
                Declaration must end with a semicolon for example :  <% int i = 0; %>
                For example,
                <% page import = "java.util.*;" %>
                <HTML>
                <BODY>
                <%!
                Date getDate()
                {
                                System.out.println ("In getDate() method");
                                return new Date();
                }
                %>
                Hello! The time is now <%= getDate() %>
                </BODY>
                </HTML>
                A declaration has translation unit scope, so it is valid in the JSP page and any of its static include files.
                The scope of a declaration does not include dynamic resources included with <jsp:include>.

JJJ
Assignment : 2

Q.1.     Attempt the following :  (Any Eight)
(1)          Explain JDBC Statement Class.
Ans : This is used for creating a static sql statement.
                The statement interface is factory of ResultSet, i.e., it provides factory method to get the object of ResultSet.
Commonly used methods of Statement :
(1)          public ResultSet executeQuery (String sql) : is used to execute SELECT query. It returns the object of ResultSet.
(2)          public int executeUpdate (String sql) : is used to execute specified query, it may be create, drop, insert, update, delete etc.
(3)          public boolean execute (String sql) : is used to execute queries that may return multiple results.
(4)          public int[] executeBatch() : is used to execute batch of commands.
(2)          Explain HashSet.
Ans :
(3)          Explain what is Thread?
Ans :
(4)          Explain the syntax of doGet() and doPost() methods.
Ans : There are two principal methods by which a browser interacts with a web server.
(1)          The most common is the GET method, in which the browser simply requests the contents of a particular URL. When the browser uses this method, the web server ends up calling the servlet's doGet() method.
                Syntax :
                public void doGet (HttpServletRequest request, HttpServletResponse response)
                throws IOException
                {
                                response.setContentType("text/html");
                                PrintWriter out = response.getWriter();
                                out.println("<h1>" + message + "</h1>");
                }
(2)          The second is the POST method, in which the browser "sends" data to a particular URL. For example, it may send some data than a user has entered in a form on a web page. In this case, the servlet's doPost() method is called.
                Syntax :
                public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws IOException
                {
                                response.setContentType("text/html");
                                PrintWriter out = response.getWriter();
                                out.println("<h1>" + message + "<h1>");
                }
(5)          Explain what is Cookies.
Ans :
(6)          Explain Stub and Skeleton.
(i)           Stub : It is a java object which resides on the client machine. Its function is to present the same interfaces as the remote server. Remote method calls initiated by the client are directed to the stub.
(ii)          Skeleton : It is a java object that resides on the server machine. It receives requests, performs deserialization and invokes appropriate code on server.
(7)          Explain what UnicastRemote() object?
Ans :
(8)          What is Runnable interface?
(i)            Runnable represent a task in Java which is executed by Thread.
(ii)           java.lang.Runnable is an interface and defines only one method called run().
(iii)          When a Thread is started in Java by using thread.start() method it calls run() method of runnable task which was passed to thread during creation.
(iv)         code written inside run() method is executed by this newly created thread.
(v)          When you call Runnable interface run() method directly, no new thread will be created and task defined inside run() method is executed by calling thread.
(9)          Explain ServletConfig() method.
(i)            ServletConfig is one of the pre-defined interface.
(ii)           ServletConfig object is used for developing flexible servlets.
(iii)          ServletConfig object exist one per servlet program.
(iv)         An object of ServletConfig is created by the container during its initialization phase.
(v)          An object of ServletConfig is available to the servlet during its execution, once the servlet execution is completed, automatically ServletConfig interface object will be removed by the container.
(vi)         An object of ServletConfig interface contains <init-param> details at web.xml, of a particular servlet.
(vii)        The moment we are using an object of ServletConfig, we need to configure the web.xml by writing <init-param> tag under <servlet> tagof web.xml.
(viii)       Whenever compiler executes init() method then the ServletConfig will be created in general.
(ix)         An object of Servlet Config contain the <init-param> data in the form of key, value pairs, here the keys represents init param names and values, which are represented in the web.xml file.
(x)          Syntax to create object of ServletConfig :  ServletConfig conf = getSevletConfig();
(10)        Explain features of JSP.
Ans :
Q.2.     Attempt any four : 
(11)        Explain the life cycle of Thread with suitable example.
Ans :
For Example :
class ThreadDemo implements Runnable  {
                Thread t;
ThreadDemo(String s)  {
t=new Thread(this,s);
t.start();  // Ready to run  }
public void run()  {  // Running state
for(int i=0; i<5; i++)  {
                System.out.println("Thread Name :" +Thread.currentThread().getName());
                try  {
                Thread.sleep(1000);  // Blocked
}  catch (Exception e)  { }
}
}  // Dread state
}
public class RunnableThreadDemo1  {
public static void main(String args[])  {
System.out.println("Thread Name :" +Thread.currentThread().getName());
ThreadDemo m1=new ThreadDemo("My Thread 1");  // New atate
ThreadDemo m2=new ThreadDemo("My Thread 2");
}
}
(2)          Explain PreparedStatement of JDBC with example?
PreparedStatement :
(i)            PreparedStatement in Java is one of the several ways to execute SQL queries using JDBC API.
(ii)           PreparedStatement is a class in java.sql package and allows Java programmer to execute SQL queries by using JDBC package.
(iii)          PreparedStatement object can be created by calling connection.prepareStatement() method.
(iv)         SQL queries passed to this method goes to Database for pre-compilation if JDBC driver supports it. If it doesn't then pre-compilation occurs while executing prepared queries.
(v)          PreparedStatement queries are pre-compiled on database and their access plan will be reused to execute further queries which allows them to execute much quicker than normal queries generated by Statement object.
(vi)         PreparedStatement gives the flexibility of supplying arguments dynamically.
Example :
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class preparedStatementDemo
{
                public static void main(String [] args) throws
                ClassNotFoundException,SQLException
                {
                                // read user entered data
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("Please enter email id : ");
                                String id = scanner.nextLine();
                                System.out.println("User id = "+id);
                                System.out.println("Please enter password to get details : ");
                                String pwd = scaner.nextLine();
                                System.out.println("User password = "+pwd);
                                printUserData(id, pwd);
                }
private static void printUserData(String id, String pwd)
throws ClassNotFoundException, SQLException
{
                Connection con = null;
                PreparedStatement ps = null;
                ResultSet rs = null;
                String query = "select name, country, password from
                Users where email = ? and password = ?";
                try          {
                                con = DBConnection.getConnection();
                                ps = con.prepareStatement(query);
                                // set the parameter
                                ps.setString(1, id);
                                ps.setString(2, pwd);
                                rs = ps.executeQuery();
                                while(rs.next())
                                {
                                                System.out.println("Name = " + rs. getString("name") + ", country = "
                                                + rs.getString("country") +", password = " + rs.getString("password"));
                                }
                }  finally  {
                if(rs != null)
                rs.close();
                ps.close();
                                con.close();
                }
}
(3)          Explain the architecture of RMI with suitable diagram?
RMI Architecture :
                RMI or Java Remote Method Invocation makes Java program available at a machine to do communication with other objects present in other JVMs, address spaces or processes.
                RMI architecture important parts are the skeleton class, stub class and object serialization.
                Stub : It is a java object which resides on the client machine. Its function is to present the same interface as the remote server. Remote method calls initiated by the client are directed to the stub.
                Skeleton : It is a java object that resides on the server machine. It receives request, performs deserialization and invokes appropriate code in the server.
RMI system consists of three layers :
(1)          Stub and Skeleton Layer : Method calls that are created by the client are intercepted. These calls are redirected towards the remote services of RMIL.
(2)          Remote Reference Layer : Connections are set up for the remote address spaces and to manage the connection. Also understands that how to manage and intercept references that are being made from clients, for remote service object.
(3)          Transport Layer : Based on IP/TCP connections in a network, between machines. It provides firewall penetration strategies as well as basic connectivity.
General Architecture Diagram
RMI runtime steps are, as shown in above figure :
Step 1 :   Take start with RMI registry then proceed to the RMI server.
Step 2 :   From RMI registry, remote objects will be looked up by the client process.
Step 3 :   Stub will be returned from server process by the lookup to the client's process.
Step 4 :   On stub, method calls will be invoked by the client process. Skeleton is called by the stub on the server process, via RMI reference manager.
Step 5 :   Actual method call will be executed by the skeleton on the remote object. Result or an exception would be returned to client process through stub and RMI reference manager.
(4)          Write java Program to read n Strings and insert it into ArrayList Collection. Display elements of collection in reverse order.
import java.util.*;
import java.io.*;
class CollectionQ3e
{
                public static void main(String ar[]) throws IOException
                {
                                int n;
                                BufferReader br = new BifferReader (new InputStreamReader(System.in));
                                System.out.println("\t Enter size of arraylist ");
                                n = Integer.parseInt(br.readLine());
                                ArrayList <string> a = new ArrayList <String> (n);
                                for(int i=0; i<n; i++)
                                {
                                                System.out.println(" Enter element ");
                                                a.add(br.readLine());
                                }
                                System.out.println("The contents of arraylist using iterator ... ");
                                Iterator <String> it = a.iterator();
                                while(it.hasNext())
                                System.out.println("\t " +it.next*());
                                ListIterator <String> lit = a.listIterator();
                                while(lit.hasNext())
                                lit.next();
                                System.out.println("The contents of arraylist in reverse order ... ");
                                while(lit.hasPrevious())
                                System.out.println(" \t " +lit.previous());
                }
}
(5)          Write a thread program to display A to Z after every 3 seconds.
import java.util.*;
import java.io.*;
class mythread implements Runnable
{
                Thread t;
                public mythread()
                {
                                t = new Thread(this);
                                t.start();
                }
                public void run()
                {              char ch;
                                for(ch = 'a'; ch <= 'z'; ch++)
                                {
                                                System.out.println(ch);
                                                try
                                                {              Thread.sleep(300);
                                                }
                                                catch (Exception e) { }
                                }
                }
}
public class Alphabets
{
                public static void main(String a[])
                {
                                mythread mt = new mythread();
                                }
}
Q.3.     Attempt any four : 
(1)          What do you mean by Java Beans? Explain its advantages?
Ans :
(2)          Explain Servlet Life Cycle with suitable example?
Ans :
Example :
ServletLifeCycleExample.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycleExample extends HttpServlet
{
                public void init(ServletConfig config) throws ServletException
                {
                                System.out.println("init() method is called");
                }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException IOException
{
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println("service() method called");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{              doGet (request, response);
}
public void destroy()
{              System.out.println("Servlet is destroying .....");
}
}
(3)          How to implement thread with Applet. Explain with example?
Implementation of Thread with Applet : There are five major modification needed to implement thread in applet, viz :
(i)            By changing the signature of applet class to include the words implements Runnable.
                Syntax :
                public class MyAppletClass extends Applet
                implements Runnable {....}
                Here, the Runnable interface defines the behaviour applet which needs to run a thread; in particular, it gives a default definition for the run() method.
(ii)           Include an instance variable to hold the applets thread object.
                Syntax :  Thread objName;
(iii)          Create a start() method that creates a thread and start it running.
                Syntax :
                public void start()
                {
                                if(objName == null)
                                {
                                                objName = new Thread(this);
                                                objName.start();
                                }
}
(iv)         Create a stop() method stops the thread :
                stop() method to suspend execution of the thread and therefore whatever the applet is doing at that time.
                syntax :
                public void stop()
                {
                                if(objName != null)
                                {
                                                objName.stop();
                                                objName = null;
                                }
                }
                Setting the variable to null makes the Thread object it previously contained available for garbage collection so that the applet can be removed from memory after a certain amount of time.
(v)          Create a run() method that contains the actual code that controls the applet.
                syntax :
                public void run()
                {              // what applet actually does
                }
                Here run() method overrides the default version of run(), which is overridden at the time of implementing Runnable interface with applet.
                The run() method is the real heart of applet.
                Example,
                import java.applet.Applet;
                import java.awt.Dimension;
                import java.awt.Font;
                import java.awt.FontMetrics;
                import java.awt.Graphics;
                /*           <applet code = "AppletThreadExample" width = 500 height = 300>
                                </applet>
                */
                public class AppletThreadExample extends Applet implements Runnable
                {
                                int counter;
                                Thread t;
                                public void init()
                                {
                                                counter = 0;
                                                t = new Thread(this);
                                                t.start();
                                }
                public void run()
                {
                                try  {
                                while(true)  {
                                repaint();
                                Thread.sleep(1000);
                                ++counter;
                                }
                }
                catch(Exception e) { }
                public void paint(Graphics g)  {
                g.setFont(new Font("Serif", Font.BOLD,30));
                FontMetrics fm = g.getFontMetrics();
                String s = "" + counter;
                Dimension d = getSize();
                int x = d.width/2 - fm.stringWidth(s)/2;
                g.drawString(s,x,y);
                }
                }
(4)          Write a java program to accept details of employee (eno, ename, sal) from the user through command line and insert into the database.
Employee.java
import java.io.*;
import java.sql.*;
class Employee
{
                static Connection cn;
                public static void main(String args[])
                {
                                int e, k, ds;
                                String str, dn, da;
                                try
                                {
                                                e = Integer.parseInt(args[0]);
                                                dn = args[1];
                                                da = args[2];
                                                ds = Integer.parseInt(args[3]);
                                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                cn = DriverManager.getConnection("jdbc:odbc:Ass","","");
                                Statement st = cn.createStatement();
                                str = "insert into employee values("+e+", '"+dn+"', '"+da+"', "+ds+")";
                                System.out.println(str);
                                k = st.executeUpdate(str);
                                if(k > 0)
                                {              System.out.println("Record is Added");
                                }
                ResultSet rs = st.executeQuery("select * from employee");
                while(rs.next())
                {              System.out.println(rs.getString("eno") + "\t" + rs.getString ("ename") + "\t" +
                                rs.getString ("eadd") + "\t" + rs.getString ("sal"));
                }
}              catch (Exception obj)
                {              System.out.println(obj);
                }
      }
}
(5)          Write a Java program while will generate following thread.
                (i)            To display 10 terms of Fibonacci Series.
                (ii)           To display 1 to 20 in reverse order ....
Fib.java
class Fib extends Thread
{
                int n, i, f, s, l;
                Fib()
                {              System.out.println(this);
                                start();
                }
public void run()
{              try
                {              l = 0;
                                f = 0; s = 1;
                                System.out.println(f + "" +s);
                                i = 3;
                                while (i <= 10)
                                {              l = f + s;
                                                System.out.println(l);
                                                f = s; s = l;
                                                i++;
                                }
                }  catch (Exception e)
                { }
                }
}
Rev.java
class Rev extends Thread
{              int i;
                Rev()
                {              System.out.println(this);
                                start();
                }
                public void run()
                {              for(i=20; i>=1; i--)
                                {              System.out.print(i+ "");
                                }
                }
}
FiboRev.java
class FiboRev
{
                public static void main(String args[])
                {              Rev r = new Rev();
                                Fib f = new Fib();
                }
}
Q.4.     Attempt any four :
(1)          Explain the difference between remote object and local object?
Ans :
(2)          Explain what is Jar file is and write steps to create it.
Ans :
(3)          What are the advantages of Collection Class?
Java Collections framework have following benefits :
(i)           Reduced Development Effort : It comes with almost all common types of collections and useful methods to iterate and manipulate the date. So we can concentrate more on business logic rather than designing our collection APIs.
(ii)          Increased Quality : Using core collection classes that are well tested increases program quality rather than using any home developed data structure.
(ii)           Resuability and Interoperability.
(iv)         Reduce effor : To learn any new API we can use core collection API classes.
(4)          Write Servlet application that will accept user name and password from user, check this user name and password, if user name and password matches then display welcome message else give error message.
UserPass.html
<html>
<body>
<h2 align = "center"> Login Validation </h2>
< form method = "get"
                action = "http://localhost : 8888/abc/Validation">
                Enter User Name <input type = "text" name = "t1">  <br>
                Enter Password <input type = "text" name = "t2">  <br>
<input type = "submit" value = "SEND">
<input type = "reset" value = "CLEAR">
</form>
</body>
</html>
Validation.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Validation extends HttpServlet
{              public void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException
                {              res.serContentType("text/html");
                                PrintWriter out = res.getWriter();
                                // extract the user name and password from req object sent by client
                                String str1 = req.getParameter("t1");
                                String str2 = req.getParameter("t2");
                                // some validation code
                if (str1.equals(str2))
                {              out.println("VALID");
                }
                else
                {              out.println("<b> INVALID </b>");
                }
                out.close();
      }
}
(5)          Write a java Program to accept details of doctor (dno, dname, salar) from the user and insert the database. (Use Prepared Statement)
doctorInformation.java
import java.io.*;
import java.sql.*;
class DoctorInformation
{              static Connection cn;
                static PreparedStatement ps;
                static ResultSet rs;
                static BufferReader br = new BufferReader (new InputStreamReader(System.in));
                public static void main(String args[])
                {              int r, p;
                                String sn;
                                try
                                {              System.out.println("Enter the dno");
                                                r=Interger.parseInt(br.readLine());
                                                System.out.println("Enter the Doctor Name");
                                                sn = br.readLine();
                                                System.out.println("Enter the Salary");
                                                p = Integer.parseInt(br.readLine());
                                                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                cn = DriverManager.getConnection("jdbc:odbc:Ass", "", "");
                String str = "insert into Doc_Info value (?, ?, ?)";
                ps = cn.preparedStatement(strs);
                ps.setInt(1, r);
                ps.setString(2, en);
                ps.setInt(3, p);
                int k = ps.executeUpdate();
                if(k > 0)
                {              System.out.println("Record is Added");
                }
                else
                {              System.out.println("Error");
                }
                }  catch (Exception er)
                {              System.out.println(er);
                }
     }
}
Q.5.     Attempt any four :
(1)          Explain the following terms with suitable syntax.
(i)           Driver Manager :
                The Driver Manager class acts as an interface between user and drivers.
                It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver.
                The Driver Manager class maintains a list of Driver classes that have registered themselves by calling the method.
                DriverManager.registerDriver().
                Methods of DriverManager Class are as follows:
                public static void registerDriver(Driver driver)
                public static void deregisterDriver(Driver driver)
                public static Connection getConnection(String url)
                public static Connection getConnection(String url, String userName, String password)
                Syntax :
                String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
                String USER = "username";
                String PASS = "password"
                Connection conn = DriverManager.getConnection(URL, USER, PASS);
(ii)          Connection :
                A Connection is the session between java application and database.
                The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMeta i.e. 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() etc.
                By default, connection commits the changes after executing queries.
                Method of DriverManager Class are as follows :
                public Statement createStatement()
                public Statement createStatement (int resultSetType, int resultSetConcurrency)
                public void setAutoCommit(boolean status)
                public void commit()
                public void rollback()
                public void close()
                Syntax :
                Connection conn = DriverManager.getConnection (URL, USER, PASS);
(2)          Explain Thread Synchronization with Suitable Example.
Ans :
(3)          Explain the different types of Scripting elements in JSP.
JSP Scripting Elements :
                JSP Scripting allows you to insert Java code into the servlet which is generated from JSP page. These are the forms of scripting elements such as comment, expression, scriptlet, declaration and expression language.
(i)           JSP comment : JSP comments are used to explain the complicated logic code or to mark some region inside a JSP page for later changes. JSP comment is stripped off from the page in the response to the web browser.
                Comments in JSP is declared inside a JSP page as follows :
                <%-- This is a JSP comment ..... one line --%>
                <%-- This is a JSP comment can span in multiple lines --%>
(ii)          Expression : Expression is used to insert values directly to the output. It is the most simple and basic of JSP scripting.
                Syntax :
                <?= expression ?>
                (Note : There is no space between <% and =)
                Example, if you want to print out the current date and time :
                <%= new java.util.Date() %>
                The XML syntax of the JSP expression is as follows :
                <jsp:expression>
                                JAVA Expression
                </jsp:expression>
(iii)         Scriptlet : Scriptlet is similar to the Expression without the equal sign "=". You can insert any plain Java code inside the scriptlet. Scriptlet is not recommended to use anymore as mixing between Java code and HTML is difficult to maintain.
                Syntax :
                <%  // any java source code here %>
                In this example, based on the current time of the day we print the message using scriptlet.
                <% @page contentType = "text/html" pageEncoding = "UTF-8" %>
                "http://www.w5.org/TR/html4/abc.dtd">
                <html>
                                <head>
                                <title> JSP scriptlet </title>
                                </head>
                                <body>
                <%
                // using scriptlet
                java.util.Calendar tm = new java.util.GregorianCalendar();
                String tod = "";
                if (tm.get (now.HOUR_OF_DAY) <12)
                {              tod = "Good Morning!";
                }
                else        if (tm.get (now.HOUR_OF_DAY) <18)
                {              tod = "Good Afternoon!";
                }
                else
                {              tod = "Good Evening!";
                }
                %>
                Good <% = tod %>
                </body>
</html>
                The XML syntax of JSP Scriptlet is as follows :
                <jsp : scriptlet>
                                // Java code of scriptlet
                </jsp : scriptlet>
(iv)         Declaration : To define methods or fields we can use JSP declaration. The JSP declaration is surrounded by the sign <%! and %>. The difference between a variable using declaration and a variable is declared using Scriptlet is that a variable declare using declaration tag is accessible by all the method while a variable declared using Scriptlet is only accessible to the method _jspservice of the generated servlet from JSP page.
                Example , if you want to declare a variable a1, you can use JSP declaration as follows :
                <%! int a1 = 100; %>
                Note : The final semicolon is very important.
                We can also declare a method using declaration tag, such as :
                <%!
                                public boolean isInRange (int a1, int min, int max)
                                {              return a1 >= min && <= max;
                                }
                %>
(4)          Write a java program to read n integer into Linked List and do following operations :
                (i)            Display only negative integers
                (ii)           Delete the last element
Linked ListDemo.java
import java.util.*;
import java.io.*;
public class LinkedListDemo
{              public static void main (String args[])
                {              List l1 = new LinkedList();
                                int i, n, ch;
                                Integer in, neg, del;
                                try
                                {              BufferReader br = new BufferReader(new InputStreamReader (System.in));
                                                System.out.println("Enter the How Many No' s");
                                                n = Integer.parseInt(br.readLine());
                                                for (i=0; i<n; i++)
                                                {
                                                System.out.println("Enter the Integer's");
                                                int m = Integer.parseInt(br.readLine());
                                                in = new Integer(m);
                                                ls.add(in);
                                                }
                                System.out.println("Elements of List Are");
                                System.out.println(ls);
                                do
                {              System.out.println("1.  Negative List");
                                System.out.println("2.  Deletion of last Element");
                                System.out.println("3.  Exit");
                                System.out.println("Enter ur Choice");
                                ch = Integer.parseInt(br.readLine());
                switch(ch)
                {              case 1 :
                                Iterator it = ls.iterator();
                                while (it.hasNext())
                                {              neg = (Integer) it.next();
                                                int nn = neg.intValue();
                                                if (nn < 0)
                                                {              System.out.print(nn + ", ");
                                                }
                                }
                                System.out.println();
                                break;
                                case 2 :
                                del = (Integer) ls.remove(ls.size() - 1)l
                                System.out.println("Deleted Element is " + del);
                                System.out.println("Final List Elements Are");
                                System.out.println(ls);
                                break;
                                case 3 :
                                System.exit(0);
                                }
                }
                while (ch != 3);
}              catch (Exception obj)
                {              System.out.println(lbj);
                }
      }
}
(5)          Write a Java servlet program to display current date and time and also wish according to server time.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/***  Servlet implementation class ServletDateTimeDemo  */
public class ServletDateTimeDemo extends HttpServlet
{              private static final long serialVersionUID = 1L;
                public void doGet (HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
                {              PrintWriter out = response.getWriter();
                                Date today = new Date();
                                out.println("<html>" + "<body><h1> Today Date and Time is </h1>");
                                out.println("<b>" + today + "</b></body>" + "</html>");
                }
}

Ebook

Ebook
Ebook