0% found this document useful (0 votes)
119 views184 pages

Java Assignment Coding Practice

Uploaded by

Bishal Chapagain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
119 views184 pages

Java Assignment Coding Practice

Uploaded by

Bishal Chapagain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 184

Java Lab Assignment

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: Programming in Java


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]
2) Write an object oriented program to find area and perimeter of rectangle. [2073, 2074]
3) Write a program to input and add two numbers using static methods (procedural programming).
4) Write a program to input principle, time and rate, then calculate simple interest using static methods.
5) Write both procedural and object oriented programs to calculate the area of a
a) Circle
b) Square
c) Rectangle
d) Sphere
6) Write a static method to calculate the sum of a one dimensional array.
7) Write a static method to calculate the average of a one dimensional array.
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.
9) Write a program to demonstrate encapsulation.
10) Write a program to demonstrate inheritance.
11) Write a program to demonstrate polymorphism using non-abstract class as parent.
12) Write a program to demonstrate polymorphism using abstract class as parent.
13) Write a program to demonstrate polymorphism using interface as parent.
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.

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”.

Unit 2, 3: User Interface Components with Swing, Event Handling


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]
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]
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]
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]
5) Write a program to illustrate the use of BorderLayout. [2073]
6) Write a program to calculate simple interest using
a) FlowLayout
b) GridLayout
c) GridBagLayout
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”.
8) (Optional) Create a basic notepad app with the following features:
a) New
b) Open
c) Save
d) Exit
Use JButton components to implement these features.
9) Create an application with UI similar to the windows notepad app.
10) Create the UI for tic-tac-toe app using JButton array and GridLayout.
11) Demonstrate the use of Open and Save dialogs for opening and saving files.
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).
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.

Unit 4: Database Connectivity


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]
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.
4) Implement CRUD operations for student table using prepared statements. Ask for user input where
applicable.
5) Implement CRUD operations for student table in Swing. Ask for user input where applicable.
6) Implement account balance transfer operation (use transactions). Ask for user input where applicable.

Unit 5: Network Programming


1) Write two programs that can communicate in a network using TCP Socket? [2070, 7073, 2074]
2) Write a program to illustrate the use of InetAddress class. [2073]
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]
4) Write a program to send email using Java [2073, 2074]
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.
6) Write echo server and echo client program using UDP.
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.
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.
Unit 6: Java Beans
1) Write a suitable program illustrating the use of Java Beans. [2069]
2) Create a custom Java Bean named Ellipse which can be used to draw an ellipse.

Unit 7: Servlets and Java Server Pages


1) Write a simple JSP program to display “Kathmandu, Nepal” 10 times. [2069]
2) Write a simple JSP program to display “Lalitpur, Nepal” 10 times. [2070]
3) Write a simple JSP program to display “Tribhuvan University” 10 times. [2071, 2074]
4) Write a program that to illustrate the use of JSP. [2073]
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]
6) Write a simple Servlet program to display “Kathmandu, Nepal” 10 times.
7) Write a Servlet program to process a login form and authenticate the user. You can use hardcoded
values for username and password.
8) Write a Servlet program to show how to create and retrieve the value of a cookie.
9) Write a JSP program to demonstrate login, logout and secure admin page.
10) Write a JSP program to show how to use custom error page.

Unit 8: RMI and CORBA


1) Use RMI to develop programs that runs in different machines. [2070]
2) Write distributed programs with client and server using RMI to find the area of a
a) Circle
b) Rectangle, and
c) Sphere

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)

Lab Assignment 1.2: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: 25th May, 2020

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};

public static void main(String[] arr)


{
System.out.println(isBalanced(array));
}
public static int isBalanced(int[] a)
{
int count = 1;
for(int i = 0; i<array.length; i+=2)
{
if(a[i]%2 != 0)
{
count = 0;
break;
}
}
for(int j = 1;j< array.length; j+=2 )
{
if(a[j]%2 == 0)
{
count = 0;
break;
}
}
return count;
}
}

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);

System.out.println("The area of Rectangle with


length "+ r.l + " & breadth " +
r.b +" is: " +
r.areaOfRectangle());

System.out.println("The perimeter of Rectangle with


length " +r.l + " & breadth " +
r.b +" is: "
r.perimeterOfRectangle())
}
public double areaOfRectangle()
{
return l*b;
}

public double perimeterOfRectangle()


{
return 2*(l+b);
}
}

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;

public class AddTwoNumbers


{
public static void main(String[] args)
{
System.out.println("Enter two numbers to get sum:");
Scanner in = new Scanner(System.in);
double num1= in.nextDouble();
double num2= in.nextDouble();

System.out.println("The sum of "+ num1 +" and "+ num2


+ " is: "+
sumOfTwoNumbers(num1,num2));
}

public static double sumOfTwoNumbers(double num1,double


num2)
{
return num1+num2;
}

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;

public class SimpleInterest


{
public static void main(String[] args)
{
System.out.println("Enter Principle, Time &
Rate:");
Scanner in = new Scanner(System.in);
double p = in.nextDouble();
double t = in.nextDouble();
double r = in.nextDouble();

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

5) Write both procedural and object-oriented programs to calculate the area of a


a) Circle
b) Square
c) Rectangle
d) Sphere

 Procedural:

a) Circle
Program:

package Q5_a_AreaOfCircleProcedural;

import java.util.Scanner;

public class Circle


{
public static void main(String[] args)
{
System.out.println("Enter the radius of a
circle:");
Scanner in = new Scanner(System.in);
double radius = in.nextDouble();
System.out.println("The area of a Circle with "+
radius + " is: "+
areaOfCircle(radius));
}

public static double areaOfCircle(double r)


{
return Math.PI*r*r;
}
}

Output:

5|Page
PREPARED BY: Dipendra Shrestha

b) Square
Program:

package Q5_b_AreaOfSquareProcedural;

import java.util.Scanner;

public class Square


{
public static void main(String[] args)
{
System.out.println("Enter the length of Square:
");
Scanner in = new Scanner(System.in);
double length = in.nextDouble();
System.out.println("The area of Square with " +
length + " is: "+
areaOfSquare(length));
}
public static double areaOfSquare(double l)
{
return l*l;
}
}

Output:

6|Page
PREPARED BY: Dipendra Shrestha

c) Rectangle:
Program

package Q5_c_AreaOfRectangleProcedural;

import java.util.Scanner;

public class Rectangle


{
public static void main(String[] args)
{
System.out.println("Enter the length and breadth
of rectangle: ");
Scanner in = new Scanner(System.in);
double length = in. nextDouble();
double breadth = in.nextDouble();
System.out.println("The area Rectangle with
length " +length + " and
breadth " +breadth+ " is: "+
areaOfRectangle(length,breadth));
}

public static double areaOfRectangle(double l,


double b)
{
return l*b;
}
}

Output:

7|Page
PREPARED BY: Dipendra Shrestha

d) Sphere:
Program

package Q5_d_AreaOfSphereProcedural;

import java.util.Scanner;

public class Sphere


{
public static void main(String[] args)
{
System.out.println("Enter the radius of
Sphere: ");
Scanner in = new Scanner(System.in);
double radius = in.nextDouble();
System.out.println("The area of Sphere with
radius " + radius + " is:
"+ areaOfSphere(radius));
}
public static double areaOfSphere(double r)
{
return 4*Math.PI*r*r;
}
}

Output:

8|Page
PREPARED BY: Dipendra Shrestha

 Object-oriented:

a) Circle
Program:

package Q5_a_AreaOfCircleObjectOriented;

public class Circle


{
private double r;
public Circle(double r)
{
this.r=r;
}
public static void main(String[] args)
{
Circle c = new Circle(5);
System.out.println("The area of Circle with
radius "+ c.r + " is:" +
c.areaOfSquare());
}
public double areaOfSquare()
{
return Math.PI*r*r;
}
}

Output:

9|Page
PREPARED BY: Dipendra Shrestha

b) Square
Program:

package Q5_b_AreaOfSquareObjectOriented;

public class Square


{
private double l;
public Square(double l)
{
this.l = l;
}

public static void main(String[] args)


{
Square s = new Square(5);
System.out.println("The area of Square with
length "+ s.l + " is: "+
s.areaOfSquare());
}

public double areaOfSquare()


{
return l*l;
}
}

Output:

10 | P a g e
PREPARED BY: Dipendra Shrestha

c) Rectangle
Program:

package Q5_c_AreaOfRectangleObjectOriented;

public class Rectangle


{
private double l,b;
public Rectangle(double l,double b)
{
this.l=l;
this.b =b;
}

public static void main(String[] args)


{
Rectangle r = new Rectangle(5,10);
System.out.println("The area of Rectangle with
length " +r.l + " & breadth
" + r.b +" is: " +
r.areaOfRectangle());
}

public double areaOfRectangle()


{
return l*b;
}
}

