Java Assignment Coding Practice
Java Assignment Coding Practice
Coding Practice
By Dipendra Shrestha
B.Sc CSIT
https://khullasikshya.com/
[Note: Questions should be typed in “Calibri 11pt” font whereas answers (code) should be in “Courier
New 11pt” font. Submit your assignments in PDF format along with a ZIP file of your source code for
each unit/subunit.]
Unit #1.3
1) Write a program to demonstrate try-catch-finally.
2) Write a program to demonstrate try-finally.
3) Write a program to create two threads. The first thread should print numbers from 1 to 10 at intervals
of 0.5 second and the second thread should print numbers from 11 to 20 at the interval of 1 second.
4) Write a program to execute multiple threads in priority base. [2075]
Unit #1.4
1) Write the simple java program that reads data from one file and writes data to another file. [2070,
2071, 2073, 2074]
2) Write a program to duplicate each character in a text file and write the output in a separate file using
character stream.
e.g.
source.txt
apple
destination.txt
aappppllee
3) Write a program to read records from a text file which contains people’s name, principle, rate and
time values. Calculate simple interest and write all the contents of the source file along with simple
interest to destination file.
source.txt
John 10000 10.5 2.5
Jane 5000 9.25 5.0
destination.txt
John 10000 10.5 2.5 2625.00
Jane 5000 9.25 5.0 2312.50
4) Write a program to read the contents of a file one line at a time and output them to the screen.
5) Write a program to input whole lines from the keyboard and write them to a file. Exit the program
when the user types “quit”.
Combined
1) Assume that a database named Astronomy contains the name and mass of each of the 8 planet of
the solar system and its distance from the sun in a table with the schema planets (id, planet, mass,
distance). Create a 2D array capable of holding all the data contained in this table. Use JDBC to
populate the array from the data in the table. The 2D array should also hold the calculated value of
gravitational force between each planet and the sun. This can be calculated using the data you just
retrieved. Display the data in the final 2D array in a Swing JTable component with appropriate
column headers.
Use Newton’s Law of Universal Gravitation to calculate the gravitational force between the sun and
each of the planets (one at a time):
𝑚𝑠 𝑚𝑝
𝐹=𝐺
𝑟2
where,
gravitation constant (G) = 6.67430 × 10−11 𝑚3 𝑘𝑔−1 𝑠 −2 ,
the mass of the sun is 1.989 × 1030 kg
This can be represented in Java with the following code:
double G = 6.67430e-11;
double ms = 1.989e+30;
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
Unit- #1.2
1) An array is called balanced if it’s even numbered elements (a[0], a[2], etc.) are even and its odd
numbered elements (a[1], a[3], etc.) are odd. Write a function named balanced that accepts an
array of integers which returns 1 if the array is balanced and returns 0 otherwise. [2075]
Elaboration of question,
Examples:
{2, 3, 6, 7} is balanced since a[0] and a[2] are even, a[1] and a[3] are odd.
{6, 7, 2, 3, 12} is balanced since a[0], a[2] and a[4] are even, a[1] and a[3] are odd.
{7, 15, 2, 3} is not balanced since a[0] is odd.
Program:
package Q1_ArrayBalance
public class ArrayBalance
{
static int[] array = {6, 7, 2, 3, 12};
Output:
1|Page
PREPARED BY: Dipendra Shrestha
2) Write an object-oriented program to find area and perimeter of rectangle. [2073, 2074]
Program
package Q2_AreaAndPerimeterOfRectangle;
public class AreaAndPerimeterOfRectangle
{
private double l,b;
public AreaAndPerimeterOfRectangle(double l,double b)
{
this.l=l;
this.b =b;
}
public static void main(String[] args)
{
AreaAndPerimeterOfRectangle r = new
AreaAndPerimeterOfRectangle(5,10);
Output:
2|Page
PREPARED BY: Dipendra Shrestha
3) Write a program to input and add two numbers using static methods (procedural
programming).
Program:
package Q3_AddTwoNumbers;
import java.util.Scanner;
Output:
3|Page
PREPARED BY: Dipendra Shrestha
4) Write a program to input principle, time and rate, then calculate simple interest using static
methods.
Program:
package Q4_SimpleInterest;
import java.util.Scanner;
System.out.println("SimpleInterest = " +
simpleInterestCalc(p,t,r));
}
public static double simpleInterestCalc(double p,
double t,
double r)
{
return (p*t*r)/100;
}
}
Output:
4|Page
PREPARED BY: Dipendra Shrestha
Procedural:
a) Circle
Program:
package Q5_a_AreaOfCircleProcedural;
import java.util.Scanner;
Output:
5|Page
PREPARED BY: Dipendra Shrestha
b) Square
Program:
package Q5_b_AreaOfSquareProcedural;
import java.util.Scanner;
Output:
6|Page
PREPARED BY: Dipendra Shrestha
c) Rectangle:
Program
package Q5_c_AreaOfRectangleProcedural;
import java.util.Scanner;
Output:
7|Page
PREPARED BY: Dipendra Shrestha
d) Sphere:
Program
package Q5_d_AreaOfSphereProcedural;
import java.util.Scanner;
Output:
8|Page
PREPARED BY: Dipendra Shrestha
Object-oriented:
a) Circle
Program:
package Q5_a_AreaOfCircleObjectOriented;
Output:
9|Page
PREPARED BY: Dipendra Shrestha
b) Square
Program:
package Q5_b_AreaOfSquareObjectOriented;
Output:
10 | P a g e
PREPARED BY: Dipendra Shrestha
c) Rectangle
Program:
package Q5_c_AreaOfRectangleObjectOriented;
Output:
11 | P a g e
PREPARED BY: Dipendra Shrestha
d) Sphere
Program:
package Q5_d_AreaOfSphereObjectOriented;
Output:
12 | P a g e
PREPARED BY: Dipendra Shrestha
Program:
package Q6_SumOf1DArray;
Output:
13 | P a g e
PREPARED BY: Dipendra Shrestha
Program
package Q7_AverageOf1DArray;
Output:
14 | P a g e
PREPARED BY: Dipendra Shrestha
8) Create a class with static methods to calculate the sum, difference and product of two
matrices (represented by 2D arrays). The methods must return the resulting matrices.
Program
package Q8_2DArrays;
import java.util.Scanner;
result = calculateSum(firstMatrix,secondMatrix);
System.out.println("The result of Matrix
addition is:");
displayMatrix(result);
result =
calculateDifference(firstMatrix,secondMatrix);
15 | P a g e
PREPARED BY: Dipendra Shrestha
result=calculateProduct(firstMatrix,secondMatrix
);
System.out.println("The result of Matrix
Multiplication is:");
displayMatrix(result);
}
public static int[][] calculateSum(int[][]firstMatrix
, int [][]secondMatrix)
{
int [][] sum = new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
mul[i][j]=0;
for(int k=0;k<3;k++)
{
16 | P a g e
PREPARED BY: Dipendra Shrestha
mul[i][j]+=firstMatrix[i][k]*
secondMatrix[k][j];
}
}
}
return mul;
}-
//Display the result in a Matrix form
public static void displayMatrix(int [][] result)
{
for(int i = 0; i<3; i++)
{
for (int j = 0; j<3; j++)
{
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
Output:
17 | P a g e
PREPARED BY: Dipendra Shrestha
package Q9_Encapsulation;
Output:
18 | P a g e
PREPARED BY: Dipendra Shrestha
package Q10_Inheritance;
rec. setValues(10,10);
System.out.println("Rec:"+rec.areaOfRectangel());
tri.setValues(10, 10);
System.out.println("Tri: "+tri.areaOfTriangle());
}
}
class Polygon
{
protected int width ;
protected int height;
output:
19 | P a g e
PREPARED BY: Dipendra Shrestha
package Q11_PolymorphismUsingNonAbstractClass;
class Shape
{
public double area()
{
return 0;
}
}
class Square extends Shape
{
private double l;
public Square(double l)
{
this.l = l;
}
public double area()
{
return l*l;
}
}
output:
20 | P a g e
PREPARED BY: Dipendra Shrestha
package Q12_PolymorphismUsingAbstractClass;
Output:
21 | P a g e
PREPARED BY: Dipendra Shrestha
interface Shape
{
double area();
}
class Square implements Shape
{
public double l;
public Square(double l)
{
this.l = l;
}
@Override public double area()
{
return l * l;
}
}
class Circle implements Shape
{
public double r;
public Circle(double r)
{
this.r = r;
}
@Override public double area()
{
return Math.PI * r * r;
}
}
public class PolymorphismUsingInterface
{
public static void main(String[] args)
{
Shape[] shapes = new Shape[]
{
new Square(5),
new Circle(1),
new Square(10),
new Circle(2)
};
for(Shape s : shapes)
System.out.println(s.area());
}
}
Output:
22 | P a g e
PREPARED BY: Dipendra Shrestha
14) Write a program to create two classes Circle and Square, with appropriate fields and methods,
in a package name shape. Create a separate class ShapeDemo to test the classes.
Program
package Q14_ShapeDemo;
class Circle
{
private double radius;
class Square
{
private double length;
23 | P a g e
PREPARED BY: Dipendra Shrestha
output:
24 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
Unit- #1.3
package Q1_TryCatchFinally;
import java.util.Scanner;
1|Page
PREPARED BY: Dipendra Shrestha
Output:
For try-block
For catch-block
package Q2_TryFinally;
Output:
2|Page
PREPARED BY: Dipendra Shrestha
3) Write a program to create two threads. The first thread should print numbers from 1 to 10 at
intervals of 0.5 second and the second thread should print numbers from 11 to 20 at the interval
of 1 second.
Program
package Q3_TwoThread;
}
}
}
}
3|Page
PREPARED BY: Dipendra Shrestha
output:
4|Page
PREPARED BY: Dipendra Shrestha
package Q4_MultipleThread;
5|Page
PREPARED BY: Dipendra Shrestha
Output:
6|Page
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
Unit- #1.4
1) Write the simple java program that reads data from one file and writes data to another file.
[2070, 2071, 2073, 2074]
Program
package Q1_FileReadWrite;
import java.io.FileInputStream;
import java.io.FileOutputStream;
in = new FileInputStream
("source_FileReadWrite.txt");
if (in!=null) in.close();
if (out!=null)out.close();
}
}
Output:
Source_FileReadWrite.txt destination_FileReadWrite.txt
1|Page
PREPARED BY: Dipendra Shrestha
2) Write a program to duplicate each character in a text file and write the output in a separate
file using character stream.
e.g.
source.txt
apple
destination.txt
aappppllee
Program
package Q2_CharacterStream;
import java.io.FileReader;
import java.io.FileWriter;
FileReader in = null;
FileWriter out = null;
in = new FileReader
("source_character_stream.txt");
out =new FileWriter
("destination_character_stream.txt");
int charData;
while(true)
{
charData = in.read();
if (charData == -1)
break;
else {
out.write(charData);
out.write(charData);
}
}
if (in!= null)in.close();
if (out!=null)out.close();
}
}
Output:
Source_character_stream.txt destination_character_stream.txt
2|Page
PREPARED BY: Dipendra Shrestha
3) Write a program to read records from a text file which contains people’s name, principle, rate
and time values. Calculate simple interest and write all the contents of the source file along
with simple interest to destination file.
e.g.:
source.txt
John 10000 10.5 2.5
Jane 5000 9.25 5.0
destination.txt
John 10000 10.5 2.5 2625.00
Jane 5000 9.25 5.0 2312.50
Program
package Q3_SimpleInterest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
while (in.hasNext())
{
String name = in.next();
float principal = in.nextFloat();
float rate = in.nextFloat();
float time = in.nextFloat();
float result = principal * rate * time ;
float interest = result/100;
Output:
3|Page
PREPARED BY: Dipendra Shrestha
4) Write a program to read the contents of a file one line at a time and output them to the
screen.
Program
package Q4_BufferReader;
import java.io.BufferedReader;
import java.io.FileReader;
try
{
in = new BufferedReader(new FileReader
("source_BufferReader.txt"));
String Line;
while(true)
{
Line = in.readLine();
if(Line == null)
break;
System.out.println(Line);
}
}
finally
{
if(in!= null)in.close();
}
}
}
Output:
4|Page
PREPARED BY: Dipendra Shrestha
5) Write a program to input whole lines from the keyboard and write them to a file. Exit the
program when the user types “quit”.
Program
package Q5_WriteIntoFile;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
while (true)
{
System.out.println("Enter your Text:");
String text = in.nextLine();
if (text.equals("quit"))
break;
out.write(text);
System.out.println(text);
}
}
finally
{
if(out!= null) out.close();
}
}
}
Output:
5|Page
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
1) Write a program using components to add two numbers. Use text fields. For inputs and output.
Your program should display the result when the user presses a button. [2069]
Program
package Q01_AddTwoNumbers;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
}
public AddTwoNumbers()
{
setLayout(new FlowLayout());
JLabel firstTextFieldLabel = new JLabel("First
Number:");
JTextField firstTextField = new JTextField(20);
add(firstTextFieldLabel);
add(firstTextField);
firstTextField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
secondTextField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
1|Page
PREPARED BY: Dipendra Shrestha
displayResultField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
calculateSum.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double firstNumber = Double.parseDouble
(firstTextField.getText());
Output:
2|Page
PREPARED BY: Dipendra Shrestha
2) Write a program using swing components to multiply two numbers. Use text fields for inputs and
output. Your program should display the result when the user presses a button. [2070]
Program
package Q02_MultiplyTwoNumbers;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
}
public MultiplyTwoNumbers()
{
setLayout(new FlowLayout());
JLabel firstTextFieldLabel = new JLabel("First
Number:");
JTextField firstTextField = new JTextField(20);
add(firstTextFieldLabel);
add(firstTextField);
firstTextField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
JLabel secondTextLabel = new JLabel("Second
Number:");
JTextField secondTextField = new JTextField(20);
add(secondTextLabel);
add(secondTextField);
secondTextField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
3|Page
PREPARED BY: Dipendra Shrestha
calculateProduct.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double firstNumber = Double.parseDouble
(firstTextField.getText());
Output
4|Page
PREPARED BY: Dipendra Shrestha
3) Write a program using swing components to find simple interest. Use text fields for inputs and
output. Your program should display the result when the user presses a button. [2071, 2074]
Program
package Q03_SimpleInterest;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleInterest()
{
add(new JLabel("Principle"));
JTextField principleTextField =new JTextField(5);
add(principleTextField);
add(new JLabel("Time"));
JTextField timeTextField = new JTextField(5);
add(timeTextField);
add(new JLabel("Rate"));
JTextField rateTextField = new JTextField(5);
add(rateTextField);
add(new JLabel("Interest"));
JTextField interestTextField =new JTextField(10);
interestTextField.setEditable(false);
add(interestTextField);
5|Page
PREPARED BY: Dipendra Shrestha
calculateInterest.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double principle = Double.parseDouble
(principleTextField.getText());
double calculateInterest =
(principle*rate*time)/100;
interestTextField.setText(String.valueOf
(calculateInterest));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
6|Page
PREPARED BY: Dipendra Shrestha
4) Design a GUI form using swing with a text field, a text label for displaying the input message “Input
any string”, and three buttons with caption “Check Palindrome”, “Reverse”, “Find Vowels”. Write
a complete program for above scenario and for checking palindrome in first button, reverse it after
clicking second button and extract the vowels from it after clicking third button. [2075]
Program
package Q04_PalindromeProgram;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
checkPalindromeButton.addActionListener(new
7|Page
PREPARED BY: Dipendra Shrestha
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String copyUserInput="";
String userInput =inputTextField.
getText();
int length = userInput.length();
reverseButton.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String reverseUserInput="";
String userInput = inputTextField.
getText();
int length = userInput.length();
findVowelButton.addActionListener(new
8|Page
PREPARED BY: Dipendra Shrestha
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
char[] vowel={'a','e','i','o','u',
'A','E','I','O','U'};
String userInput = inputTextField.
getText();
int length = userInput.length();
char[] extractedVowel= new char[length];
String showVowel="";
showVowel = showVowel +
String.valueOf
(extractedVowel[i]);
}
}
}
outputTextField.setText
("Vowels: "+showVowel);
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
output
Checking palindrome or not
9|Page
PREPARED BY: Dipendra Shrestha
10 | P a g e
PREPARED BY: Dipendra Shrestha
package Q05_BorderLayout;
import javax.swing.*;
import java.awt.*;
public BorderLayoutDemo()
{
setLayout(new BorderLayout());
add(topButton,BorderLayout.PAGE_START);
add(bottomButton,BorderLayout.PAGE_END);
add(leftButton,BorderLayout.LINE_START);
add(rightButton,BorderLayout.LINE_END);
add(centerButton,BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
output:
11 | P a g e
PREPARED BY: Dipendra Shrestha
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
add(new JLabel("Principle"));
JTextField principleTextField = new JTextField(5);
add(principleTextField);
add(new JLabel("Time"));
JTextField timeTextField = new JTextField(5);
add(timeTextField);
add(new JLabel("Rate"));
JTextField rateTextField = new JTextField(5);
add(rateTextField);
add(new JLabel("Interest"));
JTextField interestTextField = new JTextField(10);
interestTextField.setEditable(false);
add(interestTextField);
12 | P a g e
PREPARED BY: Dipendra Shrestha
calculateInterest.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double principle = Double.parseDouble
(principleTextField.getText());
double rate = Double.parseDouble
(rateTextField.getText());
double time = Double.parseDouble
(timeTextField.getText());
double calculateInterest =
(principle*rate*time)/100;
interestTextField.setText
(String.valueOf(calculateInterest));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output
13 | P a g e
PREPARED BY: Dipendra Shrestha
b) GridLayout
Program
package Q06_b_SimpleInterestGridLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleInterestGridLayout()
{
add(new JLabel("Principle"));
JTextField principleTextField = new
JTextField(5);
add(principleTextField);
add(new JLabel("Time"));
JTextField timeTextField = new JTextField(5);
add(timeTextField);
add(new JLabel("Rate"));
JTextField rateTextField = new JTextField(5);
add(rateTextField);
add(new JLabel("Interest"));
JTextField interestTextField = new
JTextField(10);
interestTextField.setEditable(false);
add(interestTextField);
add(new JLabel(""));
14 | P a g e
PREPARED BY: Dipendra Shrestha
calculateInterest.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double principle = Double.parseDouble
(principleTextField.getText());
double rate = Double.parseDouble
(rateTextField.getText());
double time = Double.parseDouble
(timeTextField.getText());
double calculateInterest =
(principle*rate*time)/100;
interestTextField.setText
(String.valueOf(calculateInterest));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output
15 | P a g e
PREPARED BY: Dipendra Shrestha
c) GridBagLayout
Program
package Q06_c_SimpleInterestGridBagLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleInterestGridBagLayout()
{
setLayout(new GridBagLayout());
GridBagConstraints s = new GridBagConstraints();
//For Principle
s.gridx =0;
s.gridy =0;
add(new JLabel("Principle"));
JTextField principleTextField=new JTextField(15);
add(principleTextField);
//For Rate
s.gridx =0;
s.gridy =1;
add(new JLabel("Time"),s);
JTextField timeTextField = new JTextField(15);
s.gridx = 1;
add(timeTextField,s);
//For Time
s.gridx =0;
s.gridy =2;
add(new JLabel("Rate"),s);
JTextField rateTextField = new JTextField(15);
s.gridx=1;
add(rateTextField,s);
16 | P a g e
PREPARED BY: Dipendra Shrestha
//For Button
s.fill =GridBagConstraints.BOTH;
s.gridx =1;
s.gridy =5;
s.gridwidth= 1;
JButton calculateInterest =new JButton("Calculate
Inrerest");
add(calculateInterest,s);
calculateInterest.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double principle = Double.parseDouble
(principleTextField.getText());
double calculateInterest =
(principle*rate*time)/100;
interestTextField.setText
(String.valueOf(calculateInterest));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
17 | P a g e
PREPARED BY: Dipendra Shrestha
7) Create a login form with username and password fields. Print “access granted” if the username
and password both are “admin”, when user clicks on Login button. If authentication fails, print
“access denied”.
Program
package Q07_LoginForm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public LoginFormDemo ()
{
setLayout(new FlowLayout());
add(new JLabel("Username"));
JTextField LoginTextField = new JTextField(5);
add(LoginTextField);
add(new JLabel("Password"));
JPasswordField LoginPasswordField = new
JPasswordField(10);
add(LoginPasswordField);
LoginButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String username = LoginTextField.getText();
char[] password = LoginPasswordField
.getPassword();
char[] actualPassword =
{'a','d','m','i','n'};
18 | P a g e
PREPARED BY: Dipendra Shrestha
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output
Username : admin
Password: admin
19 | P a g e
PREPARED BY: Dipendra Shrestha
Program
package Q08_Q09_NotepadApp;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
}
JTextArea textArea;
public NotePadApp()
{
Container c = this.getContentPane();
c.setLayout(null);
20 | P a g e
PREPARED BY: Dipendra Shrestha
fileMenu.addSeparator();
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
editMenu.addSeparator();
21 | P a g e
PREPARED BY: Dipendra Shrestha
editMenu.add(pasteMenuItem);
//**********************************************************
helpMenu.addSeparator();
22 | P a g e
PREPARED BY: Dipendra Shrestha
23 | P a g e
PREPARED BY: Dipendra Shrestha
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
chooser.setFileFilter(new FileNameExtensionFilter
("Text Files (*.txt)", "txt"));
chooser.setSelectedFile(new File(".txt"));
int result = chooser.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
PrintWriter out = null;
try
{
out = new PrintWriter(file);
out.print(text);
}
finally
{
out.close();
}
}
else
return;
}
fileChooser.setFileFilter(new FileNameExtensionFilter
("Text Files(*.txt)","txt"));
if(result == JFileChooser.APPROVE_OPTION)
{
File selectedFile=fileChooser.getSelectedFile();
BufferedReader in = null;
24 | P a g e
PREPARED BY: Dipendra Shrestha
try
{
in = new BufferedReader(new FileReader
(selectedFile));
StringBuilder sb = new StringBuilder();
String line;
while (true)
{
line = in.readLine();
sb.append(line + "\n");
if (line==null)
break;
textArea.setText(sb.toString());
}
}
finally
{
if (in!=null)in.close();
}
}
}
}
Output
25 | P a g e
PREPARED BY: Dipendra Shrestha
26 | P a g e
PREPARED BY: Dipendra Shrestha
27 | P a g e
PREPARED BY: Dipendra Shrestha
10) Create the UI for tic-tac-toe app using JButton array and GridLayout.
Program
package Q10_TicTacToeApp;
import javax.swing.*;
import java.awt.*;
Output
28 | P a g e
PREPARED BY: Dipendra Shrestha
11) Demonstrate the use of Open and Save dialogs for opening and saving files.
Program
package Q11_OpenAndSaveDialog;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
openMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent
actionEvent)
{
try {
openFile();
}
catch (Exception exception)
{
System.out.println(exception);
}
}
});
29 | P a g e
PREPARED BY: Dipendra Shrestha
saveMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String text = textArea.getText();
try {
saveFile(text);
}
catch(Exception execption)
{
System.out.println(execption);
}
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
fileChooser.setFileFilter(new FileNameExtensionFilter
("Text Files(*.txt)","txt"));
if(result == JFileChooser.APPROVE_OPTION)
{
File selectedFile =fileChooser.
getSelectedFile();
BufferedReader in = null;
String fileName = selectedFile.getName();
setTitle(fileName);
try{
in = new BufferedReader(new FileReader
(selectedFile));
StringBuilder sb = new StringBuilder();
String line;
while (true)
{
line = in.readLine();
sb.append(line + "\n");
if (line==null)
break;
textArea.setText(sb.toString());
}
}
30 | P a g e
PREPARED BY: Dipendra Shrestha
finally
{
if (in!=null) in.close();
}
}
}
chooser.setFileFilter(new FileNameExtensionFilter
("Text Files (*.txt)", "txt"));
chooser.setSelectedFile(new File(".txt"));
if(result == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
PrintWriter out = null;
try
{
out = new PrintWriter(file);
out.print(text);
}
finally
{
out.close();
}
}
else
return;
}
}
Output
31 | P a g e
PREPARED BY: Dipendra Shrestha
32 | P a g e
PREPARED BY: Dipendra Shrestha
12) Create a simple app with menus. Include a menu item inside the Help menu to show a custom
dialog named AboutDialog. The dialog must contain your App name, version and copyright
information, along with a working close button (JButton).
Program
package Q12_SimpleAppWithMenus;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
textArea.setEditable(false);
aboutDialog.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent
actionEvent)
{
dialogBox = new JDialog
(DialogDemo.this,"About App");
33 | P a g e
PREPARED BY: Dipendra Shrestha
dialogBox.setLayout(new FlowLayout());
dialogBox.setBounds(750,250,300,130);
dialogBox.setVisible(true);
dialogBox.add(textArea);
dialogBox.add(closeButton);
dialogBox.setResizable(false);
}
});
closeButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent
actionEvent)
{
dialogBox.dispose();
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output
34 | P a g e
PREPARED BY: Dipendra Shrestha
13) Create a form using JFrame to collect the records of students in Trinity. Each record should contain
the following information:
a) First Name (JTextField)
b) Last Name (JTextField)
c) Age (JTextField)
d) Gender (JRadioButton)
e) Faculty (JComboBox/JList)
f) Semester (JComboBox/JList)
g) Remarks (JTextArea)
Add both menus and toolbars to save the form to a file (display a save dialog). Also add
menu/toolbar items to reset the form as well as exit the program. Remember to close the file on
exit command.
Program
package Q13_StudentsRecodrs;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
JTextField firstNameField,lastNameField,ageField;
JRadioButton maleRadioButton,femaleRadioButton;
JComboBox facultyComboBox,semesterComboBox;
JTextArea remarksTextArea;
ButtonGroup group;
public StudentsRecord()
{
setLayout(new GridLayout(18,0));
35 | P a g e
PREPARED BY: Dipendra Shrestha
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
36 | P a g e
PREPARED BY: Dipendra Shrestha
add(firstNameLabel);
add(firstNameField);
add(lastNameLabel);
add(lastNameField);
add(ageLabel);
add(ageField);
add(genderLabel);
group = new ButtonGroup();
add(maleRadioButton);
add(femaleRadioButton);
group.add(maleRadioButton);
group.add(femaleRadioButton);
add(facultyLabel);
add(facultyComboBox);
add(semesterLabel);
add(semesterComboBox);
add(remarksLabel);
add(remarksTextArea);
saveButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
String[] text = getFieldValue();
try
{
saveFormData(text);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
});
37 | P a g e
PREPARED BY: Dipendra Shrestha
resetButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
resetMethods();
}
});
exitButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
System.exit(0);
}
});
saveMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
String[] text = getFieldValue();
try
{
saveFormData(text);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
});
resetMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
resetMethods();
}
});
exitMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
System.exit(0);
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
38 | P a g e
PREPARED BY: Dipendra Shrestha
String[] text = {
firstNameField.getText(),
lastNameField.getText(),
ageField.getText(),
group.getSelection().getActionCommand(),
(String)facultyComboBox.getSelectedItem(),
(String)semesterComboBox.getSelectedItem(),
remarksTextArea.getText()
};
return text;
}
private void saveFormData (String[] text) throws IOException
{
String userDir = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser
(userDir+"/Desktop");
chooser.setFileFilter(new FileNameExtensionFilter("Text
Files (*.txt)", "txt"));
chooser.setSelectedFile(new File(".txt"));
int result = chooser.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
PrintWriter out = null;
try
{
out = new PrintWriter(file);
for (int i=0; i<text.length; i++)
{
out.print(text[i]+"\n");
}
}
finally
{
out.close();
}
}
else
return;
}
39 | P a g e
PREPARED BY: Dipendra Shrestha
Output
40 | P a g e
PREPARED BY: Dipendra Shrestha
41 | P a g e
PREPARED BY: Dipendra Shrestha
42 | P a g e
PREPARED BY: Dipendra Shrestha
If we press ‘Reset’ menu item then our form field will be reset.
43 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
SQL Query:
create database JavaJDBC;
use JavaJDBC;
CREATE TABLE students
(
id int NOT NULL AUTO_INCREMENT,
name varchar(25) NOT NULL,
district varchar(25),
age int,
PRIMARY KEY (id)
);
1|Page
PREPARED BY: Dipendra Shrestha
1) Write a Java program using JDBC to extract name of those students who live in Kathmandu district,
assuming that the student table has four attributes (ID, name, district, and age). [2072]
Program
package Q01_ExtractStudentInformation;
import java.sql.*;
public class Students
{
public static void main(String[] args) throws
SQLException
{
//******* Establishing Connection to the Database********
Output
2|Page
PREPARED BY: Dipendra Shrestha
2) Write a program to illustrate the process of executing SQL statements in JDBC? [2073, 2074]
3) Implement CRUD (Create/Insert, Read/Select, Update, Delete) operations for student table. Ask
for user input where applicable.
Program
Create Operation
package Q02_Q03_SQLStatements;
import java.sql.*;
import java.util.Scanner;
3|Page
PREPARED BY: Dipendra Shrestha
output:
Read Operation
package Q02_Q03_SQLStatements;
import java.sql.*;
import java.util.Scanner;
4|Page
PREPARED BY: Dipendra Shrestha
if (userChoice == 'Y')
{
String sql = "select * from students";
ResultSet resultSet = statement.
executeQuery(sql);
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s, \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
}
if(userChoice== 'N')
{
System.out.println("Enter the Id to select
from database:");
int id = in.nextInt();
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
}
statement.close(); //statement has to be close.
connection.close();
}
}
5|Page
PREPARED BY: Dipendra Shrestha
Output
If user wish to see the database table details before executing ‘Read’ operation.
If user wants to execute ‘Read’ operation directly without seeing details in database table.
Update Operation
package Q02_Q03_SQLStatements;
import java.sql.*;
import java.util.Scanner;
6|Page
PREPARED BY: Dipendra Shrestha
createStatement();
if (userChoice == 'Y')
{
String sql = "select * from students";
ResultSet resultSet = statement.
executeQuery(sql);
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s, \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
}
//***If user knows what to update in database table*****
if (userChoice == 'N')
{
7|Page
PREPARED BY: Dipendra Shrestha
if (rowUpdated > 0)
System.out.println("Row updated
Successfully!!");
else
System.out.println("Row isn't Updated!!");
}
statement.close(); //statement has to be close.
connection.close(); // connection is also closed.
}
}
Output:
If user wish to see the database table details before executing ‘Update’ operation.
If user wants to execute ‘Update’ operation directly without seeing details in database table.
8|Page
PREPARED BY: Dipendra Shrestha
Delete Operation
package Q02_Q03_SQLStatements;
import java.sql.*;
import java.util.Scanner;
if (userChoice == 'Y')
{
String sql = "select * from students";
ResultSet resultSet = statement.
executeQuery(sql);
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s,\n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
9|Page
PREPARED BY: Dipendra Shrestha
if(userChoice== 'N')
{
System.out.println("Enter the Id to Delete
from database:");
int id = in.nextInt();
if (rowDeleted > 0)
System.out.println("Row Deleted
Successfully!!");
else
System.out.println("Row isn't
Deleted!!");
statement.close();
connection.close();
}
}
}
Output
If user wish to see the database table details before executing ‘Delete’ operation.
If user wants to execute ‘Delete’ operation directly without seeing details in database table.
10 | P a g e
PREPARED BY: Dipendra Shrestha
4) Implement CRUD operations for student table using prepared statements. Ask for user input
where applicable.
Program
package Q04_CrudPreparedStatement;
import java.sql.*;
import java.util.Scanner;
System.out.println("Enter Name:");
String name = in.next();
System.out.println("Enter District:");
String district = in.next();
System.out.println("Enter Age:");
int age = in.nextInt();
11 | P a g e
PREPARED BY: Dipendra Shrestha
if(rowInserted>0)
System.out.println("Row Inserted
Successfully!");
else
System.out.println("Row Insertion Failed!!");
statement.close();
connection.close();
}
}
Output
12 | P a g e
PREPARED BY: Dipendra Shrestha
package Q04_CrudPreparedStatement;
import java.sql.*;
import java.util.Scanner;
if (userChoice == 'Y')
{
String sql = "select * from students";
PreparedStatement statement = connection.
prepareStatement(sql);
ResultSet resultSet = statement.
executeQuery();
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s, \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
statement.close();
}
if(userChoice== 'N')
{
System.out.println("Enter the Id to select
from database:");
int id = in.nextInt();
13 | P a g e
PREPARED BY: Dipendra Shrestha
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
statement.close();
}
connection.close();
}
}
Output
If user wish to see the database table details before executing ‘Read’ operation.
If user wants to execute ‘Read’ operation directly without seeing details in database table.
14 | P a g e
PREPARED BY: Dipendra Shrestha
package Q04_CrudPreparedStatement;
import java.sql.*;
import java.util.Scanner;
if (userChoice == 'Y')
{
String sql = "select * from students";
PreparedStatement statement = connection.
prepareStatement(sql);
ResultSet resultSet = statement.
executeQuery(sql);
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s, \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
statement.close();
}
if (userChoice == 'N')
{
System.out.println("Enter the Id to update
into database:");
int id = in.nextInt();
15 | P a g e
PREPARED BY: Dipendra Shrestha
statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
statement.setInt(4,id);
if (rowUpdated > 0)
System.out.println("Row updated
Successfully!!");
else
System.out.println("Row isn't
Updated!!");
statement.close();
}
connection.close();
}
}
Output
If user wish to see the database table details before executing ‘Update’ operation.
16 | P a g e
PREPARED BY: Dipendra Shrestha
If user wants to execute ‘Update’ operation directly without seeing details in database table.
package Q04_CrudPreparedStatement;
import java.sql.*;
import java.util.Scanner;
17 | P a g e
PREPARED BY: Dipendra Shrestha
if (userChoice == 'Y')
{
String sql = "select * from students";
PreparedStatement statement = connection.
prepareStatement(sql);
ResultSet resultSet = statement.
executeQuery();
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %s, \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getString("age")
);
}
}
if (userChoice == 'N')
{
System.out.println("Enter the Id to Delete
from database:");
int id = in.nextInt();
statement.setInt(1, id);
if (rowDeleted > 0)
System.out.println("Row Deleted
Successfully!!");
else
System.out.println("Row isn't
Deleted!!");
statement.close();
connection.close();
}
}
}
18 | P a g e
PREPARED BY: Dipendra Shrestha
Output:
If user wish to see the database table details before executing ‘Delete’ operation.
If user wants to execute ‘Delete’ operation directly without seeing details in database table.
19 | P a g e
PREPARED BY: Dipendra Shrestha
5) Implement CRUD operations for student table in Swing. Ask for user input where applicable.
Program
package Q05_CrudSwing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
String name,district;
int age = NULL;
public CrudSwingInsert()
{
setLayout(new GridLayout(5,1,5,5));
insertButton.addActionListener(new ActionListener()
20 | P a g e
PREPARED BY: Dipendra Shrestha
{
@Override
try
{
age = Integer.parseInt
(ageTextField.getText());
}
catch (NumberFormatException e)
{
}
if(name.equals("")|| district.equals("")||
age == NULL)
{
JOptionPane.showMessageDialog(null,"Values aren't
acceptable!! Either fields are empty
or 'Age' is not an integer type.",
"Failure"
,JOptionPane.ERROR_MESSAGE);
}
else {
InsertIntoDatabase();
}
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
try {
String url = "jdbc:mariadb://localhost:3306/
JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection(url, username, password);
setLayout(new GridLayout(5,1,5,5));
String sql = String.format("Insert into students
(name,district,age) Values (?,?,?)");
PreparedStatement statement = connection.
prepareStatement(sql);
21 | P a g e
PREPARED BY: Dipendra Shrestha
statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
int rowInserted = statement.executeUpdate();
if(rowInserted>0)
JOptionPane.showMessageDialog(null,"Row
Inserted Successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Row
Inserted Successfully","Failure"
,JOptionPane.ERROR_MESSAGE);
statement.close();
connection.close();
}
catch (Exception e)
{
System.out.println("Error:"+ e.getMessage());
}
}
}
Output
22 | P a g e
PREPARED BY: Dipendra Shrestha
package Q05_CrudSwing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
int id;
JTextArea textArea;
Container c;
public CrudSwingSelect()
{
c = this.getContentPane();
c.setLayout(null);
//Adding TextArea
textArea = new JTextArea();
textArea.setBounds(80,60,250,200);
add(textArea);
selectButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
23 | P a g e
PREPARED BY: Dipendra Shrestha
try
{
id = Integer.parseInt(idField.getText());
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Values aren't
acceptable!! 'ID' is not an integer
type.","Failure",JOptionPane.ERROR_MESSAGE);
}
SelectFromDatabase();
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void SelectFromDatabase()
{
try
{ String url = "jdbc:mariadb://localhost:3306/JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.getConnection(url,
username, password);
String sql = "select * from students where id = ?";
PreparedStatement statement = connection.
prepareStatement(sql);
statement.setInt(1,id);
ResultSet resultSet = statement.executeQuery();
int id=0,age=0;
String name="",district="";
while (resultSet.next())
{
id=resultSet.getInt("id");
name = resultSet.getString("name");
district = resultSet.getString("district");
age= resultSet.getInt("age");
}
textArea.setText("ID:" + id +"\nName:" +name +"\nDistrict:"
+district+"\nAge:"+age);
statement.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
24 | P a g e
PREPARED BY: Dipendra Shrestha
Output
package Q05_CrudSwing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public CrudSwingUpdate()
{
setLayout(new GridLayout(5,1,10,20));
25 | P a g e
PREPARED BY: Dipendra Shrestha
updateButton.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent
actionEvent)
{
try
{
int id = Integer.parseInt
(idTextField.getText());
String name = nameTextField.
getText();
String district = districtTextField.
getText();
int age = Integer.parseInt
(ageTextField.getText());
UpdateDatabase(id,name,district,age);
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Values
aren't acceptable!! Either Fields
are empty or type mismatched.
","Failure",JOptionPane.ERROR_MESSAGE);
}
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void UpdateDatabase(int id, String name,
String district, int age)
{
26 | P a g e
PREPARED BY: Dipendra Shrestha
try
{
String url = "jdbc:mariadb://localhost:3306
/JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection(url, username, password);
statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
statement.setInt(4,id);
if (rowUpdated > 0)
JOptionPane.showMessageDialog(null,"Rows
update successfully!!.
","Success",JOptionPane.
INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Rows
aren't updated!!","Failure"
,JOptionPane.ERROR_MESSAGE);
statement.close();
connection.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
27 | P a g e
PREPARED BY: Dipendra Shrestha
Output
28 | P a g e
PREPARED BY: Dipendra Shrestha
package Q05_CrudSwing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
deleteButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
try {
int id = Integer.parseInt
(idTextField.getText());
DeleteFromDatabase(id);
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Values
aren't acceptable!! Either fields
are empty or type mismatched.",
"Failure",JOptionPane.ERROR_MESSAGE);
29 | P a g e
PREPARED BY: Dipendra Shrestha
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void DeleteFromDatabase(int id)
{
try
{
statement.setInt(1, id);
if (rowDeleted > 0)
JOptionPane.showMessageDialog(null,"Row
deleted Successfully."
,"Success",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Row
can't be deleted.","Failure`
",JOptionPane.ERROR_MESSAGE);
statement.close();
connection.close();
}
catch (Exception e)
{
}
}
}
30 | P a g e
PREPARED BY: Dipendra Shrestha
Output
31 | P a g e
PREPARED BY: Dipendra Shrestha
6) Implement account balance transfer operation (use transactions). Ask for user input where
applicable
Program
Deposit transaction
package Q06_Transaction;
import javax.swing.*;
import java.sql.*;
import java.util.*;
try {
String debitSql = "Update MyAccount set balance
= balance + ? where id= ?";
PreparedStatement statement = connection.
prepareStatement(debitSql);
statement.setDouble(1, amount);
statement.setInt(2, id);
statement.executeUpdate();
}
catch (SQLException e)
{
connection.rollback();
System.out.println("Transaction Error!!");
}
32 | P a g e
PREPARED BY: Dipendra Shrestha
}
}
Output
33 | P a g e
PREPARED BY: Dipendra Shrestha
Withdraw Transaction
package Q06_Transaction;
import java.sql.*;
import java.util.Scanner;
try {
String debitSql = "Update MyAccount set balance = balance
- ? where id= ?";
PreparedStatement statement = connection.
prepareStatement(debitSql);
statement.setDouble(1, amount);
statement.setInt(2, id);
statement.executeUpdate();
connection.commit();
System.out.println("Amount: " + amount + " has been
sucessfully withdrawn from id: "+ id);
}
catch (SQLException e)
{
connection.rollback();
System.out.println("Transaction Error!!");
}
}
}
34 | P a g e
PREPARED BY: Dipendra Shrestha
35 | P a g e
PREPARED BY: Dipendra Shrestha
Transfer Transaction
package Q06_Transaction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
statement.executeUpdate();
statement1.executeUpdate();
connection.commit();
System.out.println("Amount: Rs " + amount +" has been
36 | P a g e
PREPARED BY: Dipendra Shrestha
catch (SQLException e)
{
connection.rollback();
System.out.println("Transaction Error!!");
}
}
}
Output:
37 | P a g e
PREPARED BY: Dipendra Shrestha
38 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
1) Write two programs that can communicate in a network using TCP Socket? [2070, 7073, 2074]
Program
Client Side
import java.util.Scanner;
System.out.println("Client started.");
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter
(socket.getOutputStream(), true);
Scanner in = new Scanner
(socket.getInputStream());
Scanner s = new Scanner(System.in);
) {
while (true)
{
System.out.print("Input: ");
String input = s.nextLine();
out.println(input);
if (input.equalsIgnoreCase("exit")) break;
Server Side
package EchoServer;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
1|Page
PREPARED BY: Dipendra Shrestha
System.out.println("Listening to client...");
try (
ServerSocket serverSocket = new
ServerSocket(PORT);
Socket clientSocket = serverSocket.
accept();
PrintWriter out = new PrintWriter
(clientSocket.getOutputStream(), true);
Scanner in = new Scanner
(clientSocket.getInputStream());
) {
while (true)
{
String input = in.nextLine();
if (input.equalsIgnoreCase("exit")) break;
System.out.println("Received from client: "
+ input);
out.println(input);
}
}
System.out.println("Server stopped");
}
}
Output
2|Page
PREPARED BY: Dipendra Shrestha
package InetAddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
output
3|Page
PREPARED BY: Dipendra Shrestha
3) Write client and server programs in which a server program accepts a radius of a circle from the
client program, computes area, sends the computed area to the client program, and displays it
by client program. [2075]
Program
Client Side
package AreaofCircle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.Scanner;
System.out.println("Client started.");
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter
(socket.getOutputStream(), true);
Scanner in = new Scanner
(socket.getInputStream());
Scanner s = new Scanner(System.in);
) {
while (true)
{
System.out.print("Enter radius: ");
double radius = s.nextDouble();
out.println(radius);
System.out.println("Area of Circle
returned from server: "
+ in.nextDouble());
System.out.println("Do you want to
exit?(Y/N):");
String choice = s.next();
out.println(choice);
if(choice.equalsIgnoreCase("Y"))
break;
}
}
System.out.println("Client has been stopped....");
}
}
4|Page
PREPARED BY: Dipendra Shrestha
Server Side
package AreaofCircle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
try (
ServerSocket serverSocket = new
ServerSocket(PORT);
5|Page
PREPARED BY: Dipendra Shrestha
Output
Client Side
Server Side
6|Page
PREPARED BY: Dipendra Shrestha
package EmailSMTP;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;
public class SendEmail
{
public static void main(String[] args) throws
IOException {
Email email = new Email(
"dipen.stha8786@gmail.com",
"dipen.stha9860@hotmail.com",
"Test email." );
email.send();
}
}
class Email {
private Scanner in = null;
private PrintWriter out = null;
private final String SMTP_SERVER =
"smtp.wlink.com.np";
private final int SMTP_PORT = 25;
private String from = null;
private String to = null;
private String message = null;
public Email(String from, String to, String
message)
{
this.from = from;
this.to = to;
this.message = message;
}
private void send(String s) throws IOException {
System.out.println(">> " + s);
out.print(s.replaceAll("\n", "\r\n"));
out.print("\r\n");
out.flush();
}
private void receive() throws IOException
{
String line = in.nextLine();
System.out.println(" " + line);
}
public void send() throws IOException
{
Socket socket = new Socket(SMTP_SERVER,
7|Page
PREPARED BY: Dipendra Shrestha
SMTP_PORT);
in = new Scanner(socket.getInputStream());
out = new
PrintWriter(socket.getOutputStream(), true);
String hostName = InetAddress.getLocalHost()
.getHostName();
receive();
send("HELO " + hostName);
receive();
send("MAIL FROM: <" + from + ">"); receive();
send("RCPT TO: <" + to + ">"); receive();
send("DATA"); receive();
send(message);
send("."); receive();
socket.close();
}
}
Output
8|Page
PREPARED BY: Dipendra Shrestha
5) Write client and server programs in which a server program accepts the length and breadth of
a rectangle from the client program, computes area, sends the computed area to the client
program, and displays it by client program.
Program
Client Side
package AreaofRectangle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.Scanner;
System.out.println("Client started.");
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter
(socket.getOutputStream(), true);
Scanner in = new Scanner
(socket.getInputStream());
Scanner s = new Scanner(System.in);
) {
while (true)
{
System.out.print("Enter length to calculate
area of rectangle: ");
double length = s.nextDouble();
System.out.println("Enter breadth to
calculate area of rectangle:");
double breadth = s.nextDouble();
out.println(length);
out.println(breadth);
System.out.println("Area of Rectangle
returned from server: " +
in.nextDouble());
System.out.println("Do you want to
exit?(Y/N):");
String choice = s.next();
out.println(choice);
if(choice.equalsIgnoreCase("Y"))
break;
}
}
System.out.println("Client has been stopped....");
}
}
9|Page
PREPARED BY: Dipendra Shrestha
Server Side
package AreaofRectangle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
try (
ServerSocket serverSocket = new
ServerSocket(PORT);
Socket clientSocket =
serverSocket.accept();
PrintWriter out = new PrintWriter
(clientSocket.getOutputStream(),true);
Scanner in = new Scanner
(clientSocket.getInputStream());
) {
while (true)
{
double length = in.nextDouble();
double breadth = in.nextDouble();
double area = length*breadth;
}
}
10 | P a g e
PREPARED BY: Dipendra Shrestha
Output
Client Side
Server Side
11 | P a g e
PREPARED BY: Dipendra Shrestha
Client Side
package Client;
import java.net.*;
import java.io.*;
public class UDPEchoClient
{
public static void main(String[] args) throws Exception
{
InetAddress address = null;
int port = 8000;
DatagramSocket datagramSocket = null;
BufferedReader keyboardReader = null;
try
{
address = InetAddress.getByName("127.0.0.1");
datagramSocket = new DatagramSocket();
keyboardReader = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Client Started...");
String input;
while (true)
{
System.out.println("Enter Input: ");
input = keyboardReader.readLine();
12 | P a g e
PREPARED BY: Dipendra Shrestha
Server Side
package Server;
import java.net.*;
import java.io.*;
public class UDPEchoServer
{
public static void main(String args[])
{
int port = 8000;
try
{
serverDatagramSocket = new DatagramSocket(port);
System.out.println("Created UDP Echo Server on
port"+port);
while(true)
{
serverDatagramSocket.receive(datagramPacket);
input = new String(datagramPacket.getData(),
0,datagramPacket.getLength());
if (input.equalsIgnoreCase("exit")) break;
}
System.out.println("Server has been stopped...");
}
catch(IOException e)
{
System.out.println(e);
System.exit(1);
}
}
}
13 | P a g e
PREPARED BY: Dipendra Shrestha
Output
Client Side
Server Side
14 | P a g e
PREPARED BY: Dipendra Shrestha
7) Write client and server programs in which a server program accepts a radius of a circle from the
client program, computes area, sends the computed area to the client program, and displays it
by client program. The server should be able to handle multiple clients.
Program
Client side
package MultipleClient;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter
(socket.getOutputStream(), true);
}
catch (Exception e)
{
}
}
}
15 | P a g e
PREPARED BY: Dipendra Shrestha
Server Side
16 | P a g e
PREPARED BY: Dipendra Shrestha
Output
1st Client
2nd Client
Server
17 | P a g e
PREPARED BY: Dipendra Shrestha
8) Write client and server programs in which a server program accepts the length and breadth of
a rectangle from the client program, computes area, sends the computed area to the client
program, and displays it by client program. The server should be able to handle multiple clients.
Program
Client Side
package MultipleClient;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
}
}
}
18 | P a g e
PREPARED BY: Dipendra Shrestha
Server Side
package ServerSide;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
19 | P a g e
PREPARED BY: Dipendra Shrestha
{
}
}
};
t.start();
}
}
Output
1st Client
2nd Client
Server
20 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
package Q01_JavaBean;
import java.awt.Graphics;
import javax.swing.JPanel;
}
public int getBreadth()
{
return breadth;
}
public void setBreadth(int breadth)
{
this.breadth = breadth;
repaint();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(x, y, l, y);
}
}
1|Page
PREPARED BY: Dipendra Shrestha
import java.awt.Image;
import java.beans.BeanInfo;
import java.beans.SimpleBeanInfo;
public RectangleBeanInfo()
{
iconColor16 = loadImage("/images/Rectangle16x16.png");
iconColor32 = loadImage("/images/Rectangle32x32.png");
iconMono16 = loadImage("/images/Rectangle16x16.png");
iconMono32 = loadImage("/images/Rectangle32x32.png");
}
@Override
public Image getIcon(int iconType)
{
switch (iconType)
{
case BeanInfo.ICON_COLOR_16x16:
return iconColor16;
case BeanInfo.ICON_COLOR_32x32:
return iconColor32;
case BeanInfo.ICON_MONO_16x16:
return iconMono16;
case BeanInfo.ICON_MONO_32x32:
return iconMono32;
default:
return null;
}
}
}
2|Page
PREPARED BY: Dipendra Shrestha
3|Page
PREPARED BY: Dipendra Shrestha
4|Page
PREPARED BY: Dipendra Shrestha
Output:
Now we use Rectangle bean from different package i.e. from ‘UseBeans’
5|Page
PREPARED BY: Dipendra Shrestha
2. Create a custom Java Bean named Ellipse which can be used to draw an ellipse.
Program
package Q02_EllipseBean;
import java.awt.Graphics;
import javax.swing.JPanel;
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (minorAxis <= 0 || majorAxis<=0) return;
6|Page
PREPARED BY: Dipendra Shrestha
package Q02_EllipseBean;
import java.awt.Image;
import java.beans.BeanInfo;
import java.beans.SimpleBeanInfo;
public EllipseBeanInfo()
{
iconColor16 = loadImage("/images/Ellipse16x16.png");
iconColor32 = loadImage("/images/Ellipse32x32.png");
iconMono16 = loadImage("/images/Ellipse6x16.png");
iconMono32 = loadImage("/images/Ellipse32x32.png");
}
@Override
public Image getIcon(int iconType)
{
switch (iconType)
{
case BeanInfo.ICON_COLOR_16x16:
return iconColor16;
case BeanInfo.ICON_COLOR_32x32:
return iconColor32;
case BeanInfo.ICON_MONO_16x16:
return iconMono16;
case BeanInfo.ICON_MONO_32x32:
return iconMono32;
default:
return null;
}
}
}
7|Page
PREPARED BY: Dipendra Shrestha
8|Page
PREPARED BY: Dipendra Shrestha
9|Page
PREPARED BY: Dipendra Shrestha
Output:
Now we use Ellipse bean from different package i.e. from ‘UseBeans’
10 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
Name:
Program: B. Sc. (CSIT)
Roll No:
Semester: seventh (7th)
Date:
KATHMANDU, NEPAL
2020
Unit 7: Servlets and Java Server Pages
<%--
Document : Display10Times
Created on : Jun 26, 2020, 9:13:20 AM
Author : dipen
--%>
Output:
1|Page
2. Write a simple JSP program to display “Lalitpur, Nepal” 10 times. [2070]
Program
<%--
Document : Display10Times
Created on : Jun 26, 2020, 9:13:20 AM
Author : dipen
--%>
Output:
2|Page
3. Write a simple JSP program to display “Tribhuvan University” 10 times. [2071, 2074]
Program
<%--
Document : Display10Times
Created on : Jun 26, 2020, 9:13:20 AM
Author : dipen
--%>
Output:
3|Page
4. Write a program that to illustrate the use of JSP. [2073]
Program
<%--
Document : UsingJSP
Created on : Jun 26, 2020, 9:22:29 AM
Author : dipen
--%>
Output:
4|Page
5. Write a program to create a JSP web form to take input of a student and submit it to second JSP
file which may simply print the values of form submission. [2075]
Program
StudentForm.jsp
<%--
Document : StudentForm
Created on : Jun 26, 2020, 9:26:23 AM
Author : dipen
--%>
PrintDetail.jsp
<%--
Document : PrintDetail
Created on : Jun 26, 2020, 9:33:47 AM
Author : dipen
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Print Student Details.</title>
</head>
<body>
<h1>Student Details!</h1>
Name: <%= request.getParameter("name") %><br>
Roll No.: <%= request.getParameter("roll") %><br>
Address: <%= request.getParameter("address") %><br>
</body>
</html>
5|Page
Output:
6|Page
6. Write a simple Servlet program to display “Kathmandu, Nepal” 10 times.
Program
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns ={"/Display10Times"})
public class Display10Times extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Message</title>");
for(int i = 1; i<=10; i++)
{
out.println("<h1>Kathmandu Nepal.</h1>");
}
out.println("</head>");
}
}
}
Output:
7|Page
7. Write a Servlet program to process a login form and authenticate the user. You can use
hardcoded values for username and password.
Program
LoginForm.html
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-
scale=1.0">
</head>
<body>
<form action="LoginDemo" method="POST">
</form>
</body>
</html>
LoginDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/LoginDemo"})
public class LoginDemo extends HttpServlet
{
8|Page
out.println("</head>");
out.println("<body>");
Output:
9|Page
If username or password is other than admin then user is invalid.
8. Write a Servlet program to show how to create and retrieve the value of a cookie.
Program
UserForm.html
<html>
<head>
<title>User Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<form action="WelcomeCookie" method="POST">
Username: <input type="text" name="username"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
WelcomeCookie.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
10 | P a g e
@WebServlet(urlPatterns = {"/WelcomeCookie"})
public class WelcomeCookie extends HttpServlet
{
//create Cookie
private void addCookies(HttpServletResponse response,String name,
String value)
{
Cookie cookie = new Cookie(name, value);
response.addCookie(cookie);
}
//Read Cookie
private String getCookie(HttpServletRequest request, String name)
{
Cookie[] cookies = request.getCookies();
if(cookies == null)
return null;
for(Cookie cookie: cookies)
{
if(cookie.getName().equals(name))
return cookie.getValue();
}
return null;
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet WelcomeCookie</title>");
out.println("</head>");
out.println("<body>");
//Creating Cookie
addCookies(response, name, name);
out.print("Cookie was created with the cookie name as " +
name);
//calling getCookie() method to get the cookie value
String cookieValue = getCookie(request,name);
if(cookieValue!=null)
out.println("</br>Welcome " + cookieValue);
out.println("</body>");
out.println("</html>");
}
}
}
Output:
11 | P a g e
Cookies stored in browser
9. Write a JSP program to demonstrate login, logout and secure admin page.
Program
LoginForm.jsp
<%
String error ="";
if(request.getMethod().equalsIgnoreCase("POST"))
{
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("admin"))
{
session.setAttribute("username", username);
response.sendRedirect("admin.jsp");
}
else
{
error = "Invalid Username or Password!!";
}
}
%>
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>User Login Form.</h1>
<form action ="" method="POST">
Username: <input type="text" name="username"><br><br>
Password:<input type="password" name="password"><br><br>
<p style= color:red;><%= error %></p>
<input type="Submit" value="Submit">
</body>
</html>
12 | P a g e
admin.jsp
<%--
Document : admin.jsp
Created on : Jun 28, 2020, 11:27:32 AM
Author : dipen
--%>
<%
String username = (String)session.getAttribute("username");
if(username == null || username.equals(""))
{
response.sendRedirect("LoginForm.jsp");
}
%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Admin Page.</title>
</head>
<body>
<h1 style="color:green">Welcome to the Admin Page!</h1>
<a href="logout.jsp">Logout</a>
</body>
</html>
logout.jsp
<%--
Document : logout
Created on : Jun 28, 2020, 11:24:39 AM
Author : dipen
--%>
Output:
13 | P a g e
Username and password with ‘admin’ is only valid.
If we type in url to directly access admin.jsp page then it will redirect to LoginForm.jsp if
authenticated user hasn’t logged in before.
14 | P a g e
After logout is pressed
10. Write a JSP program to show how to use custom error page.
Program
Index.jsp
error.jsp
15 | P a g e
Output:
16 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)
Name:
Program: B. Sc. (CSIT)
Roll No:
Semester: seventh (7th)
Date:
KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
RmiClient.java
package Q1_rmiclient;
import compute.*;
import java.rmi.Naming;
RmiServer.java
package Q1_rmiserver;
import compute.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
1|Page
PREPARED BY: Dipendra Shrestha
}catch(Exception e)
{
System.err.println("RmiServer Exception.");
}
}
}
Output:
2|Page
PREPARED BY: Dipendra Shrestha
2. Write distributed programs with client and server using RMI to find the area of a
a) Circle
b) Rectangle, and
c) Sphere
a) Circle
Program
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
RmiClientCircle.java
package q2_a_rmiclientcircle;
import compute.*;
import java.rmi.Naming;
3|Page
PREPARED BY: Dipendra Shrestha
RmiServerCircle.java
package q2_a_rmiservercircle;
import compute.*;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
}catch(Exception e)
{
System.err.println("RmiServer Exception.");
}
}
}
Output:
4|Page
PREPARED BY: Dipendra Shrestha
b) Rectangle
Program
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
RmiClientRectangle.java
package q2_b_rmiclientrectangle;
import compute.Compute;
import java.rmi.Naming;
try{
String url = "rmi://127.0.0.1:8888/Compute";
Compute compute = (Compute)Naming.lookup(url);
double result = compute.calcArea(5,6);
System.out.println("Area of Rectangle= "+ result);
}
catch(Exception e)
{
System.err.println("Remote exception:");
}
}
}
RmiServerRectangle.java
package q2_b_rmiserverrectangle;
import compute.Compute;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
5|Page
PREPARED BY: Dipendra Shrestha
}
catch(Exception e)
{
System.err.println("RmiServer Exception.");
}
}
Output:
6|Page
PREPARED BY: Dipendra Shrestha
c) Sphere
Program
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
RmiClientSphere.java
package q2_c_rmiclientsphere;
import compute.Compute;
import java.rmi.Naming;
RmiServerSphere.java
package q2_c_rmiserversphere;
import compute.Compute;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
7|Page
PREPARED BY: Dipendra Shrestha
}
catch(Exception e)
{
System.err.println("RmiServer Exception.");
}
}
}
Output:
8|Page