Advanced - Java - Lab Manual (Updated) 31.05.2022
Advanced - Java - Lab Manual (Updated) 31.05.2022
Advanced - Java - Lab Manual (Updated) 31.05.2022
ENGINEERING(DATA SCIENCE)
IV SEMESTER
ACADEMIC YEAR 2021-22 [EVEN]
NAM E OF THE
:
STUDENT
BRANCH :
BATCH :
Advanced Java Programming Lab [MVJ20CDL48]
Institute Vision
To become an institute of academic excellence with international standards.
Institute Mission
Impart quality education along with industry exposure.
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Educational Objectives (PEOs):
IT Proficiency: Graduates will excel as IT Experts with extensive knowledge to analyze and design
solutions to Information Engineering problems.
Social &moral principles: Graduates will work in a team, showcase professionalism; ethical values
expose themselves to current trends and become responsible Engineers.
Higher education: Graduates will pursue higher studies with the sound knowledge of fundamental
Understanding of Eclipse
Operating System:
Windows
CONTENTS
Sl.No. Title of Experiment
1 Write a java program on Network Programming i.e Client - Server Programming.
12. Program to demonstrate prints the different parts of a URL specified as a command line argument.
Implementation:
To connect to another machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port. The
java.net.Socket class represents a Socket. To open a socket:
The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code
will run on the single stand-alone machine).
The second argument – TCP Port. (Just a number representing which application to run on a
server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the
data.
The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until “Stop”
is typed.
PROGRAM
package networkprograms;
import java.net.*;
import java.io.*;
// establish a connection
try
System.out.println("Connected");
catch(UnknownHostException u)
System.out.println(u);
catch(IOException i)
System.out.println(i);
while (!line.equals("Stop"))
try
line = input.readLine();
out.writeUTF(line);
catch(IOException i)
System.out.println(i);
try
input.close();
out.close();
socket.close();
catch(IOException i)
System.out.println(i);
package networkprograms;
import java.net.*;
public class Server
try
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
while (!line.equals("Stop"))
try
line = in.readUTF();
System.out.println(line);
catch(IOException i)
System.out.println(i);
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
catch(IOException i)
System.out.println(i);
}
Output: First compile the Server, Client programs
And Run Server first
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.
We create a class that extends the java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
Dept. of CSE(Data Science), MVJCE Page 13 2021-22
Advanced Java Programming Lab [MVJ20CDL48]
// Main Class
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
} */
We create a new class which implements java.lang.Runnable interface and override run() method. Then
we instantiate a Thread object and call start() method on this object.
PROGRAM-
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
object.start();
OUTPUT-
EXPERIMENT 3: Write a java program to create a New Data Source for Ms Access.
Introduction
In this article, we make a connection using JDBC to a Microsoft Access database. This
connection is made with the help of a JdbcOdbc driver. You need to use the following steps for
making a connection to the database.
Creating a Database
Step 1: Open Microsoft Access and select Blank database option and give the database name
as File name option
Step 2: Create a table and insert your data into the table
Step 3: Save the table with the desired name; in this article, we save the following records with
the table name student.
Step 4: Open your Control Panel and then select Administrative Tools.
Step 6: Now click on add option for making a new DSN.select Microsoft Access Driver (*.mdb.
*.accdb) and then click on Finish
Step 7: Make your desired Data Source Name and then click on the Select option, for example in
this article we use the name mydsn
Step 8: Now you select your data source file for storing it and then click ok and then click
on Create and Finish
Add the access database and select the path of data base with data source.
package msaccessprogram3pack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
String id = rs.getString(1) ;
String address=rs.getString(3);
System.out.println(id + fname);
catch(Exception err)
System.out.println(err);
OUTPUT:
FILE STRUCURE
EXPERIMENT 4: Write a java program to show connectivity with data base using JDBC/ODBC
Driver
Commit;
Create java project, create a package. And write Myjdbc.java class file
Myjdbc.java
package jdbcpack;
import java.sql.*;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE","kalyani","kalyani");
Statement stmt=con.createStatement();
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
EXPERIMENT 5: Write a java program to get Information about data base using Data
base Metadata
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc.
Commonly used methods of DatabaseMetaData interface
public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the version number of the
JDBC driver.
public String getUserName()throws SQLException: it returns the username of the database.
public String getDatabaseProductName()throws SQLException: it returns the product name of
the database.
public String getDatabaseProductVersion()throws SQLException: it returns the product version
of the database.
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
PROGRAM-
package jdbcpack;
import java.sql.*;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE","kalyani","kalyani");
Dept. of CSE(Data Science), MVJCE Page 25 2021-22
Advanced Java Programming Lab [MVJ20CDL48]
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"VIEW"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
con.close();
catch(Exception e)
System.out.println("Exception"+e);
}
OUTPUT:
EXPERIMENT 6: Write a java program to get Information about particular table using Result
Set Meta Data.
The metadata means data about data i.e. we can get further information from the data.If you have to get
metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface
is useful because it provides methods to get metadata from the ResultSet object.Commonly used methods of
ResultSetMetaData interface
MethodDescription:
public int getColumnCount()throws SQLExceptionit returns the total number of columns in the ResultSet
object.
public String getColumnName(int index)throws SQLExceptionit returns the column name of the specified
column index.
public String getColumnTypeName(int index)throws SQLExceptionit returns the column type name for the
specified index.
public String getTableName(int index)throws SQLExceptionit returns the table name for the specified column
index.
How to get the object of ResultSetMetaData:The getMetaData() method of ResultSet interface returns the
object of ResultSetMetaData.
Syntax:
package jdbcpack;
import java.sql.*;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
con.close();
OUTPUT:
package swingspack;
import javax.swing.*;
import java.awt.*;
//(JFrame/JApplet) to be used
JTextField txtName,txtPass;
JButton cmdOk,cmdCancel;
public SwingExample()
txtName=new JTextField(10);
cmdCancel=new JButton("Cancel");
//Step 5 – Add all the objects in the Content Pane with Layout
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(lblName); con.add(txtName);
con.add(lblPass); con.add(txtPass);
con.add(cmdOk); con.add(cmdCancel);
}//constructor
//here)
l.setSize(150,200);
l.setVisible(true);
}//main
}//class
OUTPUT-
Java Remote Method Invocation (RMI) is an object-oriented Remote Procedure Call (RPC)
technique. It allows us to invoke methods on an object that exists in a different address space.
Application components
Server
This is a program that typically creates a remote object to be used for method invocation. This object is
an ordinary object except that its class implements a Java RMI interface. Upon creation, the object is
exported and registered with a separate application called object registry (or simply registry).
Client : A client program typically consults the object registry to get a reference (handle) to a remote
object with a specified name. It can then invoke methods on the remote object using this reference
(handle) as if the object is stored in the client’s own address space. The RMI handles the details of
communication (using sockets) between the client and the server and passes information back and forth.
Note that this complex communication procedure is absolutely hidden to the client and server applications.
Object Registry
It is essentially a table of objects. Each entry of the table maps the object name to its proxy known as
stub.
Basic Steps
We then write a concrete class implementing one or more such remote interfaces
Implementing a server application that creates an instance of the remote object and registers it to the RMI
registry with a name is called object deployment.
bA client application gets a handle to this remote object and invokes methods on it.
First, start an object registry. In Java, the object registry is started using the application rmiregistry.
RMI Architecture
An Application:
SERVER_HOME FOLDER:
//Calculator.java
import java.rmi.*;
public interface Calculator extends Remote {
public int add(int a, int b) throws RemoteException;
}
//SimpleCalculator.java
import java.rmi.*;
public class SimpleCalculator implements Calculator {
public int add(int a, int b) {
System.out.println("Received: " + a + "and" + b);
int result = a + b;
Dept. of CSE(Data Science), MVJCE Page 34 2021-22
Advanced Java Programming Lab [MVJ20CDL48]
//CalculatorServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class CalculatorServer {
public static void main(String args[]) {
try {
SimpleCalculator cal = new SimpleCalculator();
Calculator stub = (Calculator)UnicastRemoteObject.exportObject(cal,0);
Registry registry = LocateRegistry.getRegistry();
String name = "calculator";
registry.rebind(name, stub);
System.out.println("Calculator server ready...");
}catch (Exception e) { e.printStackTrace(); }
}
}
CLIENT_HOME FOLDER:
//Calculator.java
import java.rmi.*;
public interface Calculator extends Remote {
public int add(int a, int b) throws RemoteException;
}
//CalculatorClient.java
import java.rmi.*;
import java.rmi.registry.*;
public class CalculatorClient {
public static void main(String args[]) {
try {
String name = "calculator";
Registry registry = LocateRegistry.getRegistry(args[0]);
//System.out.println(registry);
//uncomment above line if you want to display the info. about registry
Calculator cal = (Calculator)registry.lookup(name);
//System.out.println(cal);
//uncomment above line if you want to display the info. about cal
int x = 4, y = 3;
int result = cal.add(x,y);
System.out.println("Sent: " + x +" and "+y);
System.out.print("Received("+x+"+"+y+"=): " + result);
javac *.java
start rmiregitry
EXPERIMENT 9: Write a program in Servlets to get and display value from an HTML page.
ParameterServlet.java
package myservlet;
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
doGet(request, response);
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><head>");
out.println("<title>Servlet Parameter</title>");
out.println("</head>");
out.println("<body>");
String param=null;
while (parameters.hasMoreElements())
param=(String)parameters.nextElement();
out.println("</body></html>");
out.close();
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<tr>
<td>Name:</td>
<td>
</td>
<td>SSN:</td>
<td>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
</td>
<td>email:</td>
<td>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>ParameterServlet</servlet-name>
<servlet-class>myservlet.ParameterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParameterServlet</servlet-name>
<url-pattern>/parameter</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
EXPERIMENT 10: Write a program in JSP to get and display value from an HTML page.
In JSP, the session is the most regularly used implicit object of type HttpSession. It is mainly
used to approach all data of the user until the user session is active.
Methods used in session Implicit Object are as follows:
Method 1: isNew(): This method is used to check either the session is new or not. Boolean value
(true or false) is returned by it. Primarily it used to trace either the cookies are enabled on client
side or not. If cookies are not enabled then the session.isNew() method should return true all the
time.
Method 2: getId(): While creating a session, the servlet container allots a distinctive string
identifier to the session. This distinctive string identifier is returned by getId method.
Method 3: getAttributeNames(): All the objects stored in the session are returned by
getAttributeNames method. Fundamentally, this method results in an enumeration of objects.
Method 4: getCreationTime(): The session creation time (the time when the session became
active or the session began) is returned by getCreationTime method.
Method 5: getAttribute(String name): Using getAttribute method, the object which is stored by
the setAttribute() method is retrieved from the session. For example, We need to store the
“userid” in session using the setAttribute() method if there is the requirement of accessing userid
on every jsp page until the session is active and when needed it can be accessed using the
getAttribute() method.
Method 6: setAttribute(String, object): The setAttribute method is used to store an object in
session by allotting a unique string to the object. Later, By using the same string this object can
be accessed from the session until the session is active. In JSP, while dealing with session
setAttribute() and getAttribute() are the two most regularly used methods.
Method 7: getMaxInactiveInterval(): The getMaxInactiveInterval return session’s maximum
inactivates time interval in seconds.
Method 8: getLastAccessedTime: The getLastAccessedTime method is mostly used to notice the
last accessed time of a session.
Method 9: removeAttribute(String name): Using removeAttribute(String name) method, the
objects that are stored in the session can be removed from the session.
Method 10: invalidate(): The invalidate() method ends a session and breaks the connection of the
session with all the stored objects.
Implementation:
The ‘index.html’ page given below will display a text box together with a go button. On clicking
go button, the control is transferred to welcome.jsp page. All the outputs are appended at last.
The name which is entered by user in the index page is displayed on the welcome.jsp page and it
saves the same variable in the session object so that it can be retrieved on any page till the
session becomes inactive.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<form action="Welcome.jsp">
</form>
</body></html>
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP PAGE</title>
</head>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
</body>
</html>
In second.jsp page, the value of variable is retrieved from the session and displayed.
Second.jsp
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Web.xml
<web-app id="WebApp_ID">
<display-name>jspprog</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Problem Description
We have to write a program in Java such that it creates a calculator which allows basic operations of
addition, subtraction, multiplication and division.
To Perform Addition :
Problem Solution
1. Create a text field to accept the expression and display the output also.
4. Create the buttons for operations, that is for addition, subtraction, multiplication and division and an
equals button to compute the result.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
TextField inp;
setBackground(Color.white);
setLayout(null);
int i;
inp.setBounds(150,100,270,50);
this.add(inp);
for(i=0;i<10;i++)
button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);
this.add(button[i]);
button[i].addActionListener(this);
dec.setBounds(200,300,50,50);
this.add(dec);
dec.addActionListener(this);
clr.setBounds(250,300,50,50);
this.add(clr);
clr.addActionListener(this);
operator[0]=new Button("/");
operator[1]=new Button("*");
operator[2]=new Button("-");
operator[3]=new Button("+");
operator[4]=new Button("=");
for(i=0;i<4;i++)
operator[i].setBounds(300,150+(i*50),50,50);
this.add(operator[i]);
operator[i].addActionListener(this);
operator[4].setBounds(350,300,70,50);
this.add(operator[4]);
operator[4].addActionListener(this);
String num1="";
String op="";
String num2="";
char ch = button.charAt(0);
if (!op.equals(""))
else
inp.setText(num1+op+num2);
else if(ch=='C')
inp.setText("");
double temp;
double n1=Double.parseDouble(num1);
double n2=Double.parseDouble(num2);
else
if (op.equals("+"))
temp = n1 + n2;
else if (op.equals("-"))
temp = n1 - n2;
else if (op.equals("/"))
temp = n1/n2;
else
temp = n1*n2;
inp.setText(num1+op+num2+" = "+temp);
num1 = Double.toString(temp);
op = num2 = "";
else
inp.setText("");
else
if (op.equals("") || num2.equals(""))
op = button;
else
double temp;
double n1=Double.parseDouble(num1);
double n2=Double.parseDouble(num2);
else
if (op.equals("+"))
temp = n1 + n2;
else if (op.equals("-"))
temp = n1 - n2;
else if (op.equals("/"))
temp = n1/n2;
else
temp = n1*n2;
num1 = Double.toString(temp);
op = button;
num2 = "";
inp.setText(num1+op+num2);
/*
</applet>
*/
OUTPUT:
OUTPUT:
EXPERIMENT 12:
Parsing URL
protocol://host:[port]/[path[?params][#anchor]]
The optional parts are shown in [ ]. Examples of protocols include HTTP, HTTPS, FTP, and
File. The path is also called filename, and the host is also referred to as the authority. If a URL
does not specify a port, a default port for the protocol is used. For example, for HTTP, the
default port is 80.
The URL class provides numerous methods to retrieve these parts. For example, we can get
the protocol, authority, host name, port number, path, query, filename, and reference from a URL
using these methods. The following program (ParsingURL.java) prints the different parts of a
URL specified as a command line argument.
Source code:
import java.net.*;
System.out.println("Protocol "+obj.getProtocol());
System.out.println("Authority"+obj.getAuthority());
System.out.println("host"+obj.getHost());
System.out.println("Port"+obj.getPort());
System.out.println("Default port"+obj.getDefaultPort());
System.out.println("Path"+obj.getPath());
System.out.println("query"+obj.getQuery());
System.out.println("File"+obj.getFile());
System.out.println("Ref"+obj.getRef());
OUTPUT:
Do's
1. Do wear ID card and follow dress code.
2. Do log off the computers when you finish.
3. Do ask the staff for assistance if you need help.
4. Do keep your voice low when speaking to others in the LAB.
5. Do ask for assistance in downloading any software.
6. Do make suggestions as to how we can improve the LAB.
7. In case of any hardware related problem, ask LAB in charge for solution.
8. if you are the last one leaving the LAB, make sure that the staff in charge of the LAB is informed to
close the LAB.
9. Be on time to LAB sessions.
10. Do Keep the LAB as clean as possible.
Don'ts