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

Java Notes 2

Uploaded by

sayyedaman530
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Notes 2

Uploaded by

sayyedaman530
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

2 Marks Questions

a. Differentiate between Iterator and ListIterator.

b. What are different states in lifecycle of Thread?


A thread can be in any of the five following states
i. Newborn State: When a thread object is created a new thread is born and
said to be in Newborn state.
ii. 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.
iii. Running State: It means that the processor has given its time to the thread
for execution
iv. 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.
v. Dead State: A runnable thread enters the Dead or terminated state when it
completes its task or otherwise terminates.
c. 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.
d. Differentiate between ArrayList and Array.

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 socket is an endpoint for communication between two machines.

It is an abstract object that represents a communication channel between two


programs running on different computers.

Sockets are used in a variety of networking applications, including the World


Wide Web, email, and file sharing.

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:

To create the server application, we need to create the instance of ServerSocket


class.
Here, we are using 6666 port number for the communication between the client
and server.
Syntax:

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes connection and waits for the client

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:

Socket s=new Socket("localhost",6666);


b) Explain thread life cycle with suitable diagram.

A thread can be in any of the five following states:


Newborn State: When a thread object is created a new thread is born and said to
be in Newborn state.

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?

Type-1: JDBC-ODBC Bridge Driver

i. JDBC-ODBC converts JDBC calls to ODBC calls and give it to ODBC


Driver.
ii. ODBC Driver interconverts the calls to native calls of the DB API.
iii. Then Native calls will be understood by Vendor DB Library and then
Vendor DB Library will interconvert calls to Vendor specific DB protocol.

Type-2: Native API Driver

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.

Middleware converts JDBC calls to Vendor specific DB Protocol

Type-4: Thin Driver

It converts JDBC calls directly to vendor specific DB protocol.

It is fastest Driver because it has minimum layer of communication.


d) What is Thread? How to set Priority to the thread?

• A thread in Java is a lightweight sub-process that runs concurrently with


other threads.
• Threads can be used to improve the performance of an application by
allowing multiple tasks to be executed at the same time.
• Java assigns priority to every thread.
• By default all threads have their own priorities. But by providing
priorities we force a thread to given respect other.
• Thread priority is an integer from 1 to 10. Where 1 is the minimum
priority and 10 is the maximum.
• Priorities are integer values from 1(lowest priority given by the constant
Thread.MIN_PRIORITY) to 10(higher priority given by the constant
Thread.MAX_PRIORITY).
The default priority is 5 (Thread.NORM_PRIORITY).

e) What is difference between execute( ), execute Query( )and execute


Update( ) ?

• 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 program to demonstrate the

// Sorted Set import

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");

// Displaying the TreeSet


System.out.println(ts);

// Removing items from TreeSet

// using remove()

ts.remove("Australia");

System.out.println("Set after removing "


+ "Australia:" + ts);

// Iterating over Tree set items


System.out.println("Iterating over set:");

Iterator<String> i = ts.iterator();

while (i.hasNext())

System.out.println(i.next());
}
}
g) Explain the difference between TCP/IP and UDP.

h) Explain difference between Statements and Prepared Statement.


4 Marks Questions

a. What are the benefits of the Spring Framework?


The Spring Framework is a lightweight framework that can help speed up
application development and testing by removing complexities associated with
Java programming.
Here are some benefits of the Spring Framework:
Dependency injection (DI): This feature allows developers to inject
dependencies into their code at runtime, making it easier to write flexible and
loosely coupled code. This makes code easier to maintain and test.

Inversion of control: This principle states that objects do not depend on other
objects, but have knowledge about their abstractions for further interaction.

Loose coupling: Spring applications are loosely coupled because of DI.


Secure configurations: Spring Boot enables developers to build robust
applications having secure as well as clear configurations without losing much
time and effort.

Fast delivery: Spring Framework provides a fast startup and shutdown.

b. Explain JDBC Architecture in detail.


The JDBC API supports both two-tier and three-tier processing models for
database access but in general JDBC Architecture consists of two layers:

1) JDBC API:

This provides the application-to-JDBC Manager connection.

2) JDBC Driver API:

This supports the JDBC Manager-to-Driver Connection.

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.

c. Differentiate between List and Set interface.

d. Describe the life cycle of servlet.


The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
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
}
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 socket is an endpoint for communication between two machines.

It is an abstract object that represents a communication channel between two


programs running on different computers.

Sockets are used in a variety of networking applications, including the World


