Java Practical
Java Practical
Bagbazar, Kathmandu
Tribhuvan University
A Practical Report on
Submitted To:
Kumar Prasun
Department of Computer Science
Submitted By:
Simran Shrestha
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. In Java, an exception is an
event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Java exception handling is managed via five keywords: try, catch, throw, throws, finally.
Program statements that we want to monitor for exceptions are contained within a
Try block.
Any code that absolutely must be executed before a method returns is put in a finally block.
Source Code:
int a=6;
int b=0;
try{
int c=a/b;
catch(ArithmeticException e)
System.out.println(e);
Output:
Lab 2:
WAP to create a simple calculator GUI using the concept of Swing, Event
Handling in Java programming Language.
Theory:
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of
Oracle’s Java foundation classes. Java Swing is an API for providing graphical user interface
elements to Java Programs. Swing was created to provide more powerful and flexible
components than Java AWT (Abstract Window Toolkit).
Methods used:
1. add(Component c) : adds component to container.
2. addActionListenerListener(ActionListener d) : add actionListener for specified
component
3. setBackground(Color c) : sets the background color of the specified container
4. setSize(int a, int b) : sets the size of container to specified dimensions.
5. setText(String s) : sets the text of the label to s.
6. getText() : returns the text of the label.
Source Code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
static JFrame f;
static JTextField l;
String s0, s1, s2;
calculator()
{
s0 = s1 = s2 = "";
}
public static void main(String args[])
{
f = new JFrame("calculator");
calculator c = new calculator();
l = new JTextField(16);
l.setEditable(false);
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
be = new JButton(".");
JPanel p = new JPanel();
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
s0 = s1 = s2 = "";
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
l.setText(s0 + s1 + s2 + "=" + te);
s0 = Double.toString(te);
s1 = s2 = "";
}
else {
if (s1.equals("") || s2.equals(""))
s1 = s;
else {
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
s0 = Double.toString(te);
s1 = s;
s2 = "";
}
l.setText(s0 + s1 + s2);
}
}
}
Output:
Conclusion:
In this lab of Advanced Java Programming, we successfully created a simple calculator GUI
using the elements of Java Swing and the java event handling.
Lab 3:
I. Write a java program using TCP such that client sends number to
server and displays its factorial. The server computes factorial of the
number received from client.
Theory:
Java Socket Programming:
Java Socket programming is used for communication between the applications running on
different JRE. Java Socket programming can be connection-oriented or connection-less. Socket
and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept() method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.
Source Code:
//server program
import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(1064);
System.out.println("Waiting for Client Request");
Socket s=ss.accept();
BufferedReader br;
PrintStream ps;
String str;
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Received number");
int x=Integer.parseInt(str);
int fact=1;
for(int i=1;i<=x;i++)
fact=fact*i;
ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(fact));
br.close();
ps.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//Client program
import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[])throws IOException
{
Socket s=new Socket(InetAddress.getLocalHost(),1064);
BufferedReader br;
PrintStream ps;
String str;
System.out.println("Enter a number :");
br=new BufferedReader(new InputStreamReader(System.in));
ps=new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("The facorial of the number is : "+str);
br.close();
ps.close();
}
}
II. Write a java program using UDP showing that the sending and
receiving of message using DatagramPacket and DatagramSocket
class.
Theory:
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.
Datagram
Datagrams are collection of information sent from one device to another device via the
established network. When the datagram is sent to the targeted device, there is no assurance that
it will reach to the target device safely and completely. It may get damaged or lost in between.
Likewise, the receiving device also never know if the datagram received is damaged or not. The
UDP protocol is used to implement the datagrams in Java.
Source Code:
//sender
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class Dsender {
public static void main(String[] args)throws Exception {
DatagramSocket ds= new DatagramSocket();
String str= "Message sent by server";
InetAddress ip = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),ip, 6666);
ds.send(dp);
System.out.println("Message sent!");
ds.close();
}
}
//receiver
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Dreceiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds= new DatagramSocket(6666);
byte[] buf= new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, 1024);
ds.receive(dp);
String str= new String(dp.getData(),0,dp.getLength());
System.out.println(str);
System.out.println("Message received!");
ds.close();
}
}
Output:
Conclusion:
In this lab session, we successfully implement the concepts of Network Programming: TCP/IP
and UDP using the java.net package classes in Java programming language.
Lab 4:
You are hired by a reputed software company which is going to design an
application for "Movie Rental System". Your responsibility is to design a
schema named MRS and create a table named Movie (id, Title, Genre,
Language, Length).
WAP to design a GUI form to take input for this table and insert the data into
table after clicking the OK button.
Theory:
JDBC:
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
Source Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class Movie extends JFrame implements ActionListener {
JFrame jf;
JTextField t1, t2,t3,t4;
JLabel l1,l2,l3,l4;
JButton b1;
public Movie(){
jf = new JFrame("Movie Rental System");
l1= new JLabel("Title");
l2= new JLabel("Genera");
l3= new JLabel("Language");
l4= new JLabel("Length");
t1= new JTextField(10);
t2= new JTextField(10);
t3= new JTextField(10);
t4= new JTextField(10);
b1= new JButton("ADD");
jf.add(l1);
jf.add(t1);
jf.add(l2);
jf.add(t2);
jf.add(l3);
jf.add(t3);
jf.add(l4);
jf.add(t4);
jf.add(b1);
jf.setSize(500,700);
jf.setLayout(new FlowLayout());
b1.addActionListener(this);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mrs","root","");
Statement stmt= conn.createStatement();
System.out.println("Database connected successfully");
String sql="insert into movie(title, genera, language, length) values (?,?,?,?)";
PreparedStatement ps= conn.prepareStatement(sql);
ps.setString(1, t1.getText());
ps.setString(2, t2.getText());
ps.setString(3, t3.getText());
ps.setString(4, t4.getText());
ps.executeUpdate();
conn.close();
System.out.println("Inserted successfully");
}catch(Exception se){
System.out.println(se);
}
}
public static void main(String[] args) {
new Movie();
}
}
Output:
Inserting data into from GUI to Mysql Database as:
And, the reflected data in the database:
Conclusion:
In this lab session, we successfully connect to the MySQL database using JDBC connection
using above Movie Rental System GUI.
Lab 5:
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page). Servlet technology is robust and scalable because of java language. Before
Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side
programming language.
Source Code:
//servlet.java file
package com.innovator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class servlet extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.println(" <html>");
out.println("<h1>The current date is: "+java.time.LocalDate.now()+"</h3>");
out.println("<h1>And, the current time is: "+java.time.LocalTime.now()+"</h3>");
out.println("</html>");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
//index.html
<html>
<head>
<title>Start page</title>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
</head>
<body>
<h2>My servlet page!</h2>
<form action="./api" method="GET, POST">
<Button>Show current Date and Time</Button>
</form>
</body>
</html>
//web.xml file
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.innovator.servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/api</url-pattern>
</servlet-mapping>
</web-app>
Output:
3. create an auto refreshed page.
//Refresh.java file
package com.innovator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Refresh extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
response.setIntHeader("Refresh", 1);
// Set response content type
response.setContentType("text/html");
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
out.println("</html>");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
//index.html file
<html>
<head>
<title>Start page</title>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
</head>
<body>
<h2>My servlet page!</h2>
<form action="./Refresh" method="GET, POST">
<Button>show autorefresh page</Button>
</form>
</body>
</html>
//web.xml file
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Refresh</servlet-name>
<servlet-class>com.innovator.Refresh</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Refresh</servlet-name>
<url-pattern>/Refresh</url-pattern>
</servlet-mapping>
</web-app>
Output:
Conclusion:
In this lab of Advanced Java Programming, we successfully implemented the concept of servlet
using Maven and Tomcat server in visual studio code.
Lab 6:
Source Code:
// ControllerServlet.java file
package com.innovator.user;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.innovator.ControllerServlet.LoginBean;
response.setContentType("text/html");
String name=request.getParameter("name");
String password=request.getParameter("password");
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);
boolean status=bean.validate();
if(status){
RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
rd.forward(request, response);
}
}
@Override
doPost(req, resp);
}
}
// LoginBean.java
package com.innovator.ControllerServlet;
return name;
}
this.name = name;
}
return password;
}
this.password = password;
}
if(password.equals("saugat"))
return true;
else
return false;
}
}
//index.jsp
<html>
<body>
</form>
</body>
</html>
//login-error.jsp
//login-success.jsp
<%@page import="com.javatpoint.LoginBean"%>
<%
LoginBean bean=(LoginBean)request.getAttribute("bean");
out.print("Welcome, "+bean.getName());
%>
Output:
Conclusion:
In this lab of Advanced Java Programming, we successfully implemented the concept of JSP
using Maven and Tomcat server in visual studio code.
Lab 7:
Source Code:
import java.rmi.*;
//implementation of interface
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class AddRemImp1 extends UnicastRemoteObject implements AddRem
{
public AddRemImp1() throws RemoteException{
}
public int addNum(int a, int b){
return (a+b);
}
}
//client program
import java.rmi.*;
import java.net.*;
import java.util.*;
public class AddClient {
public static void main(String args[]) {
Scanner sc;
try {
String host = "localhost";
sc = new Scanner(System.in);
System.out.println("Enter the 1st parameter");
int a = sc.nextInt();
System.out.println("Enter the 2nd parameter");
int b = sc.nextInt();
AddRem remobj = (AddRem) Naming.lookup("rmi://" + host + "/AddRem");
System.out.println(remobj.addNum(a, b));
} catch (RemoteException re) {
re.printStackTrace();
} catch (NotBoundException nbe) {
nbe.printStackTrace();
} catch (MalformedURLException mfe) {
mfe.printStackTrace();
}
}
}
//server program
import java.rmi.*;
import java.net.*;
public class AddServer
{
public static void main(String args[])
{
try{
AddRemImp1 locobj= new AddRemImp1();
Naming.rebind("rmi:///AddRem",locobj);
}
catch(RemoteException re){
re.printStackTrace();
}
catch(MalformedURLException mfe){
mfe.printStackTrace();
}
}
}
Output: