Java Notes 2
Java Notes 2
e. What is Thread?
i. A thread in Java is a lightweight sub-process that runs concurrently with
other threads.
ii. Threads can be used to improve the performance of an application by
allowing multiple tasks to be executed at the same time.
iii. Threads are created by extending the Thread class or implementing the
Runnable interface.
iv. When a thread is created, it is in the new state.
v. To start a thread, the start() method is called. The run() method is the
entry point for the thread and it contains the code that the thread will
execute.
f. What is accept() method in networking?
i. The accept() method is a system call that is used by a server to accept a
connection request from a client.
ii. When a client connects to a server, the server creates a new socket for the
connection and then calls the accept() method to accept the connection.
iii. The accept() method returns a new socket object that represents the
connection.
g. What are common JDBC Exceptions?
i. In Java Database Connectivity (JDBC), exceptions are used to handle errors
that may occur during database operations.
ii. Some common JDBC exceptions include:
• SQLException
• SQLTimeoutException
• SQLIntegrityConstraintViolationException
• SQLDataException
• SQLSyntaxErrorException:
h. Mention the Implicit Objects in a JSP.
i. Implicit objects are predefined objects that are available to the JSP page.
ii. They are created by the JSP container automatically and are ready for use
in the JSP page.
iii. There are nine implicit objects in JSP:
• out: This object is used to print the output to the console.
• request: This object is used to access the HTTP request object.
• response: This object is used to access the HTTP response object.
• session: This object is used to access the HTTP session object.
• application: This object is used to access the ServletContext object.
• pageContext: This object is used to access the JSP page context.
• config: This object is used to access the ServletConfig object.
• exception: This object is used to access the exception object.
• page: This object is used to access the current JSP page object.
i. What is the difference between Process and Thread?
j. What is socket ?
i. A socket in Java is an endpoint of a two-way communication link
between two programs running on the network.
ii. It is an abstract class that provides a way for applications to connect to
each other over a network.
iii. Sockets are used in a variety of applications, including web servers, email
clients, and file transfer programs.
iv. They are also used in many other types of applications, such as chat
programs, online games, and distributed computing systems.
k. What is hibernate?
i. Hibernate is an open-source, lightweight, object-relational mapping (ORM)
tool for Java that maps Java classes to database tables.
ii. It provides an abstraction layer between the application and the database,
taking care of boilerplate code and resource management.
iii. Hibernate also provides a query language (HQL) that's similar to SQL.
l. What is the use of forName() method ?
Java provides forName() method to dynamically load the driver class.
m. What is use of accept ( ) method?
i. The accept() method in Java is used to accept a connection request
from a client.
ii. It is a method of the ServerSocket class.
iii. The accept() method blocks until a connection is made, and then
returns a Socket object representing the connection.
iv. The accept() method takes one argument, which is a ServerSocket
object. The ServerSocket object represents the server that is listening
for connections.
n. What is JSP?
i. JSP stands for Java Servlet Pages, a server-side scripting language
that allows developers to create dynamic web pages based on HTML,
XML, or other types. ii. JSP files contain HTML, along with
embedded JSP tags that contain snippets of Java code.
iii. JSP is an advanced version of Servlet Technology and is easier to
maintain because it doesn't require recompilation or redeployment,
requires less coding, and has access to the entire Java API.
o. What is the role of Prepared Statement?
i. The PreparedStatement interface extends the Statement interface which
gives you added functionality with a couple of advantages over a generic
Statement object.
ii. This statement gives you the flexibility of supplying arguments
dynamically.
p. What is spring?
i. Spring is a Framework designed by Rod Johnson in 2003.
ii. It is light weighted, Open source framework use for develop the any type
of application like web application, database application, Console
application etc.
iii. We use the Spring because it has ability to works with any type of
application, it provides the loose coupling and provides the dependency
injection etc.
5 Marks Questions
a) Explain the concept of Socket and Server Socket with suitable syntax.
Give example.
A server socket is a type of socket that is used by servers to listen for and accept
incoming connections from clients.
When a client connects to a server socket, a new socket is created to handle the
communication between the two programs.
Creating Server:
Creating Client:
To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port
number.
Here, we are using "localhost" because our server is running on same system.
Syntax:
Runnable State: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor. If all threads in queue
are of same priority then they are given time slots for execution.
Running State: It means that the processor has given its time to the thread for
Execution.
Blocked State: If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.
Dead State: A runnable thread enters the Dead or terminated state when it
completes its task or otherwise terminates.
c) What are different types of JDBC Drivers?
Native API Driver converts JDBC calls to native calls of the DB API
Type-3: Network Protocol Driver
This Driver does not directly converts JDBC call,it uses a middleware between
the calling program and Database.
• execute(String SQL) :
Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.
• executeUpdate(String SQL):
Returns the numbers of rows affected by the execution of the SQL
statement. Use this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT, UPDATE, or
DELETE statement.
• executeQuery(String SQL):
Returns a ResultSet object. Use this method when you expect to get a result
set, as you would with a SELECT statement.
f) Explain the SortedSet Interface with example.
The SortedSet interface present in java.util package extends the Set interface
present in the collection framework. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Set
interface and adds a feature that stores all the elements in this interface to be
stored in a sorted manner.
java.util.*;
class SortedSetExample{
public static void main(String[] args)
{
SortedSet<String> ts
= new TreeSet<String>();
ts.add("India");
ts.add("Australia");
ts.add("South Africa");
ts.add("India");
// using remove()
ts.remove("Australia");
Iterator<String> i = ts.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
g) Explain the difference between TCP/IP and UDP.
Inversion of control: This principle states that objects do not depend on other
objects, but have knowledge about their abstractions for further interaction.
1) JDBC API:
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager
ensures that the correct driver is used to access each data source. The driver
manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases. Diagram above is the architectural diagram,
which shows the location of the driver manager with respect to the JDBC
drivers and the Java application.
Whenever request is made by client browser, then servlet container calls the
service() method.
Work of service() method is to handle requests coming from client.
Service() method checks the HTTP request type like get,post and calls the
doGet(),doPost()
Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
3.destroy method is invoked
The web container calls the destroy method before removing the servlet instance
from the service. (only calls once at the end of servlet life cycle)
It gives the servlet an opportunity to clean up any resource for example memory,
thread etc
The syntax of the destroy method of the Servlet interface is given below: public
void destroy()
{
//cleanup code
}
e. Short note on Session Tracking.
• Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
• Http protocol is a stateless so we need to maintain state using session
tracking techniques.
• Each time user requests to the server, server treats the request as the new
request.
• So we need to maintain the state of an user to recognize to particular user.
Session Tracking Techniques There are four techniques used in Session
tracking:
Cookies
Hidden Form Field
URL Rewriting
User authorization
HttpSession
f. Explain Socket and Server Socket.
A server socket is a type of socket that is used by servers to listen for and
accept incoming connections from clients.
Creating Server:
Here, we are using 6666 port number for the communication between the
client and server.
Syntax:
Creating Client:
Syntax:
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
MyClient.java import java.io.*; import
args) { try{
DataOutputStream dout=new
DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello
s.close();
}catch(Exception e){System.out.println(e);}
Because of this we may get problems such as threads may race each other or
one thread may overwrite the data just written by another thread.
It means that two or more threads accessing the same data simultaneously may
lead to loss of data integrity.
For example, if two people access the same saving account,it is possible that one
person
may overdraw and cheque may bounce.
Here, we should ensure that the resources will be used by only one thread.The
process using which we achieve this is called synchronization.
It means that the threads that execute in parallel and use common critical
resources must be synchronized at some points to assure a correct
functioning of the system.The fragments of program code which perform
such operations are called critical sections.
In this context the synchronization means that a thread must wait for another
thread to
leave the critical section, if it has already entered this section, and to enter into
this section using some security measures.
Driver.
v. ODBC Driver interconverts the calls to native calls of the DB API.
vi. Then Native calls will be understood by Vendor DB Library and then Vendor
DB Library will interconvert calls to Vendor specific DB protocol.
Advantages: iii.
Easy to use.
iv. Can be
easily connected
to any database.
Disadvantages:
iii. Performance degraded because JDBC method call is converted into the
ODBC function calls.
iv. The ODBC driver needs to be installed on the client machine.
Native API Driver converts JDBC calls to native calls of the DB API
Advantage:
Disadvantage:
This Driver does not directly converts JDBC call,it uses a middleware between
the calling program and Database.
Advantage:
No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
Advantage:
Disadvantage:
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print
the values of variable or method. iii. Scripting Elements.
Java Server Page (JSP) is a technology for controlling the content or appearance
of Web pages through the use of servlets. Small programs that are specified in
the Web page and run on the Web server to modify the Web page before it is
sent to the user who requested it. There are total three Scripting Element in JSP
Scriptlet tag
Expression tag
Declaration tag
This tag allow user to insert java code in JSP. The statement which is written
will be moved to jspservice() using JSP container while generating servlet from
JSP. When client make a request, JSP service method is invoked and after that
the content which is written inside the scriptlet tag executes.
Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is
used for writing your content on the client-side. We can use this tag for
displaying information on the client’s browser. The JSP Expression tag
transforms the code into an expression statement that converts into a value in
the form of a string object and inserts into the implicit output object.
Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is
used for writing your content on the client-side. We can use this tag for
displaying information on the client’s browser. The JSP Expression tag
transforms the code into an expression statement that converts into a value in
the form of a string object and inserts into the implicit output object. m. Short
note on Networking Terminology.
The widely used Java networking terminologies used are as follows:
IP Address
Protocol
Port Number
MAC Address
Socket
1) IP Address
2) Protocol
TCP
FTP
Telnet
SMTP
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between
two applications.
4) MAC Address
6) Socket
As displayed in the above diagram, there are three states of a servlet: new(init),
ready(service) and end(destroy).
The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state.
In the ready state, servlet performs all the tasks. When the web container
invokes the destroy() method, it shifts to the end state.
1.init method is invoked init() method is called only once when servlet is
created(after creating object of servlet class) same like applet. The init method
is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface.
Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
2.service method is invoked
It is main method of servlet that performs actual task.
Whenever request is made by client browser, then servlet container calls the
service() method.
Work of service() method is to handle requests coming from client.
Service() method checks the HTTP request type like get,post and calls the
doGet(),doPost()
Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
3.destroy method is invoked
The web container calls the destroy method before removing the servlet instance
from the service. (only calls once at the end of servlet life cycle)
It gives the servlet an opportunity to clean up any resource for example memory,
thread etc
The syntax of the destroy method of the Servlet interface is given below: public
void destroy()
{
//cleanup code
}
Programs
import java.util.*;
Slip4_1(int n)// 5
{
no = n;// no=5
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DisplayAll {
public static void main(String[] args) { try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","system");
Statement st=con.createStatement();//query to count all records from table
employee
String q="Select COUNT(*) from employees";
//to execute query
ResultSet rs=smt.executeQuery(q);
//to print the resultset on console
System.out.println(rs); cn.close();
}
catch(Exception e)
{
System.out.println(e);
}}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\nAlphabets displayed!");
}
}
5. Write a java program to display all the alphabets from ‘A’ to ‘Z’
after every 3 seconds.
public class Slip26_1 extends Thread
{ char c; public
void run()
{
for(c = 'A'; c<='Z';c++)
{
System.out.println(""+c);
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
}}
public static void main(String args[])
{
Slip26_1 t = new Slip26_1();
t.start();
}
}
JSP FILE:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
intnum = Integer.parseInt(request.getParameter("num"));
int n = num; intrem,no = 0; while(n!=0)
{
rem = n%10;
no = no+rem*rem*rem; n
= n/10;
}
if(no == num)
{
out.println("\nArmstrong Number");
}
else
{
out.println("Not Armstrong");
}
%>
import java.sql.*;
import java.util.*; public
class Slip8_1
{
public static void main(String args[])
{ tr
y{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","system");
Statement st=con.createStatement();
PreparedStatement ps=con.prepareStatement("insert into employee
values(?,?,?,?)");
Scanner s=new Scanner(System.in);
System.out.println("how many values u wanna insert?");
int n=s.nextInt(); for(int i=1;i<=n;i++)
{
System.out.println("eno"); int
eno=s.nextInt();
System.out.println("ename");
String ename=s.next();
System.out.println("dept");
String dept=s.next();
System.out.println("sal"); int
sal=s.nextInt();
ps.setInt(1,eno);
ps.setString(2,ename);
ps.setString(3,dept);
ps.setInt(4,sal);
ps.executeUpdate();
}
String str="delete * from employee where ename='a%' ";
ResultSet rs=st.executeQuery(str);
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}
con.close();
}
catch(Exception e){}
}
}
9. Write a JSP program to accept Name and Age of Voter and check
whether he 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">
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");
}
%>