Output:

11 | P a g e
PREPARED BY: Dipendra Shrestha

d) Sphere
Program:

package Q5_d_AreaOfSphereObjectOriented;

public class Sphere


{
private double r;
public Sphere(double r)
{
this.r = r;
}
public static void main(String[] args)
{
Sphere s = new Sphere(5);
System.out.println("The area of Sphere with
radius " + s.r + " is: "+
s.areaOfSphere());
}
public double areaOfSphere()
{
return 4*Math.PI*r*r;
}
}

Output:

12 | P a g e
PREPARED BY: Dipendra Shrestha

6) Write a static method to calculate the sum of a one-dimensional array.


Program:

package Q6_SumOf1DArray;

public class SumOfArray


{
public static void main(String[] args)
{
int []a = {1,2,3,4,5};
System.out.println("The sum of numbers in array
is: "+ sum(a));
}
public static int sum(int []data)
{
int sum =0;
for(int i = 0; i<data.length; i++)
{
sum +=data[i];
}
return sum;
}
}

Output:

13 | P a g e
PREPARED BY: Dipendra Shrestha

7) Write a static method to calculate the average of a one-dimensional array.


Program

package Q7_AverageOf1DArray;

public class AverageOfArray


{
public static void main(String[] args)
{
int []a = {1,2,3,4,5};
System.out.println("The average of numbers in
array is: "+ average(a));
}

public static int average(int []data)


{

int sum =0;


for(int i = 0; i<data.length; i++)
{
sum +=data[i];
}
return sum/data.length;
}
}

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;

public class TwoDArrayDemo


{
public static void main(String[] args)
{
int [][] firstMatrix= new int[3][3];
int [][] secondMatrix = new int[3][3];
int [][] result = new int [3][3];

Scanner in = new Scanner(System.in);


//Taking input for 1st Matrix
System.out.println("Enter values of first 3 by 3
matrix");
for (int i =0 ; i<3; i++)
{
for (int j =0; j<3; j++)
{
firstMatrix[i][j] = in.nextInt();
}
}

//Taking input for second Matrix


System.out.println("Enter Values of second 3 by
3 matrix");
for (int i =0 ; i<3; i++)
{
for (int j =0; j<3; j++)
{
secondMatrix[i][j] = in.nextInt();
}
}

result = calculateSum(firstMatrix,secondMatrix);
System.out.println("The result of Matrix
addition is:");
displayMatrix(result);

result =
calculateDifference(firstMatrix,secondMatrix);

System.out.println("The result of difference


between two matrices is:");
displayMatrix(result);

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++)
{
sum[i][j] = firstMatrix[i][j]+
secondMatrix[i][j];
}
}
return sum;
}
public static int[][] calculateDifference(
int [][]firstMatrix,
int [][]secondMatrix)
{
int [][] difference = new int[3][3];

for(int i = 0 ; i<3; i++)


{
for(int j =0; j<3; j++)
{
difference[i][j] = firstMatrix[i][j]-
secondMatrix[i][j];
}
}
return difference;
}

public static int[][] calculateProduct(


int[][] firstMatrix,
int[][]secondMatrix)
{
int mul[][]=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

9) Write a program to demonstrate encapsulation.



Program

package Q9_Encapsulation;

public class EncapsulationDemo


{
public static void main(String[] args)
{
Student s = new Student();
s.setRollno(16);
s.setName("Dipendra");
System.out.println("Roll no.: " + s. getRollno()
);
System.out.println("Name: "+ s.getName());
}
}
class Student
{
private int rollno;
private String name;
public int getRollno()
{
return rollno;
}
public void setRollno(int rollno)
{
this.rollno = rollno;
}

public String getName()


{
return name;
}
public void setName(String name)
{
this.name = name;
}
}

Output:

18 | P a g e
PREPARED BY: Dipendra Shrestha

10) Write a program to demonstrate inheritance.



Program

package Q10_Inheritance;

public class InheritanceDemo


{
public static void main(String[] args)
{
Polygon pol =new Polygon();
Rectangle rec = new Rectangle();
Triangle tri = new Triangle();

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;

protected void setValues(int a, int b)


{
width = a;
height = b;
}
}
class Rectangle extends Polygon
{
int areaOfRectangel()
{
return (width*height);
}
}

class Triangle extends Polygon


{
double areaOfTriangle()
{
return (width*height)/2;
}
}

output:

19 | P a g e
PREPARED BY: Dipendra Shrestha

11) Write a program to demonstrate polymorphism using non-abstract class as parent.



Program

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;
}
}

public class PolymorphismUsingNonAbstractClass


{
public static void main(String[] args)
{
Shape s =new Square(5);
System.out.println("Area of Square: "+ s.area());
}
}

output:

20 | P a g e
PREPARED BY: Dipendra Shrestha

12) Write a program to demonstrate polymorphism using abstract class as parent.



Program:

package Q12_PolymorphismUsingAbstractClass;

abstract class Shape


{
public abstract double area();
}

class Square extends Shape


{
private double l;
public Square(double l)
{
this.l = l;
}
public double area()
{
return l*l;
}
}

public class PolymorphismUsingAbstractClass


{
public static void main(String[] args)
{
Shape s = new Square(5);
System.out.println("Area of Square:"+ s.area());
}
}

Output:

21 | P a g e
PREPARED BY: Dipendra Shrestha

13) Write a program to demonstrate polymorphism using interface as parent.



Program
package Q13_PolymorphismUsingInterface;

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;

public double getRadius()


{
return radius;
}
public void setRadius(double radius)
{
this.radius = radius;
}
public double areaOfCircle()
{
return Math.PI*radius*radius;
}
}

class Square
{
private double length;

public double getLength()


{
return length;
}

public void setLength(double length)


{
this.length = length;
}
public double areaOfSquare()
{
return length*length;
}
}

public class ShapeDemo


{
public static void main(String[] args)
{
Circle c = new Circle();
Square s = new Square();
c.setRadius(5);
s.setLength(5);

System.out.println("The area of Circle with

23 | P a g e
PREPARED BY: Dipendra Shrestha

radius " + c.getRadius() + "


is: "+ c.areaOfCircle());
System.out.println("The area of Square with
length" + s.getLength() + "
is: "+ s.areaOfSquare());
}
}

output:

24 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)

Lab Assignment 1.3: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: 25th May, 2020

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

Unit- #1.3

1) Write a program to demonstrate try-catch-finally.



Program

package Q1_TryCatchFinally;

import java.util.Scanner;

class InvalidRadiusException extends Exception


{
public InvalidRadiusException(String message)
{
super(message);
}
}
class Circle
{
private double r;
public void setR(double r) throws InvalidRadiusException
{
if(r<0)
{
throw new InvalidRadiusException("Invalid radius
as it can't be negative
value. ");
}
else{
this.r = r;
}
}
}

public class TryCatchFinallyDemo


{
public static void main(String[] args)
{
System.out.println("Enter the radius: ");
Scanner in = new Scanner(System.in);
double radius = in.nextDouble();
Circle c = new Circle();
try{
c.setR(radius);
}
catch (InvalidRadiusException e)
{
System.out.println(e.getMessage());
}
finally{
System.out.println("Finally block executed");
}
}
}

1|Page
PREPARED BY: Dipendra Shrestha

Output:

For try-block

For catch-block

2) Write a program to demonstrate try-finally.



Program

package Q2_TryFinally;

public class TryFinallyDemo


{
public static void main(String[] args)
{
int[] arr = new int[4];
try {
int i = arr[3];
System.out.println("Inside try block");
}
finally {
System.out.println("Finally block executed.");
}
}
}

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;

class First extends Thread


{
@Override public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try {
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());

}
}
}
}

public class ThreadInterval


{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}

3|Page
PREPARED BY: Dipendra Shrestha

output:

4|Page
PREPARED BY: Dipendra Shrestha

4) Write a program to execute multiple threads in priority base. [2075]



Program

package Q4_MultipleThread;

class First extends Thread


