Java Manual
Java Manual
Prepared By:
Mr. Shrikrishna U. Kolhar
Assistant Professor
Department of Electronics and Telecommunication Engineering.
Vidya Pratishthan’s
Kamalnayan Bajaj Institute of Engineering and Technology,
Baramati
List of Experiments
1 Write a program to demonstrate status of key on an Applet window such as
KeyPressed, KeyReleased, KeyUp, KeyDown.
2 Write a program to create a frame using AWT. Implement mouseClicked,
mouseEntered() and mouseExited() events. Frame should become visible when
the mouse enters it.
3 Develop a GUI which accepts the information regarding the marks for all the
subjects of a student in the examination. Display the result for a student in a
separate window.
4 Write a program to insert and retrieve the data from the database using JDBC.
5 Develop an RMI application which accepts a string or a number and checks that
string or number is palindrome or not.
6 Write a program to demonstrate the use of InetAddress class and its factory
methods.
7 Write program with suitable example to develop your remote interface, implement
your RMI server, implement application that create your server, also develop
security policy file.
8 Write a database application that uses any JDBC driver.
9 Create a simple calculator application using servlet.
10 Create a registration servlet in Java using JDBC. Accept the details such as
Username, Password, Email, and Country from the user using HTML Form and
store the registration details in the database
Program No: 1
Program Statement: Write a program to demonstrate status of key on an Applet window such
as KeyPressed, KeyReleased, KeyUp, KeyDown.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
switch(key)
{
case KeyEvent.VK_F1:
msg = msg + "F1";
break;
case KeyEvent.VK_F2:
msg = msg + "F2";
break;
case KeyEvent.VK_F3:
msg = msg + "F3";
break;
case KeyEvent.VK_F4:
msg = msg + "F4 ";
break;
case KeyEvent.VK_RIGHT:
msg = msg + "RIGHT ";
break;
case KeyEvent.VK_LEFT:
msg = msg + "LEFT ";
break;
case KeyEvent.VK_UP:
msg = msg + "UP ";
break;
case KeyEvent.VK_DOWN:
msg = msg + "DOWN ";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Post-lab questions:
1. Identify the name of listener interface used in above program
2. Which command is used for registering listener in the above program?
3. Identify the name of event class
4. Name the methods used for handling event in above program
Program No: 2
Program Statement: Write a program to create a frame using AWT. Implement
mouseClicked, mouseEntered() and mouseExited() events. Frame should become visible
when the mouse enters it.
Program:
/**** Mouse_Exp2.java ****/
// Program we want to check events like Mouse click, mouse entered and
mouse exited
import java.awt.*;
import java.awt.event.*;
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new Mouse_Exp2();
}
@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
}
Post-lab questions:
1. How to identify that above program is a GUI program?
2. Identify the name of listener interface used in above program
3. Which command is used for registering listener in the above program?
4. Identify the name of event class
5. Name the methods used for handling event in above program
Program No: 3
Program Statement: Develop a GUI which accepts the information regarding the marks for
all the subjects of a student in the examination. Display the result for a student in a separate
window.
Theory:
If you want to accept marks for 3 subjects of a student and after clicking on submit a
new window will pop-up to display overall result
Which component classes are required for creating above GUI?
Draw GUI here.
Program:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public ReportCard()
{
lname.setText("Enter Name");
jp.add(lname);
jp.add(tname);
lMath.setText("Enter Math Marks");
jp.add(lMath);
jp.add(tMath);
lScience.setText("Enter Science Marks");
jp.add(lScience);
jp.add(tScience);
lEnglish.setText("Enter English Marks");
jp.add(lEnglish);
jp.add(tEnglish);
jp.add(bsubmit);
add(jp);
bsubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String val = tname.getText();
JLabel l1 = new JLabel("Welcome "+val);
int sub1 = Integer.parseInt(tMath.getText());
int sub2 = Integer.parseInt(tScience.getText());
int sub3 = Integer.parseInt(tEnglish.getText());
int sum = sub1+sub2+sub3;
float average = sum/3;
JLabel l2 = new JLabel("Average "+ average);
JPanel jip = new JPanel();
jip.add(l1);
jip.add(l2);
JFrame inf = new JFrame();
inf.setVisible(true);
inf.add(jip);
inf.setSize(300, 100);
}
});
Post-lab Questions:
1. Identify component classes used in above program.
2. Which event and listener used in the program?
3. What is the use of integer.parseInt() method?
Program No: 4
Program Statement: Write a program to insert and retrieve the data from the database using
JDBC.
Theory:
What is JDBC and what is the use of it? (https://www.javatpoint.com/java-jdbc)
Write 5 steps for JDBC connectivity (https://www.javatpoint.com/steps-to-connect-to-the-
database-in-java)
Program:
1. Program to display the contents of the table
import java.sql.*;
// User class
public class SQLStatementSelect{
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from pqr");
while(rs.next())
//System.out.println("Success");
System.out.println(rs.getString(1)+" "+rs.getString(2)+"
"+rs.getString(3));
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
2. Program to insert new record into the table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");
"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");
int i = stmt.executeUpdate();
System.out.println(i + "Records deleted");
con.close();
}
catch(Exception e){
System.out.println(e);
}
"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");
int i = stmt.executeUpdate();
System.out.println(i + "Records updated");
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
Post-lab Questions:
1. List the SQL queries for 1) displaying all the data from the table 2) inserting new record
3) deleting particular record 4) updating any field of the record
2. List and explain the commands for JDBC connectivity steps
Program No: 5
Program Statement: Develop an RMI application which accepts a string or a number and
checks that string or number is palindrome or not.
Theory:
What is RMI? Architecture of RMI application, Working of RMI application, RMI registry,
https://www.tutorialspoint.com/java_rmi/java_rmi_introduction.htm
list steps for RMI application development
Program:
1. Following is an example of a remote interface. Here we have defined an interface
with the name Hello and it has a method called printMsg().
import java.rmi.Remote;
import java.rmi.RemoteException;
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
Post-lab Questions:
1. List steps to write RMI program
(https://www.tutorialspoint.com/java_rmi/java_rmi_application.htm)
2. Write example code for creating remote interface
Program No: 6
Program Statement: Write a program to demonstrate the use of InetAddress class and its
factory methods.
Theory:
Write use of InetAddress class, two versions of IP address and TCP/IP communication
protocol.
https://www.javatpoint.com/InetAddress-class
Program:
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
import java.net.Inet4Address;
import java.util.Arrays;
import java.net.InetAddress;
public class InetDemo2
{
public static void main(String[] arg) throws Exception
{
InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
byte addr[]={72, 3, 2, 12};
System.out.println("ip : "+ip);
System.out.print("\nip1 : "+ip1);
InetAddress ip2 = InetAddress.getByAddress(addr);
System.out.print("\nip2 : "+ip2);
System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
System.out.print("\nHost Address : " +ip.getHostAddress());
System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
System.out.print("\nhashCode : " +ip.hashCode());
System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
}
}
Post-lab Questions:
List factory methods and instance methods of InetAddress class. Write use of each one.
Program No: 7
Program Statement: Write program with suitable example to develop your remote interface,
implement your RMI server, implement application that create your server, also develop
security policy file.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
// Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
8. Client Program: Following is the client program of this application. Here, we are
fetching the remote object and invoking its method named animation().
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
Post-lab questions:
1. List steps to run the program
Program No: 8
Program Statement: Write a database application that uses any JDBC driver.
Theory and Program:
1. We will take an example to see how a client program can retrieve the records of
a table in MySQL database residing on the server.
2. Assume we have a table named student_data in the database details as shown
below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
3. Assume the name of the user is myuser and its password is password.
4. Creating a Student Class: Create a Student class with setter and getter methods as shown
below.
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
6. Developing the Implementation Class: Create a class and implement the above created
interface.
7. Here we are implementing the getStudents() method of the Remote interface. When you
invoke this method, it retrieves the records of a table named student_data. Sets these
values to the Student class using its setter methods, adds it to a list object and returns
that list.
import java.sql.*;
import java.util.*;
// Database credentials
String USER = "myuser";
String PASS = "password";
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
10. Client Program: Following is the client program of this application. Here, we are fetching
the remote object and invoking the method named getStudents(). It retrieves the records
of the table from the list object and displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
public class Client {
private Client() {}
public static void main(String[] args)throws Exception {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// Looking up the registry for the remote object
Hello stub = (Hello) registry.lookup("Hello");
// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Program No: 9
Program Statement: Create a simple calculator application using servlet.
Program:
index.html
<html><head>
<title>Calculator App</title></head><body>
<form action="CalculatorServlet" >
Enter First Number <input type="text" name="txtN1"><br>
Enter Second Number <input type="text" name="txtN2" ><br>
Select an Operation<input type="radio" name="opr" value="+">
ADDTION <input type="radio" name="opr" value="-">
SUBSTRACTION <input type="radio" name="opr" value="*">
MULTIPLY <input type="radio" name="opr" value="/">
DIVIDE <br><input type="reset">
<input type="submit" value="Calculate" >
</form></body></html>
CalculatorServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class CalculatorServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet
CalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String opr=request.getParameter("opr");
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("*"))
result=n1*n2;
out.println("<h1> Result = "+result);
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("/"))
result=n1/n2;
out.println("</body></html>");
}}
Experiment No: 10
Program Statement: Create a registration servlet in Java using JDBC. Accept the details
such as Username, Password, Email, and Country from the user using HTML Form and store
the registration details in the database
Program:
index.html
<html><head><title>Login Form</title></head>
<form action="LoginServlet" >
Enter User ID<input type="text" name="txtId"><br>
Enter Password<input type="password" name="txtPass"><br>
<input type="reset">
<input type="submit" value=" Click to Login "></form></html>
LoginServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
if(uname.equals("admin") &&upass.equals("12345"))
{
out.println("<body bgcolor=blue >");
out.println("<h1> Welcome !!! "+uname+"</h1>");
}
else
{
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");