Java Lab Work
Java Lab Work
Exercise 1
Implement the following classes and test its functions.
Solution:
public class Line {
private Point BEGIN=new Point();
private Point END=new Point();
@Override
public String toString(){
return(" Begin @("+this.getBEGINX()+","+this.getBEGINY()+") &
END @("+this.getENDX()+","+this.getENDY()+")");
}
public double getLength(){
double xDiff = this.getBEGINX()-this.getENDX();
double yDiff = this.getBEGINY()-this.getENDY();
double result = Math.sqrt((xDiff*xDiff)+(yDiff*yDiff));
return(result);
}
}
public Point(){
}
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
public int getX() {
return X;
}
@Override
public String toString(){
return("Point @ ("+this.getX()+","+this.getY()+")");
}
}
Outputs
Cylinder, and Glome and two interfaces Area and Volume (Area.java and Volume.java are
given below).
Your classes may only have the class variable specified in the table below and the methods
defined in the two interfaces Area and Volume. You will implement the methods specified in
the Area and Volume interfaces and have them return the appropriate value for each shape.
Class Shape will have a single public method called getName that returns a string.
}
Circle.java
public class Circle extends Shape implements Area{
private double RADIUS;
@Override
public double getArea() {
return(Math.PI*this.RADIUS*this.RADIUS);
}
}
Cube.java
public class Cube extends Square implements Volume {
@Override
public double getVolume() {
return(super.getSIDE()*super.getSIDE()*super.getSIDE());
}
}
Cylinder.java
public class Cylinder extends Circle implements Volume {
private double HEIGHT;
@Override
public double getVolume(){
return(0.5*super.getArea()*super.getArea());
}
}
Shape.java
public class Shape {
private String NAME;
@Override
public double getVolume() {
return(4/3*super.getArea()*super.getRADIUS());
}
}
Square.java
public class Square extends Shape implements Area {
private double SIDE;
@Override
public double getArea() {
return(this.getSIDE()*this.getSIDE());
}
}
Test.java
public class test {
public static void main(String[] args) {
Circle C=new Circle(5,"Circle1");
Cube Cu=new Cube(3,"Cube1");
Cylinder Cy=new Cylinder(7,6,"Cylinder1");
Sphere S=new Sphere(8,"Sphere1");
Square Sq=new Square(6,"Square1");
Glome G=new Glome(9,"Glome1");
import java.util.Random;
class ExceptionExample {
int a = 0, b = 0, c = 0;
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b / c);
} catch (ArithmeticException e) {
System.out.println("Division by zero");
a = 0;
Output
1.4. Multithreading
ExtendThread.java
super(name);
}
public void run() {
try {
Thread.sleep(sleepTime);
System.out.println();
} catch (Exception e)
{ System.out.println(e.toString());
ImplementThread.java
this.name = name;
@Override
try {
System.out.println(getName() + " is going to sleep");
th.sleep(sleepTime);
} catch (Exception e)
{ System.out.println(e.toString());
return this.name;
MultithreadingDemo.java
System.out.println("Starting Threads");
Thread1.start();
Thread2.start();
Thread3.start();
Thread4.start();
/ obj1.start();
/ obj2.start();;
/ obj3.start();
/ obj4.start();
Output
1.5. File IO
1.5.1. Read Into & Write From File
ReadFromFile.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
FileReader fr = null;
BufferedReader br = null;
public ReadFromFile() {}
fr = new FileReader(filelocation);
br = new BufferedReader(fr);
String line="";
System.out.println("line");}
} finally {
if (fr != null) {
fr.close();
br.close();
}
}}}
WriteToFile.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
FileInputStream in = null;
try {
in = new FileInputStream(filelocation);
int size;
out.write(size);
System.out.println(ex.toString());
} finally {
in.close();
out.close();
}
FileIO.java
import java.io.IOException;
try {
rff.readDateFromFile();
wrf.writeDataToFile();
import java.io.*;
import java.util.zip.DeflaterOutputStream;
while((data = fis.read())!=-1){
dos.write(data);
}
dos.close();
fos.close();
fis.close();
}}
Unzip.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.InflaterInputStream;
fos.write(data);
iis.close();
fos.close();
fis.close();
}
2. User Interface Components with swings
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box,
Tooltips, Menus, etc.)
GUIToolsDemo.java
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler;
import javax.swing.filechooser.FileNameExtensionFilter
;
public GUIToolsDemo() {
super("GUIToolsDemo");
con.setLayout(new FlowLayout());
lblName.setText("Name:");
con.add(lblName);
txtName.setText("Enter Name...");
txtName.setDragEnabled(true);
con.add(txtName);
con.add(lblPass);
txtPass.setText("*******");
con.add(txtPass);
genderGroup.add(rdMale);
genderGroup.add(rdFemale);
con.add(rdMale);
con.add(rdFemale);
con.add(lblCourse);
con.add(cmbCourses);
con.add(lblComments);
btnSubmit.addActionListener(this);
btnCancel.addActionListener(this);
con.add(btnSubmit);
btnSubmit.setTransferHandler(new TransferHandler("text"));
con.add(btnCancel);
fileMenu.add(newProject);
mainMenu.add(fileMenu);
fc.setFileFilter(filter);
fc.showOpenDialog(this);
fileMenu.add(newProject);
editMenu.add(cut);
editMenu.add(copy);
editMenu.add(paste);
mainMenu.add(editMenu);
setJMenuBar(mainMenu);
setSize(500, 600);
setVisible(true);
}
@Override
if(e.getSource()==btnSubmit)
String s= this.txtName.getText();
this.txtName.setText(s);
/int a= Integer.parseInt(s);
System.out.println("Cancel button is pressed");
Outputs
2.2. Layout Managements
2.2.1. Border Layout
BorderLayoutDemo.java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
private String names[] = {"HIDE NORTH", "HIDE SOUTH", "HIDE EAST","HIDE WEST", "HIDE CENTER"};
public BorderLayoutDemo() {
super("BorderLayout Demo");
con.setLayout(layout);
}
con.add(buttons[0], BorderLayout.NORTH);
buttons[0].addActionListener(this);
con.add(buttons[1], BorderLayout.SOUTH);
buttons[1].addActionListener(this);
con.add(buttons[2], BorderLayout.EAST);
buttons[2].addActionListener(this);
con.add(buttons[3], BorderLayout.WEST);
buttons[3].addActionListener(this);
con.add(buttons[4], BorderLayout.CENTER);
buttons[4].addActionListener(this);
setSize(400, 400);
setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
if (e.getSource() == buttons[i]) {
buttons[i].setVisible(false);
}
Output
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
"Button8", "Button9"};
con.setLayout(layout);
setSize(400, 400);
setVisible(true);
new GridLayoutDemo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output
2.2.3. Flow Layout
FlowLayoutDemo.java
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
FlowLayout layout;
public Flowlayout(){
con.setLayout(layout);
btnLeft.addActionListener(new ActionListener() {
@Override
layout.setAlignment(FlowLayout.LEFT);
layout.layoutContainer(con);
});
layout.setAlignment(FlowLayout.RIGHT);
layout.layoutContainer(con);
});
layout.setAlignment(FlowLayout.CENTER);
layout.layoutContainer(con);
}
});
setSize(400,400);
setVisible(true);
Outputs
3. Events Handling
GUIEventHandling.java
public GUIEventHandling() {
super("GUI EventHandling");
con.setLayout(new FlowLayout());
con.add(new JLabel("Country"));
cmbCountry.setToolTipText("Select Country");
cmbCountry.addActionListener(this);
con.add(cmbCountry);
con.add(new JLabel("-"));
setSize(500, 500);
setVisible(true);
@Override
if (e.getSource().equals(cmbCountry)) {
if (cmbCountry.getSelectedItem().toString() == "Nepal")
{ txtCodeNumber.setText("+977");
} else {
txtCodeNumber.setText("");
} Outputs
4.Database Connectivity
5.Network Programming
5.1. Working with URLs
ParseURL.java
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://example.com:80/docs/books/tutorial"
+
"/index.html?
name=networking#DOWNLOADIN
G");
System.out.println("protocol = " +
aURL.getProtocol());
System.out.println("authority = " +
aURL.getAuthority());
System.out.println("filename = " +
aURL.getFile()); System.out.println("host
= " + aURL.getHost());
System.out.println("port = " +
aURL.getPort());
System.out.println("path
= " + aURL.getPath());
System.out.println("query = " +
aURL.getQuery());
System.out.println("ref
= " + aURL.getRef());
}
}
Output
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?
name=networking ref = DOWNLOADING
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
String message;
String message;
try {
ostream = sock.getOutputStream();
dos.writeBytes(message);
ostream.close();
sock.close();
Server.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
try {
System.out.println("Server started!");
cSock = serSock.accept();
istream = cSock.getInputStream();
} finally {
dis.close();
istream.close();
cSock.close();
serSock.close();
Outputs
6. Servlets
6.1. HTTP Request and Response
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;
public HelloServlet(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
response.setContentType("text/html;charset= UTF-8");
write.println("HELLO WORLD!!");
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello World!!</h1>
</body>
</html>
Output
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form method="post" action ="mypage.jsp">
<table width="400" border="5" align="center">
<tr>
<td colspan="5" align="center"><h1>JSP form
Demo</h1></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type='text' name='name'/></td>
</tr>
<tr>
<td>Phone N0:</td>
<td><input type='text' name='phone'/></td>
</tr>
<tr>
</tr>
</form>
</body>
Mypage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%@page import="java.util.Date"%>
<%
if(session.isNew()){
session.setAttribute(UserIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
visitCount= (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount+1;
session.setAttribute(visitCountKey, visitCount);
userID = (String)session.getAttribute(UserIDKey);
%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<tr>
</tr>
<tr>
<td>user ID</td>
<td> <%out.print(userID);%></td>
</tr>
<tr>
<td>Session ID</td>
<td> <%out.print(session.getId());%></td>
</tr>
<tr>
<td>Creation Time</td>
<td><%out.print(creationTime);%></td>
</tr>
<tr>
<td><%out.print(lastAcessTime);%></td>
</tr>
<tr>
<td>Number of Visits</td>
<td><%out.print(visitCount);%></td>
</tr>
<tr>
<td>GOTO:</td>
</tr>
</form>
</body>
</html>
afterSession.jsp
<%
if(user==null){
%>
<jsp:forward page="index.jsp"></jsp:forward>
<%}%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>After Session</h1>
<p> <%out.print(user);%></p>
</html>
beforSession.jsp
<%
if(user==null){
%>
<jsp:forward page="index.jsp"></jsp:forward>
<%}%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>After Session</h1>
<p> <%out.print(user);%></p>
</body>
</html>
Outputs
8. RMI
8.1. Creating and Executing RMI Application
RMIInterface.java
import java.rmi.Remote;
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
try {
int respons=stub.add(2,5);
System.out.println("SUM="+ respons);
} catch (Exception e) {
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
try {
System.out.println("Server ready");
} catch (Exception e) {
@Override
return (x+y);
Outputs
SUM= 7