{
@Override public void run()
{
for (int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}
}
class Second extends Thread
{
@Override public void run()
{
for (int i = 11; i <= 20; i++)
{
System.out.println(i);
}
}
}

class Third extends Thread


{
@Override public void run()
{
for (int i = 21; i <= 30; i++)
{
System.out.println(i);
}
}
}
public class ThreadPriority
{
public static void main(String[] args) throws
InterruptedException
{
Thread t1 = new First();
Thread t2 = new Second();
Thread t3 = new Third();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}

5|Page
PREPARED BY: Dipendra Shrestha

Output:

6|Page
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)

Lab Assignment 1.4: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: May 25, 2020

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;

public class FileReadWrite


{
public static void main(String[] args) throws
Exception
{
FileInputStream in = null;
FileOutputStream out = null;

in = new FileInputStream
("source_FileReadWrite.txt");

out = new FileOutputStream


("destination_FileReadWrite.txt");
int byteData;
while (true)
{
byteData = in.read();
if (byteData == -1)
{
break;
}
out.write(byteData);
}

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;

public class CharacterStreamDemo


{
public static void main(String[] args) throws
Exception
{

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;

public class SimpleInterest


{
public static void main(String[] args) throws
FileNotFoundException
{
Scanner in = new Scanner(new File
("source_simple_interest.txt"));

PrintWriter out = new PrintWriter(new File


("destination_simple_interest.txt"));

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;

out.printf("%s %.2f %.2f %.2f %.2f %n",name,


principal, rate, time, interest);
}
in.close();
out.close();
}
}

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;

public class BufferReaderDemo


{
public static void main(String[] args) throws
Exception
{
BufferedReader in = null;

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;

public class WriteIntoFile


{
public static void main(String[] args) throws
Exception
{
PrintWriter out = null;
try
{
out = new PrintWriter(new FileWriter
destination_write_into_file.txt"));
Scanner in = new Scanner(System.in);

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)

Lab Assignment 2, 3: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: May 25, 2020

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

Unit 2, 3: User Interface Components with Swing, Event Handling

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 class AddTwoNumbers extends JFrame


{
public static void main(String[] args)
{
AddTwoNumbers frame = new AddTwoNumbers();
frame.setVisible(true);
frame.setBounds(500,100,250,250);

}
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);

JLabel secondTextLabel = new JLabel("Second


Number:");
JTextField secondTextField = new JTextField(20);
add(secondTextLabel);
add(secondTextField);

secondTextField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);

JLabel displayResultLabel = new


JLabel("Result:");
JTextField displayResultField = new
JTextField(20);
add(displayResultLabel);
add(displayResultField);
displayResultField.setEditable(false);

1|Page
PREPARED BY: Dipendra Shrestha

displayResultField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);

JButton calculateSum = new JButton("Calculate Sum");


add(calculateSum);

calculateSum.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double firstNumber = Double.parseDouble
(firstTextField.getText());

double secondNumber = Double.parseDouble


(secondTextField.getText());

double sum = firstNumber + secondNumber;


displayResultField.setText
(String.valueOf(sum));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

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 class MultiplyTwoNumbers extends JFrame


{
public static void main(String[] args)
{
MultiplyTwoNumbers frame = new
MultiplyTwoNumbers();
frame.setVisible(true);
frame.setBounds(500,100,250,250);

}
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);

JLabel displayResultLabel =new JLabel("Result:");


JTextField displayResultField =new JTextField(20;
add(displayResultLabel);
add(displayResultField);
displayResultField.setEditable(false);
displayResultField.setComponentOrientation
(ComponentOrientation.RIGHT_TO_LEFT);
JButton calculateProduct = new JButton("Calculate
Product");
add(calculateProduct);

3|Page
PREPARED BY: Dipendra Shrestha

calculateProduct.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
double firstNumber = Double.parseDouble
(firstTextField.getText());

double secondNumber = Double.parseDouble


(secondTextField.getText());

double sum = firstNumber * secondNumber;


displayResultField.setText
(String.valueOf(sum));
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

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 class SimpleInterest extends JFrame


{
public static void main(String[] args)
{
SimpleInterest frame = new SimpleInterest();
frame.setVisible(true);

public SimpleInterest()
{

//place your code here


setLayout(new FlowLayout());

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);

JButton calculateInterest =new JButton("Calculate


Inrerest");
add(calculateInterest);

5|Page
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:

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;

public class Palindrome extends JFrame


{
public static void main(String[] args)
{
Palindrome frame = new Palindrome();
frame.setVisible(true);
}
public Palindrome()
{
setLayout(new GridLayout(4,1,10,20));

JLabel inputLabel = new JLabel("Input any


String: ");
JTextField inputTextField = new JTextField(20);
add(inputLabel);
add(inputTextField);

JLabel outputLabel = new JLabel("Output: ");


JTextField outputTextField = new JTextField(20);
add(outputLabel);
add(outputTextField);
outputTextField.setEditable(false);

JButton checkPalindromeButton = new


JButton("Check Palindrome");
add(checkPalindromeButton);

JButton reverseButton = new JButton("Reverse");


add(reverseButton);

JButton findVowelButton = new JButton("Find


Vowel");
add(findVowelButton);

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();

for (int i = length-1; i>=0; i-- )


{
copyUserInput = copyUserInput +
userInput.charAt(i);
}
if (copyUserInput.equalsIgnoreCase
(userInput))
{
outputTextField.setText("String is
palindrome.");
}
else {
outputTextField.setText("String
isn't a palindrome.");
}
}
});

reverseButton.addActionListener(new
ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String reverseUserInput="";
String userInput = inputTextField.
getText();
int length = userInput.length();

for (int i = length-1; i>=0; i-- )


{
reverseUserInput = reverseUserInput +
userInput.charAt(i);
}

outputTextField.setText("Reverse String is: "+


reverseUserInput);
}
});

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="";

for (int i =0; i<=length-1; i++ )


{
for (int j = 0; j<=vowel.length-1;
j++)
{
if(userInput.charAt(i)==
vowel[j])
{
extractedVowel[i] =
userInput.charAt(i);

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

Checking for Reverse

Checking for Find Vowel

10 | P a g e
PREPARED BY: Dipendra Shrestha

5) Write a program to illustrate the use of BorderLayout. [2073]



Program

package Q05_BorderLayout;

import javax.swing.*;
import java.awt.*;

public class BorderLayoutDemo extends JFrame


{
public static void main(String[] args)
{
BorderLayoutDemo frame = new BorderLayoutDemo();
frame.setVisible(true);
frame.setTitle("Border Layout");
}

public BorderLayoutDemo()
{
setLayout(new BorderLayout());

JButton topButton = new JButton("PAGE_START/NORTH");


JButton bottomButton = new JButton("PAGE_END/SOUTH");
JButton leftButton = new JButton("LINE_START/WEST");
JButton rightButton = new JButton("LINE_END/EAST");
JButton centerButton = new JButton("CENTER");

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

6) Write a program to calculate simple interest using


a) FlowLayout
b) GridLayout
c) GridBagLayout

a) FlowLayout
Program
package Q06_a_SimpleInterestFlowLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleInterestFlowLayout extends JFrame


{
public static void main(String[] args)
{
SimpleInterestFlowLayout frame = new
SimpleInterestFlowLayout();
frame.setVisible(true);
}
public SimpleInterestFlowLayout()
{
setLayout(new FlowLayout());

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);

JButton calculateInterest = new JButton("Calculate


Inrerest");
add(calculateInterest);

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 class SimpleInterestGridLayout extends JFrame


{
public static void main(String[] args)
{
SimpleInterestGridLayout app = new
SimpleInterestGridLayout();
app.setVisible(true);
}

public SimpleInterestGridLayout()
{

//place your code here


setLayout(new GridLayout(5,1));

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(""));

JButton calculateInterest = new


JButton("Calculate Inrerest");
add(calculateInterest);

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 class SimpleInterestGridBagLayout extends JFrame


{
public static void main(String[] args)
{
SimpleInterestGridBagLayout app = new
SimpleInterestGridBagLayout();
app.setVisible(true);
}

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);

//For Interest Displaying Field


s.gridx =0;
s.gridy =3;
add(new JLabel("Interest"),s);
JTextField interestTextField =new JTextField(15);
interestTextField.setEditable(false);
s.gridx =1;
add(interestTextField,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 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:

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 class LoginFormDemo extends JFrame


{
public static void main(String[] args)
{
LoginFormDemo app =new LoginFormDemo();
app.setVisible(true);
}

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);

JButton LoginButton = new JButton("Login");


add(LoginButton);

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'};

if (username.equals("admin") && Arrays.


equals(actualPassword,password))
{
System.out.println("access granted");
}
else {
System.out.println("access denied");
}

18 | P a g e
PREPARED BY: Dipendra Shrestha

}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
}

Output

Username : admin
Password: admin

Username or password different from ‘admin’

19 | P a g e
PREPARED BY: Dipendra Shrestha

8) (Optional) Create a basic notepad app with the following features:


a) New
b) Open
c) Save
d) Exit
Use JButton components to implement these features

9) Create an application with UI similar to the windows notepad app.


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.*;

public class NotePadApp extends JFrame


{
public static void main(String[] args)
{

NotePadApp frame = new NotePadApp();


frame.setVisible(true);
frame.setBounds(500,100,1000,500);
frame.setTitle("JMenu Introduction");

}
JTextArea textArea;
public NotePadApp()
{
Container c = this.getContentPane();
c.setLayout(null);

textArea = new JTextArea();


textArea.setBounds(0,20,1000,500);
c.add(textArea);
//********************** Creating Menu Bar *****************
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0,0,1000,20);
c.add(menuBar);

//***************** Adding Menus to the Menu Bar************


//Adding 'File' Menu to menuBar.
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);

//Adding 'Edit' Menu to Menu Bar.

20 | P a g e
PREPARED BY: Dipendra Shrestha

JMenu editMenu = new JMenu("Edit");


menuBar.add(editMenu);

//Adding 'Format' Menu to Menu Bar.


JMenu formatMenu = new JMenu("Format");
menuBar.add(formatMenu);

//Adding 'View' Menu to Menu Bar.


JMenu viewMenu = new JMenu("View");
menuBar.add(viewMenu);

//Adding 'View' Menu to Menu Bar.


JMenu helpMenu = new JMenu("Help");
menuBar.add(helpMenu);

//****************** Adding MenuItems to the Menu**********


//Adding MenuItems to the 'File' Menu
JMenuItem newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);

JMenuItem openMenuItem = new JMenuItem("Open...");


fileMenu.add(openMenuItem);

JMenuItem saveMenuItem = new JMenuItem("Save" );


fileMenu.add(saveMenuItem);

JMenuItem saveAsMenuItem = new JMenuItem("Save


AS...");
fileMenu.add(saveAsMenuItem);

fileMenu.addSeparator();

JMenuItem pageSetupMenuItem = new JMenuItem("Page


Setup...");
fileMenu.add(pageSetupMenuItem);

JMenuItem printMenuItem = new JMenuItem("Print...");


fileMenu.add(printMenuItem);

fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);

//Adding MenuItem to the 'Edit' Menu


JMenuItem undoMenuItem = new JMenuItem("Undo");
editMenu.add(undoMenuItem);

editMenu.addSeparator();

JMenuItem cutMenuItem = new JMenuItem("Cut");


editMenu.add(cutMenuItem);

JMenuItem copyMenuItem = new JMenuItem("Copy");


editMenu.add(copyMenuItem);

JMenuItem pasteMenuItem = new JMenuItem("Paste");

21 | P a g e
PREPARED BY: Dipendra Shrestha

editMenu.add(pasteMenuItem);

JMenuItem deleteMenuItem= new JMenuItem("Delete");


editMenu.add(deleteMenuItem);

//Adding MenuItem to the 'Format' Menu


JCheckBox wordWrapMenuItemCheckBox = new
JCheckBox("Word Wrap");
formatMenu.add(wordWrapMenuItemCheckBox);

JMenuItem fontMenuItem = new JMenuItem("Font..");


formatMenu.add(fontMenuItem);

//Adding MenuItem to the 'View' Menu


JMenu zoomMenu = new JMenu("Zoom");

//******* Adding MenuItem to the zoomMenu. *************


JMenuItem zoomInMenuItem = new JMenuItem("Zoom In");
zoomMenu.add(zoomInMenuItem);

JMenuItem zoomOutMenuItem = new JMenuItem("Zoom


Out");
zoomMenu.add(zoomOutMenuItem);

JMenuItem defaultZoomMenuItem = new


JMenuItem("Restore Default Zoom");
zoomMenu.add(defaultZoomMenuItem);

//**********************************************************

//Adding MenuItem to the 'View' Menu of type checkbox.


JCheckBox statusBarCheckBox = new JCheckBox("Status
Bar");
viewMenu.add(statusBarCheckBox);
statusBarCheckBox.setSelected(true);
statusBarCheckBox.setEnabled(false);

//Adding MenuItem to the 'Help' Menu


JMenuItem viewHelpMenuItem = new JMenuItem("View
Help");
helpMenu.add(viewHelpMenuItem);

JMenuItem sendFeedbackMenuItem = new JMenuItem("Send


Feedback");
helpMenu.add(sendFeedbackMenuItem);

helpMenu.addSeparator();

JMenuItem aboutNotepadMenuItem = new JMenuItem


("About Notepad");
helpMenu.add(aboutNotepadMenuItem);

22 | P a g e
PREPARED BY: Dipendra Shrestha

//************ Adding ActionListener for 'File' Menu.*****

// Adding Action Listener for 'New' MenuItem.


newMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("");
}
});

//Add ActionListener For 'Save' MenuItem.


saveMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String text = textArea.getText();
try
{
saveFile(text);
}
catch(Exception execption)
{
System.out.println(execption);
}
}
});

//Adding ActionListener For 'Open' MenuItem.


openMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent
actionEvent)
{
try
{
openFile();
}
catch (Exception exception)
{
System.out.println(exception);
}
}
});

//Adding Action Listner for 'Exit' MenuItem.


exitMenuItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);

23 | P a g e
PREPARED BY: Dipendra Shrestha

}
});