Wide Web, email, and file sharing.

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:

To create the server application, we need to create the instance of


ServerSocket class.

Here, we are using 6666 port number for the communication between the
client and server.

Syntax:

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes connection and waits for the client

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:

Socket s=new Socket("localhost",6666);


Example:

MyServer.java import java.io.*;

import java.net.*; public class

MyServer { public static void

main(String[] args){ try{

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

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

java.net.*; public class MyClient

{ public static void main(String[]

args) { try{

Socket s=new Socket("localhost",6666);

DataOutputStream dout=new

DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello

Server"); dout.flush(); dout.close();

s.close();
}catch(Exception e){System.out.println(e);}

g. Explain different ways to create Thread.

There are two ways to create a thread:

By extending Thread class

By implementing Runnable interface.

Extending Thread class**


To create a thread by extending the Thread class, you need to create a new class
that extends the Thread class and override the run() method. The run() method
contains the code that the thread will execute.

Implementing Runnable interface**

To create a thread by implementing the Runnable interface, you need to create a


new class that implements the Runnable interface and override the run()
method. The run() method contains the code that the thread will execute.

h. Explain thread synchronization with suitable example.

Synchronization is the way to avoid data corruption caused by simultaneous


access to the same data. As we know all threads shares the same memory
space,it is also possible that they can share same variables or same object at
same time.

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.

The property of a thread to execute in parallel with the application’s main


thread or with other threads is the main feature of the java concurrent
programming. But this property causes usually a lot of trouble for
programmers which must assure a correct sharing of the resources used in
common by different threads.

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.

i. Short note on Set Interface


The Set interface in Java is a collection that can't contain duplicate elements. It
models the mathematical set abstraction. The Set interface contains methods
inherited from Collection and adds the restriction that duplicate elements are
prohibited.
The Java platform contains three general-purpose Set implementations:
HashSet: Stores its elements in a hash table
TreeSet
LinkedHashSet
The Set interface also allows for basic mathematical set operations like union,
intersection, and subset.
Here are some methods of the Set interface:
add(E e): Adds the specified element to this set if it is not already present.
addAll(Collection<? extends E> c): Adds all of the elements in the specified
collection to this set if they're not already present.
The Set interface is a member of the Java Collections Framework. j.
Explain JDBC Drivers with a suitable diagram
Type-1: JDBC-ODBC Bridge Driver iv. JDBC-ODBC converts JDBC calls to

ODBC calls and give it to ODBC

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.

Type-2: Native API Driver

Native API Driver converts JDBC calls to native calls of the DB API

Advantage:

performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

The Native driver needs to be installed on the each client machine.

The Vendor client library needs to be installed on client machine.


Type-3: Network Protocol Driver

This Driver does not directly converts JDBC call,it uses a middleware between
the calling program and Database.

Middleware converts JDBC calls to Vendor specific DB Protocol

Advantage:

No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.

Disadvantages:

1.Network support is required on client machine.

2.Requires database-specific coding to be done in the middle tier.

3.Maintenance of Network Protocol driver becomes costly because it requires


database-specific coding to be done in the middle tier.
Type-4: Thin Driver

It converts JDBC calls directly to vendor specific DB protocol.

It is fastest Driver because it has minimum layer of communication.

Advantage:

Better performance than all other drivers.

No software is required at client side or server side.

Disadvantage:

Drivers depend on the Database.


k. Explain in detail JSP tags with example.
JSP tags are used to insert Java code into HTML pages. They are markup that is
surrounded by angle brackets, and create a container for Java code. This
separates dynamic content from static design elements on your site.
• Directive tags: Provide general information about the JSP page to the JSP
engine
• Declaration tags: Declare and define variables and methods that can be used
in the JSP page
• Scriptlet tags: Embed Java code fragments in the JSP page • Expression tags:
Print values in the output HTML in a JSP page
l. Explain in detail the following components of JSP.
i. JSP Directives.
The include directive is used to include the contents of any resource it may
be jsp file, html
file or text file. The include directive includes the original content of the
included resource at
page translation time (the jsp page is translated only once so it will be
better to include static resource).
Advantage of Include directive
Code Reusability

ii. JSP Tags.


• Declaration Tags:
This Tag is used for declare the variables. Along with this, Declaration Tag can
also declare method and classes. Jsp initializer scans the code and find the
declaration tag and initialize all the variables, methods and classes. JSP
container keeps this code outside of the service method
(_JSPService()) to make them class level variables and methods.
• Scriptlet Tag
Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag
implements the _jspService method functionality by writing script/java
code.
• expression tag

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

Connection-oriented and connection-less protocol

Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 .


It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For


example:

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

MAC (Media Access Control) Address is a unique identifier of NIC (Network


Interface Controller).
A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it


is reliable but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver.


So it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communication. n.


Explain the life cycle of servlet. Give example
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.

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
}

o. State purpose of:


i. Statement
The statement object is used to execute the query against the database.
Connection interface acts as a factory for statement object. A statement object
can be any one of the Statement, CallableStatement, and PreparedStatement
types .To create a statement object we have to call createStatement() method
of Connection interface. Connection interface also provides the transaction
management methods like commit() and rollback() etc.
Syntax:
Statement stmt=conn.createStatement(); ii.
Connection
Second step is to open a database connection. DriverManager class provides
the facility to create a connection between a database and the appropriate
driver. To open a database connection we can call getConnection() method of
DriverManager class.
Syntax:
Connection connection = DriverManager.getConnection(url, user, password)
iii. ResultSet
Statement interface provides the methods to execute a statement.
To execute a statement for select query use below:
Syntax:
ResultSet rs = stmt.executeQuery(selectQuery); iv.
DriverManager
Second step is to open a database connection. DriverManager class provides
the facility to create a connection between a database and the appropriate
driver. To open a database connection we can call getConnection() method of
DriverManager class.
Syntax:
Connection connection = DriverManager.getConnection(url, user, password) To
create a connection with Oracle database:
Syntax:
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","p
assword");
To load or register MS-Access Driver class:
Syntax:
Connection conn=DriverManager.getConnection(“jdbc:odbc:DBSourceName”);

Programs

1. Write a java program to display IP Address and Name of client


machine. import java.net.*;

public class ClientInfo {


public static void main(String[] args) throws UnknownHostException {
InetAddress i = InetAddress.getLocalHost();
System.out.println(i);
System.out.println("IP Address:" + i.getHostAddress() + "\nName:" +
i.getHostName());
}
}

2. Write a java program to display “Hello Java” message n times

on the screen. (Use Runnable Interface)

import java.util.*;

class Slip4_1 implements Runnable {


int i, no;

Slip4_1(int n)// 5
{
no = n;// no=5

public void run() {


for (i = 1; i <= no; i++) {
System.out.println("\nHello Java");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println(e);
}
}
}

public static void main(String args[]) {


Scanner s = new Scanner(System.in);
System.out.println("Enter How many times to display message");
int n = s.nextInt();
Slip4_1 s4 = new Slip4_1(n);// 5
Thread t = new Thread(s4);
t.start();
}
}

3. Write a JDBC program to count the number of records in table.


(Without using standard method).

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);
}}
}