setDefaultCloseOperation(EXIT_ON_CLOSE);

//***************** For 'Save' menuItem functionality*****

private void saveFile(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);
out.print(text);
}
finally
{
out.close();
}
}
else
return;
}

//****************For 'Open' menuItem functionality*********

private void openFile() throws Exception


{
String userDir = System.getProperty("user.home");
JFileChooser fileChooser = new JFileChooser
(userDir+"/Desktop");

fileChooser.setFileFilter(new FileNameExtensionFilter
("Text Files(*.txt)","txt"));

int result = fileChooser.showOpenDialog(this);

if(result == JFileChooser.APPROVE_OPTION)
{
File selectedFile=fileChooser.getSelectedFile();
BufferedReader in = null;

24 | P a g e
PREPARED BY: Dipendra Shrestha

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());
}
}
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.*;

public class TicTacToe extends JFrame


{
public static void main(String[] args)
{
TicTacToe frame = new TicTacToe();
frame.setBounds(500,100,500,500);
frame.setVisible(true);
}
public TicTacToe()
{
JButton[] JButtonArray = new JButton[9];
setLayout(new GridLayout(3,3));

for (int i=0; i<9; i++)


{
JButtonArray[i] = new JButton();
add(JButtonArray[i]);
}
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

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.*;

public class OpenAndSaveDemo extends JFrame


{
public static void main(String[] args)
{
OpenAndSaveDemo frame = new OpenAndSaveDemo();
frame.setBounds(500,100,1000,500);
frame.setVisible(true);
}
JTextArea textArea;
public OpenAndSaveDemo()
{

textArea = new JTextArea();


add(textArea);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

JMenu fileMenu = new JMenu("File");


menuBar.add(fileMenu);

JMenuItem openMenuItem = new JMenuItem("Open");


JMenuItem saveMenuItem = new JMenuItem("save");
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);

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);
}

private void openFile() throws Exception


{
String userDir = System.getProperty("user.home");
JFileChooser fileChooser = new JFileChooser
(userDir+"/Desktop");

fileChooser.setFileFilter(new FileNameExtensionFilter
("Text Files(*.txt)","txt"));

int result = fileChooser.showOpenDialog(this);

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();
}

}
}

private void saveFile(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);
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;

public class DialogDemo extends JFrame


{
public static void main(String[] args)
{
DialogDemo frame = new DialogDemo();
frame.setBounds(500,100,1000,500);
frame.setVisible(true);
}
JDialog dialogBox;
public DialogDemo()
{
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

JMenu helpMenu = new JMenu("Help");


menuBar.add(helpMenu);

JMenuItem aboutDialog = new JMenuItem("About");


helpMenu.add(aboutDialog);

JTextArea textArea = new JTextArea();


textArea.setText("App Name: TestApp"+
"\n"+"Version: 1.0"+ "\n"+
"Copyright © 2000-2020 JetBrains s.r.o");

textArea.setEditable(false);

JButton closeButton = new JButton("Close");

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;

public class StudentsRecord extends JFrame


{
public static void main(String[] args)
{
StudentsRecord frame = new StudentsRecord();
frame.setVisible(true);
frame.setBounds(500,100,500,800);
frame.setTitle("Student Records");

JTextField firstNameField,lastNameField,ageField;
JRadioButton maleRadioButton,femaleRadioButton;
JComboBox facultyComboBox,semesterComboBox;
JTextArea remarksTextArea;
ButtonGroup group;
public StudentsRecord()
{
setLayout(new GridLayout(18,0));

//****************** For MenuBar, Menu and MenuItem **************


JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(Color.green );
setJMenuBar(menuBar);

JMenu fileMenu = new JMenu("File");


menuBar.add(fileMenu);

35 | P a g e
PREPARED BY: Dipendra Shrestha

JMenuItem saveMenuItem = new JMenuItem("Save");


fileMenu.add(saveMenuItem);

JMenuItem resetMenuItem = new JMenuItem("Reset");


fileMenu.add(resetMenuItem);

fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);

//********************** For JToolBar **************************

ImageIcon resetIcon = new ImageIcon("resetIcon.png");


ImageIcon saveIcon = new ImageIcon("saveIcon.png");
ImageIcon exitIcon = new ImageIcon("exitIcon.png");

JToolBar toolBar = new JToolBar();


add(toolBar);

JButton saveButton = new JButton(saveIcon);


toolBar.add(saveButton);
JButton resetButton = new JButton(resetIcon);
toolBar.add(resetButton);
JButton exitButton = new JButton(exitIcon);
toolBar.add(exitButton);

//********** For JTextField,CheckBox and ComboBox ****************

JLabel title = new JLabel("Students Record");


Font font = new Font("TimesRoman",Font.BOLD,20);
title.setFont(font);
title.setHorizontalAlignment(title.CENTER);
add(title);

Font font1 = new Font("TimesRoman",Font.ITALIC,16);


JLabel firstNameLabel = new JLabel("FirstName:");
firstNameLabel.setFont(font1);
firstNameField = new JTextField(10);

JLabel lastNameLabel = new JLabel("LastName:");


lastNameLabel.setFont(font1);
lastNameField = new JTextField(10);

JLabel ageLabel = new JLabel("Age:");


ageLabel.setFont(font1);
ageField = new JTextField(10);

JLabel genderLabel = new JLabel("Gender:");


genderLabel.setFont(font1);
maleRadioButton = new JRadioButton("Male");
femaleRadioButton = new JRadioButton("Female");

JLabel facultyLabel = new JLabel("Faculty:");


facultyLabel.setFont(font1);
String[] facultyList =
{"BSC/CSIT","BBM","BIT","Engineering"};
facultyComboBox = new JComboBox(facultyList);

36 | P a g e
PREPARED BY: Dipendra Shrestha

JLabel semesterLabel = new JLabel("Semester:");


semesterLabel.setFont(font1);
String[] semesterList ={"1st Semester","2nd Semester",
"3rd Semester","4th Semester",
"5th Semester","6th Semester",
"7th Semester","8th Semester"};

semesterComboBox = new JComboBox(semesterList);

JLabel remarksLabel = new JLabel("Remarks:");


remarksLabel.setFont(font1);
remarksTextArea = new JTextArea();

//*** Adding Label, Fields,RadioButtons, ComboBox and TextArea****

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);

//********** ActionListener For JButton on ToolBar ***************

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);
}
});

//*********** Action Listener For JMenuItem on Menu **************

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

//*********** Methods for Reset and Save **********************


private void resetMethods()
{
firstNameField.setText("");
lastNameField.setText("");
ageField.setText("");
group.clearSelection();
facultyComboBox.setSelectedIndex(0);
semesterComboBox.setSelectedIndex(0);
remarksTextArea.setText("");
}
private String[] getFieldValue()
{
maleRadioButton.setActionCommand("Male");
femaleRadioButton.setActionCommand("Female");

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

Either you can save from shortcut icon as well. It works!!

42 | P a g e
PREPARED BY: Dipendra Shrestha

As we can see that record has been successfully saved to desktop.

If we press ‘Reset’ menu item then our form field will be reset.

43 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)

Lab Assignment 4: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: 27th May, 2020

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

Unit 4: Database Connectivity

Here is my database structure.

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********

String url = "jdbc:mariadb://localhost:3306


/JavaJDBC";
String username = "root";
String password= "";
Connection connection=DriverManager.getConnection
(url,username,password);

// ****************** Executing SQL Statement ***********


Statement statement= connection.
createStatement();

String sql = "select * from students where


district='kathmandu'";
ResultSet resultSet = statement.
executeQuery(sql);
while (resultSet.next())
{
System.out.printf("%d, %s, %s, %d \n",
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getString("district"),
resultSet.getInt("age")
);
}
statement.close();
connection.close();
}
}

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;