4. Write a java program which will display name and priority of


current thread. Change name of Thread to MyThread and set the
priority to 2 and display it on screen. public class Slip26_1{
public static void main(String[] args) {
// Creating a thread to display alphabets after 3 seconds
Thread displayThread = new Thread(() -> { try {
Thread.sleep(3000); // Wait for 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

// Displaying alphabets from A to Z


for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
}
});

// Start the display thread


displayThread.start();
try
{
// Wait for the display thread to finish before exiting the main thread
displayThread.join();

} 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();
}
}

6. Write a JSP program to check whether given number is Armstrong or


not.
<!DOCTYPE html>
<html>
<head>
<title><</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="Slip28.jsp" method="post"> Enter
Number :
<input type="text" name="num">
<input type="submit" value="submit">
</form>
</body>
</html>

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");
}
%>

7. Write a java program to create a Mobile (Model_No,


Company_Name, Price, Color) table.
importjava.sql.*; class
Slip13_1
{
public static void main(String a[]) try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","
system","system");
Statement st=con.createStatement();if(con==null)
{
System.out.println("Connection Failed");
System.exit(1);
}
System.out.println("Connection Established....");
stmt=con.createStatement(); String sql="create
table
mobile"+"(Model_Noint,"+"Company_Namevarchar(20),"+"price
float(6,2),"+"color varchar(20))"; stmt.executeUpdate(sql);
System.out.println("Table Created sucessfully..."); con.close();
}
catch(Exception e)
{
System.out.println(e);
}}
}
8. Write a JDBC program to delete the records of employees whose
names are starts with ‘A’ character.

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">

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");
}
%>

You might also like