public class Create {


public static void main(String[] args) throws
SQLException
{
//******** Establishing Connection to the Database

String url = "jdbc:mariadb://localhost:3306


/JavaJDBC";
String username = "root";
String password = "";
Connection connection=DriverManager.getConnection
(url, username, password);

//**Insert into students table according to user input**


Statement statement= connection.
createStatement();

Scanner in = new Scanner(System.in);


System.out.println("Enter Name:");
String name = in.nextLine();
System.out.println("Enter District:");
String district = in.next();
System.out.println("Enter Age:");
int age = in.nextInt();

String sql = String.format("Insert into students


(name,district,age) Values
('"+name+"','"+district+"','"+age+"')");

int rowInserted = statement.executeUpdate(sql);


if(rowInserted>0)
System.out.println("Row InsertedSuccessfully!");
else
System.out.println("Row Insertion Failed!!");
statement.close();
connection.close();
}
}

3|Page
PREPARED BY: Dipendra Shrestha

output:

Read Operation

package Q02_Q03_SQLStatements;

import java.sql.*;
import java.util.Scanner;

public class Read {

public static void main(String[] args) throws


SQLException
{
//*** Establishing Connection to the Database ****

String url = "jdbc:mariadb://localhost:3306/


JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection
(url, username, password);

// ************** Creating SQL Statement******


Statement statement = connection.
createStatement();

4|Page
PREPARED BY: Dipendra Shrestha

// **** If user want to select but he/she don't know


//what values are inside database table *******

System.out.println("Do You want to see database


table before making Selection Query??(Y/N):");

Scanner in = new Scanner(System.in);


char userChoice = in.next().charAt(0);

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 want to select and he/she don't know


//what values are inside database table **************

if(userChoice== 'N')
{
System.out.println("Enter the Id to select
from database:");
int id = in.nextInt();

String sql = "select * from students where


id = '"+id+"'";
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(); //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;

public class Update {

public static void main(String[] args) throws


SQLException
{
//******Establishing Connection to the Database ********

String url "jdbc:mariadb://localhost:3306


/JavaJDBC";
String username = "root";
String password = "";

Connection connection = DriverManager.


getConnection(url, username, password);

// *********** Creating SQL Statement *********


Statement statement = connection.

6|Page
PREPARED BY: Dipendra Shrestha

createStatement();

// ****** If user want to update but he/she don't know


//what values are inside database table ******

System.out.println("Do You want to see database


table before updating??(Y/N):");
Scanner in = new Scanner(System.in);
char userChoice = in.next().charAt(0);

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')
{

System.out.println("Enter the Id to update


into database:");
int id = in.nextInt();

System.out.println("Enter the Name to update


into database:");
String name = in.next();

System.out.println("Enter the District to


update into database:");
String district = in.next();

System.out.println("Enter the Age to update


into database:");
int age = in.nextInt();

String sql = "update students set


name = '" + name + "'
,district= '" + district + "'
, age = '" + age + "
' where id='" + id + "'";

int rowUpdated = statement.executeUpdate(sql);

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.

Record ‘9’ was successfully updated.

8|Page
PREPARED BY: Dipendra Shrestha

Delete Operation

package Q02_Q03_SQLStatements;

import java.sql.*;
import java.util.Scanner;

public class Delete


{

public static void main(String[] args) throws


SQLException
{
//******* Establishing Connection to the Database *****

String url = "jdbc:MySQL://localhost:3306


/JavaJDBC ";
String username = "admin";
String password= "admin";

Connection connection = DriverManager.


getConnection(url,username,password);

// ******Creating SQL Statement ***********************


Statement statement= connection.
createStatement();

// ****** If user want to select but he/she don't know


//what values are inside database table
//***********************************

System.out.println("Do You want to see


database table before making
Selection Query??(Y/N):");

Scanner in = new Scanner(System.in);


char userChoice = in.next().charAt(0);

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 user want to select but he/she don't know what


//values are inside database table *******************

if(userChoice== 'N')
{
System.out.println("Enter the Id to Delete
from database:");
int id = in.nextInt();

String sql = "delete from students where


id= '" + id + "'";
int rowDeleted = statement.
executeUpdate(sql);

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

Record with id ‘9’ was successfully removed.

4) Implement CRUD operations for student table using prepared statements. Ask for user input
where applicable.

Program

Create Operation Using PreparedStatement

package Q04_CrudPreparedStatement;

import java.sql.*;
import java.util.Scanner;

public class CreatePreparedStatement


{
public static void main(String[] args) throws
SQLException
{
String url = "jdbc:mariadb://localhost:3306
/JavaJDBC?";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection(url, username,
password);
Scanner in = new Scanner(System.in);

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();

//****** Sql prepared statement *************


String sql = String.format("Insert into students
(name,district,age)
Values (?,?,?)");

11 | P a g e
PREPARED BY: Dipendra Shrestha

PreparedStatement statement = connection.


prepareStatement(sql);

//****************** Binding Parameter *******


statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
int rowInserted = statement.executeUpdate();

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

Read Operation Using PreparedStatement

package Q04_CrudPreparedStatement;

import java.sql.*;
import java.util.Scanner;

public class ReadPreparedStatement


{
public static void main(String[] args) throws
SQLException
{

String url = "jdbc:mariadb://localhost:3306/


JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection(url, username,
password);

System.out.println("Do You want to see


database table before making
Selection Query??(Y/N):");
Scanner in = new Scanner(System.in);
char userChoice = in.next().charAt(0);

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

//***************** Sql Prepared Statement**************

String sql = "select * from students where


id = ?";
PreparedStatement statement = connection.
prepareStatement(sql);
statement.setInt(1,id);

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();
}
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

Update Operation Using PreparedStatement

package Q04_CrudPreparedStatement;

import java.sql.*;
import java.util.Scanner;

public class UpdatePreparedStatement


{
public static void main(String[] args) throws
SQLException
{

String url = "jdbc:mariadb://localhost:3306


/JavaJDBC";
String username = "root";
String password = "";

Connection connection = DriverManager.


getConnection(url, username, password);

System.out.println("Do You want to see database


table before updating??(Y/N):");
Scanner in = new Scanner(System.in);
char userChoice = in.next().charAt(0);

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();

System.out.println("Enter the Name to update


into database:");
String name = in.next();

15 | P a g e
PREPARED BY: Dipendra Shrestha

System.out.println("Enter the District to


update into database:");
String district = in.next();

System.out.println("Enter the Age to update


into database:");
int age = in.nextInt();

String sql = "update students set name =


?,district= ?, age = ?
where id= ?";
PreparedStatement statement = connection.
prepareStatement(sql);

statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
statement.setInt(4,id);

int rowUpdated = statement.executeUpdate();

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.

Record ‘10’ was successfully updated.

Delete Operation Using PreparedStatement

package Q04_CrudPreparedStatement;

import java.sql.*;
import java.util.Scanner;

public class DeletePreparedStatement


{
public static void main(String[] args) throws
SQLException
{
String url = "jdbc:mariadb://localhost:3306
/JavaJDBC";
String username = "root";
String password = "";
Connection connection = DriverManager.
getConnection(url, username, password);

17 | P a g e
PREPARED BY: Dipendra Shrestha

System.out.println("Do You want to see database


table before making Selection
Query??(Y/N):");
Scanner in = new Scanner(System.in);
char userChoice = in.next().charAt(0);

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();

String sql = "delete from students where id=


?";
PreparedStatement statement = connection.
prepareStatement(sql);

statement.setInt(1, id);

int rowDeleted = statement.executeUpdate();

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.

Record with id ‘10’ was successfully removed.

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

Insert Operation Using Swing

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 static java.sql.Types.NULL;

public class CrudSwingInsert extends JFrame


{
public static void main(String[] args)
{
CrudSwingInsert frame = new CrudSwingInsert();
frame.setVisible(true);
}

String name,district;
int age = NULL;
public CrudSwingInsert()
{
setLayout(new GridLayout(5,1,5,5));

JLabel nameLabel = new JLabel("Name:");


add(nameLabel);
JTextField nameTextField = new JTextField(20);
add(nameTextField);

JLabel districtLabel = new JLabel("District");


add(districtLabel);
JTextField districtTextField = new JTextField(20);
add(districtTextField);

JLabel ageLabel = new JLabel("Age");


add(ageLabel);
JTextField ageTextField = new JTextField(20);
add(ageTextField);

JLabel blankLabel = new JLabel("");


add(blankLabel);
JButton insertButton = new JButton("Insert");
add(insertButton);

insertButton.addActionListener(new ActionListener()

20 | P a g e
PREPARED BY: Dipendra Shrestha

{
@Override

public void actionPerformed(ActionEvent actionEvent)


{
name = nameTextField.getText();
district = districtTextField.getText();

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);
}

public void InsertIntoDatabase()


{

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

Select Operation Using Swing

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;

public class CrudSwingSelect extends JFrame


{
public static void main(String[] args)
{
CrudSwingSelect frame = new CrudSwingSelect();
frame.setVisible(true);
frame.setBounds(500,100,1000,500);
}

int id;
JTextArea textArea;
Container c;
public CrudSwingSelect()
{
c = this.getContentPane();
c.setLayout(null);

//Setting the BackGround Color of the Frame.


Color clr = new Color(255, 247, 205);
c.setBackground(clr);

//Adding 'UserName:' Label


JLabel idLabel = new JLabel("User Id:");
idLabel.setBounds(20,10,90,50);
c.add(idLabel);

//Adding name text field.


JTextField idField = new JTextField();
idField.setBounds(80,25,200,20);
add(idField);

//Adding 'Select' Button.


JButton selectButton = new JButton("Select");
selectButton.setBounds(290,25,100,25);
add(selectButton);

//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

Update Operation Using Swing

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 class CrudSwingUpdate extends JFrame


{
public static void main(String[] args)
{
CrudSwingUpdate frame = new CrudSwingUpdate();
frame.setVisible(true);
frame.setBounds(500,100,550,250);
}

public CrudSwingUpdate()
{
setLayout(new GridLayout(5,1,10,20));

JLabel idLabel = new JLabel("Id:");


add(idLabel);
JTextField idTextField = new JTextField(20);
add(idTextField);

JLabel nameLabel = new JLabel("Name:");


add(nameLabel);
JTextField nameTextField = new JTextField(20);
add(nameTextField);

25 | P a g e
PREPARED BY: Dipendra Shrestha

JLabel districtLabel = new JLabel("District");


add(districtLabel);
JTextField districtTextField = new
JTextField(20);
add(districtTextField);

JLabel ageLabel = new JLabel("Age");


add(ageLabel);
JTextField ageTextField = new JTextField(20);
add(ageTextField);

JLabel blankLabel = new JLabel("");


add(blankLabel);

JButton updateButton = new JButton("Update");


add(updateButton);

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);

String sql = "update students set name =


?,district= ?,age = ?
where id= ?";
PreparedStatement statement = connection.
prepareStatement(sql);

statement.setString(1,name);
statement.setString(2,district);
statement.setInt(3,age);
statement.setInt(4,id);

int rowUpdated = statement.executeUpdate();

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

Delete Operation Using Swing

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 class CrudSwingDelete extends JFrame


{
public static void main(String[] args)
{
CrudSwingDelete frame = new CrudSwingDelete();
frame.setVisible(true);
frame.setBounds(500,100,500,100);
}
public CrudSwingDelete()
{
setLayout(new GridLayout(2,1,10,5));
JLabel idLabel = new JLabel("Id:");
add(idLabel);
JTextField idTextField = new JTextField(20);
add(idTextField);

JLabel Label = new JLabel();


add(Label);

JButton deleteButton = new JButton("Delete");


add(deleteButton);

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
{

String url = "jdbc:mariadb://localhost:3306


/JavaJDBC";
String username = "root";
String password = "";

Connection connection = DriverManager.


getConnection(url, username, password);

String sql = "delete from students where id= ?";


PreparedStatement statement = connection.
prepareStatement(sql);

statement.setInt(1, id);

int rowDeleted = statement.executeUpdate();

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.*;

public class BalanceDeposit


{
static Connection connection;
public static void main(String[] args) throws Exception
{
String url = "jdbc:mariadb://localhost:3306/Bank ";
String username = "root";
String password = "";
connection = DriverManager.getConnection(url,
username, password);

Scanner in = new Scanner(System.in);


System.out.println("**** Deposit *****");

System.out.println("Enter id: ");


int id = in.nextInt();

System.out.println("Enter amount: ");


double amount = in.nextDouble();

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

Database record before deposit transaction is performed

33 | P a g e
PREPARED BY: Dipendra Shrestha

Withdraw Transaction

package Q06_Transaction;

import java.sql.*;
import java.util.Scanner;

public class BalanceWithdraw


{
static Connection connection;
public static void main(String[] args) throws Exception
{
String url = "jdbc:mariadb://localhost:3306/Bank";
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username,
password);

Scanner in = new Scanner(System.in);


System.out.println("**** Withdraw *****");

System.out.println("Enter id: ");


int id = in.nextInt();

System.out.println("Enter amount: ");


double amount = in.nextDouble();

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

Database record before withdraw transaction is performed

After performing withdraw transaction.

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;

public class BalanceTransfer


{
static Connection connection;
public static void main(String[] args) throws Exception
{
String url = "jdbc:mariadb://localhost:3306/Bank";
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username,
password);
Scanner in = new Scanner(System.in);
System.out.println("**** Transfer *****");

System.out.println("Enter id: ");


int id = in.nextInt();

System.out.println("Enter Recipient's id: ");


int recipientId = in.nextInt();

System.out.println("Enter amount: ");


double amount = in.nextDouble();
try
{
String debitSql = "Update MyAccount set balance =
balance - ? where id = ?";

String creditSql = "Update MyAccount set balance =


balance + ? where id = ?";

PreparedStatement statement = connection.


prepareStatement(debitSql);
statement.setDouble(1, amount);
statement.setInt(2, id);

PreparedStatement statement1 = connection.


prepareStatement(creditSql);
statement1.setDouble(1, amount);
statement1.setInt(2, recipientId);

statement.executeUpdate();
statement1.executeUpdate();
connection.commit();
System.out.println("Amount: Rs " + amount +" has been

36 | P a g e
PREPARED BY: Dipendra Shrestha

successfully transferred from


id: " + id+ " to Recipient's id: "+
recipientId);
}

catch (SQLException e)
{
connection.rollback();
System.out.println("Transaction Error!!");
}
}
}

Output:

Database record before transfer transaction is performed

After performing withdraw transaction.

37 | P a g e
PREPARED BY: Dipendra Shrestha

38 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)

Lab Assignment 5: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: 27th May 2020

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

Unit- 5 Network Programming

1) Write two programs that can communicate in a network using TCP Socket? [2070, 7073, 2074]

Program

Client Side

import java.util.Scanner;

public class Client


{
public static void main(String[] args) throws IOException
{
final String HOST = "127.0.0.1";
final int PORT = 1234;

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;

System.out.println("Echoed from server: " +


in.nextLine());
}
}
}
}

Server Side

package EchoServer;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {


public static void main(String[] args) throws
IOException
{
final int PORT = 1234;
System.out.println("Server started.");

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

2) Write a program to illustrate the use of InetAddress class. [2073]



Program

package InetAddress;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressDemo


{
public static void main(String[] args)throws
UnknownHostException
{
InetAddress address = InetAddress.
getByName("www.google.com");
System.out.println(address.getHostAddress());
System.out.println(address.getHostName());
}
}

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;

public class Client


{
public static void main(String[] args) throws
IOException
{
final String HOST = "127.0.0.1";
final int PORT = 1234;

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;

public class Server


{
public static void main(String[] args) throws
IOException
{
final int PORT = 1234;
System.out.println("Server started.");
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)
{
double radius = in.nextDouble();
double area = Math.PI*radius*radius;
System.out.println("Radius received from
client: " + radius);
out.println(area);

String choice = in.next();


if (choice.equalsIgnoreCase("Y")) break;
}
System.out.println("Server has been stopped.");
}
}
}

5|Page
PREPARED BY: Dipendra Shrestha

Output

Client Side

Server Side

6|Page
PREPARED BY: Dipendra Shrestha

4) Write a program to send email using Java [2073, 2074]



Program

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;

public class Client


{
public static void main(String[] args) throws
IOException
{
final String HOST = "127.0.0.1";
final int PORT = 1234;

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;

public class Server


{
public static void main(String[] args) throws
IOException
{
final int PORT = 1234;
System.out.println("Server started.");
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)
{
double length = in.nextDouble();
double breadth = in.nextDouble();
double area = length*breadth;

System.out.println("Length and Breadth


received from client: " +
length +" " + breadth);
out.println(area);

String choice = in.next();


if (choice.equalsIgnoreCase("Y")) break;
}
System.out.println("Server has been stopped.");
}

}
}

10 | P a g e
PREPARED BY: Dipendra Shrestha

Output

Client Side

Server Side

11 | P a g e
PREPARED BY: Dipendra Shrestha

6) Write echo server and echo client program using UDP.



Program

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();

DatagramPacket sendDatagramPacket = new


DatagramPacket(input.getBytes(),
input.length(), address, port);
datagramSocket.send(sendDatagramPacket);

byte[] b1 = new byte[1024];


DatagramPacket receiveDatagramPacket = new
DatagramPacket(input.getBytes()
,input.length());
datagramSocket.receive(receiveDatagramPacket);

String str = new String


(receiveDatagramPacket.getData());
System.out.println("Result Received from Server
is: " + str);
if (input.equalsIgnoreCase("exit")) break;
}
System.out.println("Client Stopped...");
}
catch (IOException e)
{
System.out.println(e);
System.exit(1);
}
}
}

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;

DatagramSocket serverDatagramSocket = null;

try
{
serverDatagramSocket = new DatagramSocket(port);
System.out.println("Created UDP Echo Server on
port"+port);

byte buffer[] = new byte[1024];


DatagramPacket datagramPacket = new DatagramPacket
(buffer, buffer.length);
System.out.println("Server Started ...");
String input;

while(true)
{
serverDatagramSocket.receive(datagramPacket);
input = new String(datagramPacket.getData(),
0,datagramPacket.getLength());

System.out.println("Received from Client: "+


input);
serverDatagramSocket.send(datagramPacket);

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;

public class ClientSide


{
public static void main(String[] args) throws
Exception
{
final String HOST = "localhost";
final int PORT = 1234;

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)
) {
System.out.println("Client Started...");
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 stopped...");

}
catch (Exception e)
{

}
}
}

15 | P a g e
PREPARED BY: Dipendra Shrestha

Server Side

public class Server


{
public static void main(String[] args) throws
Exception
{
final int PORT = 1234;
ServerSocket serverSocket = new
ServerSocket(PORT);
System.out.println("Server Started...");
while(true)
{
Socket clientSocket = serverSocket.accept();
Thread t = new Thread()
{
public void run()
{
try (
PrintWriter out = new
PrintWriter
(clientSocket.getOutputStream(),
true);
Scanner in = new Scanner
(clientSocket.
getInputStream());
)
{
while (true)
{
double radius =
in.nextDouble();
double area =
Math.PI*radius*radius;
System.out.println("Radius
received from client: "
+ radius);
out.println(area);

String choice = in.next();


if(choice.equalsIgnoreCase("Y"))
break;
}
}
catch (IOException e)
{
}
}
};
t.start();
}
}

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;

public class Client


{
public static void main(String[] args) throws Exception
{
final String HOST = "localhost";
final int PORT = 1234;
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)
) {
System.out.println("Client Started...");
while (true)
{
System.out.print("Enter Length: ");
double length = s.nextDouble();
out.println(length);
System.out.print("Enter Breadth: ");
double breadth = s.nextDouble();
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 stopped...");
}
catch (Exception e)
{

}
}
}

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;

public class Server


{
public static void main(String[] args) throws
Exception
{
final int PORT = 1234;
ServerSocket serverSocket = new ServerSocket
(PORT);
System.out.println("Server Started...");
while(true)
{
Socket clientSocket = serverSocket.accept();
Thread t = new Thread()
{
public void run()
{
try (

PrintWriter out = new


PrintWrite(clientSocket.
getOutputStream(),
true);
Scanner in = new Scanner
(clientSocket.
getInputStream());
)
{
while (true)
{
double length =
in.nextDouble();
double breadth =
in.nextDouble();
double area = length*breadth;
System.out.println("Length and
Breadth received from
client: " + length + " " +
breadth);
out.println(area);

String choice = in.next();


if (choice.equalsIgnoreCase("Y"))
break;
}
}
catch (IOException e)

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)

Lab Assignment 6: Advance Java Programming

Submitted By: Submitted to:

Name: Dipendra Shrestha


Program: B. Sc. (CSIT) Aman Maharjan
Roll No: 16
Semester: seventh (7th)
Date: 25th June 2020

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

1. Write a suitable program illustrating the use of Java Beans. [2069]


 Program

package Q01_JavaBean;

import java.awt.Graphics;
import javax.swing.JPanel;

public class Rectangle extends JPanel


{
public Rectangle() { }
private int length = 0;
private int breadth = 0;
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
repaint();

}
public int getBreadth()
{
return breadth;
}
public void setBreadth(int breadth)
{
this.breadth = breadth;
repaint();
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);

if (length <= 0 || breadth<=0) return;


int x = 50, y = 50;
int l = length, b = breadth;

g.drawRect(x, y, l, y);
}
}

1|Page
PREPARED BY: Dipendra Shrestha

For Rectangle icon


package Q01_JavaBean;

import java.awt.Image;
import java.beans.BeanInfo;
import java.beans.SimpleBeanInfo;

public class RectangleBeanInfo extends SimpleBeanInfo


{
private final Image iconColor16;
private final Image iconColor32;
private final Image iconMono16;
private final Image iconMono32;

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;
}
}
}

Icon images are kept inside images folder as:

2|Page
PREPARED BY: Dipendra Shrestha

Adding custom bean i.e. Rectangle to palette Manager

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;

public class Ellipse extends JPanel


{
public Ellipse() { }

private int majorAxis = 0;


private int minorAxis = 0;

public int getMinorAxis()


{
return minorAxis;
}

public void setMinorAxis(int minorAxis)


{
this.minorAxis = minorAxis;
repaint();
}

public int getMajorAxis()


{
return majorAxis;
}

public void setMajorAxis(int majorAxis)


{
this.majorAxis = majorAxis;
repaint();
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (minorAxis <= 0 || majorAxis<=0) return;

int cx = getWidth() / 2, cy = getHeight() / 2;


int x = cx - majorAxis, y = cy - minorAxis;
int w = 2 * majorAxis, h = 2*minorAxis;
g.drawOval(x, y, w, h);
}
}

6|Page
PREPARED BY: Dipendra Shrestha

For Ellipse icon

package Q02_EllipseBean;

import java.awt.Image;
import java.beans.BeanInfo;
import java.beans.SimpleBeanInfo;

public class EllipseBeanInfo extends SimpleBeanInfo


{
private final Image iconColor16;
private final Image iconColor32;
private final Image iconMono16;
private final Image iconMono32;

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;
}
}
}

Icon images are kept inside images folder as:

7|Page
PREPARED BY: Dipendra Shrestha

Adding custom bean i.e. Ellipse to palette Manager

8|Page
PREPARED BY: Dipendra Shrestha

Custom Ellipse bean is successfully added to the palette manager

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)

Lab Assignment 7: Advance Java Programming

Submitted By: Submitted to:

Name:
Program: B. Sc. (CSIT)
Roll No:
Semester: seventh (7th)
Date:

KATHMANDU, NEPAL
2020
Unit 7: Servlets and Java Server Pages

1. Write a simple JSP program to display “Kathmandu, Nepal” 10 times. [2069]



Program

<%--
Document : Display10Times
Created on : Jun 26, 2020, 9:13:20 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>Display Address 10 Times</title>
</head>
<body>
<%
for(int i = 1; i<=10; i++)
{
out.println("Kathmandu,Nepal<br>");
}
%>
</body>
</html>

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
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Display Address 10 Times</title>
</head>
<body>
<%
for(int i = 1; i<=10; i++)
{
out.println("Lalitpur,Nepal<br>");
}
%>
</body>
</html>

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
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Display Address 10 Times</title>
</head>
<body>
<%
for(int i = 1; i<=10; i++)
{
out.println("Tribhuvan University<br>");
}
%>
</body>
</html>

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
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-
8">
<title>Illustrate the use of JSP</title>
</head>
<body>
<%
for(int i =1; i<=5; i++)
out.println("Illustration for the use of JSP.<br>");
%>
</body>
</html>

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
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Student Form.</title>
</head>
<body>
<h1>Fill up the form!</h1>
<form action="PrintDetail.jsp" method="POST">

Name: <input type="text" name="name"><br><br>


Roll No.: <input type="text" name="roll"><br><br>
Address: <input type="text" name="address"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

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">

Username: <input type="text" name="username"/>


</br>
</br>
Password:<input type="password" name="password"/>
</br>
</br>
<input type="submit" value="Submit"/>

</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
{

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 LoginDemo</title>");

8|Page
out.println("</head>");
out.println("<body>");

//getting form input values


String getUsername = request.getParameter("username");
String getPassword = request.getParameter("password");

//checking username and password.


if(getUsername.equals("admin") &&
getPassword.equals("admin"))
{
out.println("<h1 style=color:green;>User is
authenticated.<br> Welcome to the
admin page!</h1>");
}
else
{
out.println("<h1 style=color:red;>User is
invalid!!<br> Username or Password
error.</h1>");
}
out.println("</body>");
out.println("</html>");
}
}
}

Output:

If username = admin & password = admin then user is authenticated.

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>");

//getting the form input from user


String name = request.getParameter("username");

//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

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
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
--%>

<% session.invalidate(); %>


<% response.sendRedirect("LoginForm.jsp"); %>

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.

Username and Password with ‘admin’ is the authenticated one.

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

<%@page errorPage="error.jsp" %>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error Demo</title>
</head>
<body>
<h1>Division</h1>
<%
if(true)
throw new RuntimeException("Hello error page!");
%>
</body>
</html>

error.jsp

<%@page isErrorPage="true" %>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p><%= exception.getMessage() %></p>
</body>
</html>

15 | P a g e
Output:

16 | P a g e
TRINITY INTERNATIONAL COLLEGE
(Tribhuvan University Affiliated)

Lab Assignment 8: Advance Java Programming

Submitted By: Submitted to:

Name:
Program: B. Sc. (CSIT)
Roll No:
Semester: seventh (7th)
Date:

KATHMANDU, NEPAL
2020
PREPARED BY: Dipendra Shrestha

1. Use RMI to develop programs that runs in different machines. [2070]



Program
compute.java (common for both client and server)

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote


{
public double add(double a, double b)throws RemoteException;

RmiClient.java

package Q1_rmiclient;

import compute.*;
import java.rmi.Naming;

public class RmiClient


{

public static void main(String[] args)


{
try{
String url = "rmi://127.0.0.1:8888/Compute";
Compute compute = (Compute)Naming.lookup(url);
double result = compute.add(5,6);
System.out.println("Sum = "+ result);
}
catch(Exception e)
{
System.err.println("Remote exception:");
}
}
}

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;

public class RmiServer implements Compute


{

public RmiServer() {super();}

1|Page
PREPARED BY: Dipendra Shrestha

public double add (double a , double b)throws RemoteException


{
return a+b;
}

public static void main(String[] args)


{
try
{
Compute server = new RmiServer();
final int PORT = 8888;
Registry registry = LocateRegistry.createRegistry
(PORT);
UnicastRemoteObject.exportObject(server,PORT);
registry.rebind("Compute", server);

}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

Compute.java (Common for both client and server)

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote


{
public double calcArea(double r)throws RemoteException;

RmiClientCircle.java

package q2_a_rmiclientcircle;
import compute.*;
import java.rmi.Naming;

public class RmiClientCircle


{
public static void main(String[] args)
{
try
{
String url = "rmi://127.0.0.1:8888/Compute";
Compute compute = (Compute)Naming.lookup(url);
double result = compute.calcArea(1);
System.out.println("Area of Circle = "+ result);
}
catch(Exception e)
{
System.err.println("Remote exception:");
}
}
}

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;

public class RmiServerCircle implements Compute


{

public RmiServerCircle() {super();}


public double calcArea (double r) throws RemoteException
{
return Math.PI*r*r;
}

public static void main(String[] args)


{
try
{
Compute server = (Compute) new RmiServerCircle();
final int PORT = 8888;
Registry registry = LocateRegistry.createRegistry
(PORT);
UnicastRemoteObject.exportObject(server,PORT);
registry.rebind("Compute", server);

}catch(Exception e)
{
System.err.println("RmiServer Exception.");
}
}
}

Output:

4|Page
PREPARED BY: Dipendra Shrestha

b) Rectangle

Program

Compute.java (common for both client and server)

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote


{
public double calcArea(double l ,double b) throws
RemoteException;
}

RmiClientRectangle.java

package q2_b_rmiclientrectangle;

import compute.Compute;
import java.rmi.Naming;

public class RmiClientRectangle


{
public static void main(String[] args)
{

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;

public class RmiServerRectangle implements Compute


{

public RmiServerRectangle() {super();}

5|Page
PREPARED BY: Dipendra Shrestha

public double calcArea (double l ,double b) throws


RemoteException
{
return l*b;
}

public static void main(String[] args)


{
try
{
Compute server = new RmiServerRectangle();
final int PORT = 8888;
Registry registry = LocateRegistry.createRegistry
(PORT);
UnicastRemoteObject.exportObject(server,PORT);
registry.rebind("Compute", server);

}
catch(Exception e)
{
System.err.println("RmiServer Exception.");

}
}

Output:

6|Page
PREPARED BY: Dipendra Shrestha

c) Sphere

Program

Compute.java (common for both client and server)

package compute;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Compute extends Remote


{
public double calcArea(double r) throws RemoteException;

RmiClientSphere.java

package q2_c_rmiclientsphere;

import compute.Compute;
import java.rmi.Naming;

public class RmiClientSphere


{
public static void main(String[] args)
{
try{
String url = "rmi://127.0.0.1:8888/Compute";
Compute compute = (Compute)Naming.lookup(url);
double result = compute.calcArea(1);
System.out.println("Area of Sphere= "+ result);
}
catch(Exception e)
{
System.err.println("Remote exception:");
}

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;

public class RmiServerSphere implements Compute


{

7|Page
PREPARED BY: Dipendra Shrestha

public RmiServerSphere() {super();}


public double calcArea (double r) throws RemoteException
{
return 4*Math.PI*Math.pow(r, 2);
}

public static void main(String[] args)


{
try
{
Compute server = new RmiServerSphere();
final int PORT = 8888;
Registry registry = LocateRegistry.createRegistry
(PORT);
UnicastRemoteObject.exportObject(server,PORT);
registry.rebind("Compute", server);

}
catch(Exception e)
{
System.err.println("RmiServer Exception.");

}
}
}

Output:

8|Page

You might also like