[Go to site: main page, start]

0% found this document useful (0 votes)
3 views43 pages

Java Lab

This document is a lab report for an Advanced Java course, detailing various programming exercises and their source code. The labs cover topics such as jagged and 2D arrays, multiple inheritance, functions for array manipulation, GUI programming, multithreading, and file handling. Each lab includes a specific task along with the corresponding Java code to demonstrate the concepts learned in the course.

Uploaded by

surajnpl696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

Java Lab

This document is a lab report for an Advanced Java course, detailing various programming exercises and their source code. The labs cover topics such as jagged and 2D arrays, multiple inheritance, functions for array manipulation, GUI programming, multithreading, and file handling. Each lab includes a specific task along with the corresponding Java code to demonstrate the concepts learned in the course.

Uploaded by

surajnpl696
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LAB REPORT OF ADVANCED JAVA

Submitted by: Submitted to:


Name: Rashik Shrestha Name: Sunil Chaudhary
Roll no: 20816
Section: ’B’
Faculty: BSc CSIT
Lab Lab Titles
No.
01 Write a java program initialize and demonstrate jagged array elements with sum of
each row.
02 Write a java program to to initialize and display 2D array elements with sum of each
row.
03 Write a java program to implement the concepts of multiple inheritances in Java to
calculate the area of a shape and the cost to paint it.
04 Write a java program to implement the concepts of multiple inheritances in Java
using interfaces to calculate the area of a shape and the cost to paint it.
05 Write a java program to implement the concepts of multiple inheritances in Java
using abstracts to calculate the area of a shape and the cost to paint it.
06 Write a function that takes an array of integers as an argument and returns a value
based on the sums of the even and odd numbers in the array.
07 Write a function that accepts an array of non-negative integers and returns the
second largest integer in the array [Return -1 if there is no second largest].
08 You have given string:
String[] str = new String[]{"a", "b", "c", "a", "a", "d", "c", "f"};
i. Find Repeated Words
ii. Display Non-Repeated Words
iii. Remove All Repeated Word
09 Count occurrences of each word in a given array:
strings= {"apple", "banana", "apple", "orange", "banana", "apple", "strawberry"}
10 Find the longest word in an array:
strings= {"sun", "moon", "stars", "galaxy"}
11 Find the shortest word in an array:
strings= {"apple", "banana", "cat", "orange"}
12 Write a simple java program to demonstrate how thread priority is handled.
13 Write a java program to demonstrate Multithreading using synchronized method.
14 Write a java program to demonstrate inter-thread communication or Co-operation
threading.
15 Write a java program to read from file [Link] and write its contents to [Link].
16 Write a java program to read from file [Link] and write its contents to [Link].
17 Write a java program to demonstrate object serialization and deserialization.
18 Write a java program to read, read write using Random Access File.
19 Write a java program to create a GUI form.
20 Write a java program to use GridLayout.
21 Write a java program to use GridBagLayout.
22 Write a program using swing components to add two digits. Use text fields for
inputs and output. The program should display the result when the user presses a
button.
23 Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user presses mouse and difference if user release mouse.
24 Write a java GUI program to calculate square of entered number.
25 Write a java program to add two digits using RMI.
26 Write a java program to insert five student records and display them all.
27 Write a simple client and server socket program to read data from client and print in
server.
28 Write a java program to split different component of URL from given url:
([Link]
on2)
29 Write a java program to display source code of a webpage by URLConnection class.
Write a program to demonstrate lifecycle of servlet.
30

31 Write a program to store and retrieve session in servlet.

Write a program to store, retrieve and delete cookies.


32
Write a program to a JSP web form to take input of a student and submit it to
33
second JSP file which may simply print the values of form submission.
LAB 01:
Write a java program to initialize and demonstrate jagged array elements with sum of each
row.

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
int[][] matrix = new int[][]{{1,2}, {3,4,5}, {1,2,3,4,5}};

for (int i = 0; i < [Link]; i++) //row


{
int sum = 0;
for (int j = 0; j < matrix[i].length; j++) //column
{
[Link](matrix[i][j] + " ");
sum += matrix[i][j];
}
[Link]("Sum of row " + (i + 1) + ": " + sum);
}
}
}

LAB 02:
Write a java program to initialize and display 2D array elements with sum of each row.

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {

int[][] matrix = new int[][]{{1, 2}, {3,4,5}, {1,2,3,4,5}};

for (int i = 0; i < [Link]; i++) // row


{
int sum = 0; // Variable to store sum of elements in each row
for (int j = 0; j < matrix[i].length; j++) // column
{
[Link](matrix[i][j] + " ");
sum += matrix[i][j]; // Add the current element to the sum
}
[Link]("Sum of row " + (i + 1) + ": " + sum);
}
}
}

Lab 03:
Write a java program to implement the concepts of multiple inheritances in Java to calculate
the area of a shape and the cost to paint it.
SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
Rectangle rect= new Rectangle(23, 7);
[Link]([Link]());
[Link]([Link]([Link]()));
}
}
class Shape{
protected int length,breadth;
Shape(int l, int b){
[Link]=l;
[Link]=b;
}
}
interface PaintCost{
int getCost(int area);
}
class Rectangle extends Shape implements PaintCost {
Rectangle(int l,int b){
super(l, b);
}
public int getArea(){
return length*breadth;
}
@Override
public int getCost(int area){
return (2*(length*breadth));
}
}
Lab 04
Write a java program to implement the concepts of multiple inheritances in Java using
interfaces to calculate the area of a shape and the cost to paint it.

SOURCE CODE:
public class Multiple_Interface {
public static void main(String[] args) {
Rectangles rect= new Rectangles(5, 7);
[Link]([Link]());
[Link]([Link]([Link]()));
}
}
interface CalArea
{
int getArea();
}
interface PaintCost
{
int getCost(int area);
}
class Rectangles implements CalArea, PaintCost
{
int length,breadth;
Rectangles(int l,int b)
{
[Link]=l;
[Link]=b;
}
@Override
public int getArea()
{
return length*breadth;
}
@Override
public int getCost(int area)
{
return (3*(area));
}
}
Lab 05
Write a java program to implement the concepts of multiple inheritances in Java using
abstracts to calculate the area of a shape and the cost to paint it.

SOURCE CODE:
public class Abstract {
public static void main(String[] args) {
Rectangle rect = new Rectangle(7, 30);
[Link]("Area: " + [Link]());
[Link]("Cost: " + [Link]());
}
}

abstract class Shape {


protected int length, breadth;

Shape(int l, int b) {
[Link] = l;
[Link] = b;
}

abstract int getArea();


}

interface PaintCost {
int getCost();
}

class Rectangle extends Shape implements PaintCost {


Rectangle(int l, int b) {
super(l, b);
}
@Override
public int getCost() {
int area = getArea();
return area * 70;
}
}
Lab 06
Write a function that takes an array of integers as an argument and returns a value based on
the sums of the even and odd numbers in the array.
SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
[Link](a2(new int[] {1, 2, 3, 4}));
[Link](a2(new int[] {4, 1, 2, 3}));
[Link](a2(new int[] {3, 3, 4, 4}));
[Link](a2(new int[] {1, 1}));
[Link](a2(new int[] {1}));
[Link](a2(new int[] {}));
}
static int a2(int[] a)
{
int sumEven = 0;
int sumOdd = 0;

for (int i=0; i<[Link]; i++)


{
if (a[i]%2 == 0)
sumEven += a[i];
else
sumOdd += a[i];
}

return sumOdd - sumEven;


}
}

Lab 07
Write a function that accepts an array of non-negative integers and returns the second largest
integer in the array [Return -1 if there is no second largest].

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
[Link](a1(new int[]{1, 2, 3, 4}));
[Link](a1(new int[]{4, 1, 2, 3}));
[Link](a1(new int[]{1, 1, 2, 2}));
[Link](a1(new int[]{1, 1}));
[Link](a1(new int[]{1}));
[Link](a1(new int[]{}));
}
static int a1(int[] a)
{
int max1 = -1,max2 = -1;
for (int i=0; i<[Link]; i++){
if (a[i] > max1){
max2 = max1;
max1 = a[i];
}
else if (a[i] != max1 && a[i] > max2)
max2 = a[i];
}
return max2;
}
}

Lab 08
You have given string:
String[] str = new String[]{"a", "b", "c", "a", "a", "d", "c", "f"};
i. Find Repeated Words
ii. Display Non-Repeated Words
iii. Remove All Repeated Words

SOURCE CODE:
import [Link];
public class App {
public static void main(String[] args) throws Exception {
String[] str = new String[]{"a", "b", "c", "a", "a", "d", "c", "f"};
// Repeated Words
[Link]("Repeated Words:");
for (int i = 0; i < [Link]; i++) {
boolean alreadyPrinted = false;
for (int k = 0; k < i; k++) {
if (str[i].equals(str[k])) {
alreadyPrinted = true;
break;
}
}
if (alreadyPrinted) {
continue;
}
for (int j = i + 1; j < [Link]; j++) {
if (str[i].equals(str[j])) {
[Link](str[i]);
break;
}
}
}

// Display Non-Repeated Words


[Link]("\nNon-Repeated Words:");
for (int i = 0; i < [Link]; i++) {

// Remove All Repeated Words


ArrayList<String> nonRepeatedList = new ArrayList<>();
for (int i = 0; i < [Link]; i++) {
boolean isRepeated = false;
for (int j = 0; j < [Link]; j++) {
if (i != j && str[i].equals(str[j])) {
isRepeated = true;
break;
}
}
if (!isRepeated) {
[Link](str[i]);
}
}
// Convert ArrayList back to array
String[] nonRepeatedArray = new String[[Link]()];
nonRepeatedArray = [Link](nonRepeatedArray);
// Print the array after removing repeated words
[Link]("Array after removing repeated words:");
for (String s : nonRepeatedArray) {
[Link](s + " ");
}
}
}
Lab 09
Count occurrences of each word in a given array:
strings= {"apple", "banana", "apple", "orange", "banana", "apple", "strawberry"}

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
String[] strings = {"apple", "banana", "apple", "orange", "banana",
"apple","strawberry"};
boolean[] counted = new boolean[[Link]];
[Link]("Word Occurrences:");
for (int i = 0; i < [Link]; i++) {
if (counted[i]) continue; // Skip if already counted
int count = 1;
for (int j = i + 1; j < [Link]; j++) {
if (strings[i].equals(strings[j])) {
count++;
counted[j] = true;
}
}
[Link](strings[i] + ": " + count);
}
}
}

Lab 10
Find the longest word in an array:
strings= {"sun", "moon", "stars", "galaxy"}

SOURCE CODE:
public class App{
public static void main(String[] args) throws Exception{
String[] strings = {"sun", "moon", "stars", "galaxy"};

// Find the longest word using array indices


int longestIndex = 0;
for (int i = 1; i < [Link]; i++) {
if (strings[i].length() > strings[longestIndex].length()) {
longestIndex = i;
}
}
[Link]("The longest word is: " + strings[longestIndex]);
}
}

Lab 11
Find the shortest word in an array:
strings= {"apple", "banana", "cat", "orange"}

SOURCE CODE:
public class App{
public static void main(String[] args) throws Exception{
String[] strings= {"apple", "banana", "cat", "orange"};
// Find the longest word using array indices
int shortestIndex = 0;
for (int i = 1; i < [Link]; i++) {
if (strings[i].length() < strings[shortestIndex].length()) {
shortestIndex = i;
}
}
[Link]("The shortest word is: " + strings[shortestIndex]);
}
}

Lab 12
Write a simple java program to demonstrate how thread priority is handled.

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
TestMultiPriority1 m1= new TestMultiPriority1();
TestMultiPriority1 m2= new TestMultiPriority1();
TestMultiPriority1 m3= new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
class TestMultiPriority1 extends Thread{
public void run()
{
[Link]([Link]().getPriority());
}
}

Lab 13
Write a java program to demonstrate Multithreading using synchronized method.

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
Table obj=new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
class Table{
synchronized void printTable (int n)
{
for(int i=1;i<5;i++)
{
[Link](n*i);
try{
[Link](400);
}catch(Exception e)
{
[Link](e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1 (Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2 (Table t)
{
this.t=t;
}
public void run()
{
[Link](100);
}
}

Lab 14
Write a java program to demonstrate inter-thread communication or Co-operation threading.

SOURCE CODE:
public class App {
public static void main(String[] args) throws Exception {
Customer c=new Customer();
Thread t1= new Thread()
{
public void run()
{
[Link](15000);
}
};
[Link]();
Thread t2=new Thread(){
public void run()
{
[Link](5000);
}
};
[Link]();
}
}
class Customer{
int amount = 10000;
synchronized void withdraw(int amount)
{
[Link]("Going to withdraw...");
if([Link]<amount)
{
[Link]("Less balance. Waiting for deposit...");
try{
wait();
}
catch (Exception e)
{}
}
[Link]-=amount;
[Link]("Withdraw completed...");
}
synchronized void deposit(int amount)
{
[Link]("Going to deposit...");
[Link]+=amount;
[Link]("Deposit completed...");
notify();
}
}
Lab 15
Write a java program to read from file [Link] and write its contents to [Link].

SOURCE CODE:
import [Link];
import [Link];

public class App {


public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]();
[Link]();
}
}
OUTPUT:
[Link]:

[Link]:

Lab 16
Write a java program to read from file [Link] and write its contents to [Link].
SOURCE CODE:
import [Link].*;
public class App {
public static void main(String[] args) throws Exception {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
} finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
OUTPUT:

Lab 17
Write a java program to demonstrate object serialization and deserialization.

SOURCE CODE:
import [Link].*;
public class App {
public static void main(String[] args) throws Exception {
Student st = new Student();
[Link]=5;
[Link]="Raseek";
[Link]="Bhaktapur";
try{
FileOutputStream out = new FileOutputStream("[Link]");
ObjectOutputStream oboutput= new ObjectOutputStream(out);
[Link](st);
[Link]();
[Link]();
[Link]("Object is serialized");
FileInputStream in = new FileInputStream("[Link]");
ObjectInputStream obinput= new ObjectInputStream(in);
st=(Student)[Link]();
[Link]();
[Link]();
}catch(IOException e){
[Link]();
}
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
class Student implements Serializable{
public String name,address;
public int id;
}

Lab 18
Write a java program to read, read write using Random Access File.

SOURCE CODE:
import [Link].*;
public class App {
public static void main(String[] args) throws Exception {
String FILEPATH = "[Link]";
try {
[Link](new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "Stay [Link] days are on their way.", 8);
[Link](new String(readFromFile(FILEPATH, 0, 100)));
} catch (IOException e) {
[Link]();
}
}

private static byte[] readFromFile(String filepath, int position, int size) throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "r");
[Link](position);
byte[] bytes = new byte[size];
[Link](bytes);
[Link]();
return bytes;
}

private static void writeToFile(String filepath, String data, int position) throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "rw");
[Link](position);
[Link]([Link]());
[Link]();
}
}

Lab 19
Write a java program to create a GUI form.

SOURCE CODE:
import [Link].*;
public class App {
public static void main(String[] args) throws Exception {
JFrame f = new JFrame();
JTextField nameField;
JTextArea addressArea;
JTextField emailField;
JRadioButton maleButton;
JRadioButton femaleButton;
JRadioButton otherButton;
JComboBox<String> countryComboBox;
JCheckBox hobbyReading;
JCheckBox hobbyTraveling;
JCheckBox hobbySports;
JButton submitButton;

[Link]("User Form");

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


[Link](20, 20, 100, 25);
nameField = new JTextField();
[Link](140, 20, 200, 25);
[Link](nameLabel);
[Link](nameField);

JLabel addressLabel = new JLabel("Address:");


[Link](20, 60, 100, 25);
addressArea = new JTextArea();
[Link](140, 60, 200, 75);
[Link](addressLabel);
[Link](addressArea);
JLabel emailLabel = new JLabel("Email:");
[Link](20, 150, 100, 25);
emailField = new JTextField();
[Link](140, 150, 200, 25);
[Link](emailLabel);
[Link](emailField);

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


[Link](20, 190, 100, 25);
maleButton = new JRadioButton("Male");
[Link](140, 190, 100, 25);
femaleButton = new JRadioButton("Female",true);
[Link](240, 190, 100, 25);
otherButton = new JRadioButton("Others");
[Link](340, 190, 100, 25);
ButtonGroup genderGroup = new ButtonGroup();
[Link](maleButton);
[Link](femaleButton);
[Link](otherButton);
[Link](genderLabel);
[Link](maleButton);
[Link](femaleButton);
[Link](otherButton);

JLabel countryLabel = new JLabel("Country:");


[Link](20, 230, 100, 25);
String[] countries = {"Nepal", "USA", "Australia", "Other" };
countryComboBox = new JComboBox<>(countries);
[Link](140, 230, 200, 25);
[Link](countryLabel);
[Link](countryComboBox);

JLabel hobbiesLabel = new JLabel("Hobbies:");


[Link](20, 270, 100, 25);
hobbyReading = new JCheckBox("Reading");
[Link](140, 270, 100, 25);
hobbyTraveling = new JCheckBox("Traveling");
[Link](140, 300, 100, 25);
hobbySports = new JCheckBox("Sports");
[Link](140, 330, 100, 25);
[Link](hobbiesLabel);
[Link](hobbyReading);
[Link](hobbyTraveling);
[Link](hobbySports);

submitButton = new JButton("Submit");


[Link](140, 380, 100, 25);
[Link](submitButton);

[Link](450, 450);
[Link](null);
[Link](true);
}
}

Lab 20
Write a java program to use GridLayout.

SOURCE CODE:
import [Link].*;
import [Link].*;

public class App {


private JFrame f;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private JButton resetButton;

App(){
f= new JFrame();
[Link]("Login Form");
[Link](new GridLayout(4,2,10,10));
userLabel= new JLabel("Username");
[Link]([Link]);
[Link](userLabel);
userText = new JTextField();
[Link](userText);
passwordLabel= new JLabel("Password");
[Link](passwordLabel);
passwordText= new JPasswordField();
[Link](passwordText);
loginButton = new JButton("Login");
[Link](loginButton);
resetButton = new JButton("Reset");
[Link](resetButton);

[Link](250,200);
[Link](true);
}
public static void main(String[] args) throws Exception {
new App();
}
}
Lab 21
Write a java program to use GridBagLayout.

SOURCE CODE:
import [Link].*;
import [Link].*;
public class App {
private JFrame f;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private JButton resetButton;
App()
{
f=new JFrame();
[Link]("Login Form");
[Link](new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link]=new Insets(5, 5, 5, 5);
[Link]=[Link];

userLabel=new JLabel("Username");
[Link]=0;
[Link]=0;
[Link](userLabel,gbc);

userText = new JTextField();


[Link]=1;
[Link]=0;
[Link](userText,gbc);

passwordLabel= new JLabel("Password");


[Link]=0;
[Link]=1;
[Link](passwordLabel,gbc);

passwordText= new JPasswordField();


[Link]=1;
[Link]=1;
[Link](passwordText,gbc);

loginButton= new JButton("Login");


[Link]=0;
[Link]=2;
[Link](loginButton,gbc);

resetButton= new JButton("Reset");


[Link]=1;
[Link]=2;
[Link](resetButton,gbc);

[Link](250,250);
[Link](true);
}
public static void main(String[] args) throws Exception {
new App();
}
}

Lab 22
Write a program using swing components to add two digits. Use text fields for inputs and
output. The program should display the result when the user presses a button.

SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;

public class App extends Frame implements ActionListener{


JLabel l1, l2;
JTextField t1, t2, t3;
JButton b1;
App()
{
l1 = new JLabel("First Number:");
[Link](20, 100, 100, 20); //x, y, width, height
t1 = new JTextField();
[Link](120, 100, 100, 20);
l2 = new JLabel("Second Number:");
[Link](20, 140, 100, 20);

t2 = new JTextField();
[Link](120, 140, 100, 20);
b1 = new JButton("Sum");
[Link](20, 170, 80, 20);
t3 = new JTextField();
[Link](120, 170, 100, 20);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(t3);
//register listener
[Link](this);//passing current instance
setSize(400,300);
setLayout(null);
setVisible(true);

}
public void actionPerformed(ActionEvent e){
if([Link]()==b1){

int num1 = [Link]([Link]());


int num2 = [Link]([Link]());
int sum = num1 + num2;
[Link]([Link](sum));
}

}
public static void main(String[] args) throws Exception {
new App();
}
}
Lab23
Write a GUI program using components to find sum and difference of two numbers. Use two
text fields for giving input and a label for output. The program should display sum if user
presses mouse and difference if user release mouse.

SOURCE CODE:
import [Link].*;
import [Link].*;
public class App implements MouseListener{
Label lbloutput;
TextField txtOne;
TextField txtTwo;
App()
{
Frame f=new Frame();
lbloutput = new Label();
[Link](20,50,100,20);
txtOne=new TextField();
[Link](20,80,100,20);
txtTwo=new TextField();
[Link](20,110,100, 20);
[Link](this);
[Link](lbloutput);
[Link](txtOne);
[Link](txtTwo);

[Link](300,300);
[Link](null);
[Link](true);
}
public void mousePressed(MouseEvent e) {
int a=[Link]([Link]());
int b=[Link]([Link]());
int c=a+b;
[Link]([Link](c));
}
public void mouseReleased(MouseEvent e) {
int a=[Link]([Link]());
int b=[Link]([Link]());
int c=a-b;
[Link]([Link](c));
}
public void mouseClicked(MouseEvent e) {

}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {

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


new App();
}
}

Mouse Pressed:

Mouse Released:

Lab 24
Write a java GUI program to calculate square of entered number.

SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;

public class App extends Frame implements ActionListener{


JLabel l1,l2;
JTextField t1, t2;
JButton b1;
App()
{
l1 = new JLabel("Enter any number:");
[Link](20, 100, 200, 20); //x, y, width, height
t1 = new JTextField();
[Link](210, 100, 100, 20);

b1 = new JButton(" Calculate Square");


[Link](60, 140, 200, 15);

l2 = new JLabel("Square of entered number:");


[Link](20, 170, 200, 20);
t2 = new JTextField();
[Link](210, 170, 100, 20);

add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
[Link](this);//passing current instance
setSize(400,300);
setLayout(null);
setVisible(true);

}
public void actionPerformed(ActionEvent e){
int num1 = [Link]([Link]());
if([Link]()==b1){
int square = num1*num1;
[Link]([Link](square));
}
}
public static void main(String[] args) throws Exception {
new App();
}
}
Lab 25
Write a java program to add two digits using RMI.

SOURCE CODE:
[Link]:
import [Link].*;
public interface Adder extends Remote{
public int add(int x, int y)throws RemoteException;
}

[Link]:
import [Link].*;
import [Link].*;

public class client{


public static void main(String[] args) throws RemoteException{
try{
Registry reg=[Link]("localhost",5000);
Adder ad=(Adder)[Link]("hi_server");
[Link]("Addition"+[Link](23,7));
}
catch(NotBoundException|RemoteException e)
{
[Link](e);
}

}
}

[Link]:
import [Link].*;
import [Link].*;
import [Link];
public class server extends UnicastRemoteObject implements Adder{
public server() throws RemoteException{
super();
}
public static void main(String[] args) throws RemoteException{
try{
Registry reg=[Link](5000);
[Link]("hi_server", new server());
[Link]("Server is Now Ready..");
}catch(RemoteException e)
{
[Link](e);
}
}
@Override
public int add(int x,int y) throws RemoteException{
return x+y;
}
}

Lab 26
Write a java program to insert five student records and display them all.

SOURCE CODE:
[Link]:
import [Link].*;

public class App {


public static void main(String[] args) throws Exception {
CRUDStudent obj=new CRUDStudent();
Scanner sc=new Scanner([Link]);
for (int i = 0; i < 5; i++) {
[Link]("Enter Record Student#: "+(i+1));
[Link]("Enter Id: ");
int id=[Link]();
[Link]("Enter Name: ");
String name=[Link]();
[Link]("Enter Email: ");
String email=[Link]();
[Link]("Enter Gender: ");
String gender=[Link]();
[Link](id, name, email, gender);
[Link]("Record Inserted");
}
[Link]();
[Link]();
}
}
[Link]:
import [Link].*;
public class CRUDStudent {
public void InsertStudent(int id, String name, String email,String gender)
{
try {

[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/sevendb?useSSL=false","ro
ot","");
String sql="insert into tblstudents(id,name,address,emailid) values(?,?,?,?)";
PreparedStatement ps = [Link](sql);
[Link](1, id);
[Link](2, name);
[Link](3, email);
[Link](4, gender);
[Link]();
[Link]();
}
catch(Exception e){ [Link](e);}
}
public void DisplayRecord()
{
try {
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/sevendb?useSSL=false","ro
ot","");

Statement stmt=[Link]();
ResultSet rs=[Link]("select * from tblstudents");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3)+"
"+[Link](4));
[Link]();
}
catch(Exception e){ [Link](e);}
}
}
Lab 27
Write a simple client and server socket program to read data from client and print in server.
SOURCE CODE:
[Link]:
import [Link].*;
import [Link].*;
public class client{
public static void main(String[] args) throws IOException{
Socket s=new Socket("localhost",4999);
PrintWriter pr=new PrintWriter([Link]());
[Link]("Raseek");
[Link]();
[Link]();
}
}
[Link]:
import [Link].*;
import [Link].*;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(4999);
Socket s=[Link]();
[Link]("Client Connected");
InputStreamReader in=new InputStreamReader([Link]());
BufferedReader bf=new BufferedReader(in);

String str=[Link]();
[Link]("Client:"+str);
[Link]();
[Link]();
}
}

Lab 28
Write a java program to split different component of URL from given url:
([Link]

SOURCE CODE:
import [Link].*;
public class App {
public static void main(String[] args) throws MalformedURLException {
URL url1 = new
URL("[Link]
2");
[Link]([Link]());
[Link]();
[Link]("Different components of the given URL:");
[Link]("Protocol: " + [Link]());
[Link]("Hostname: " + [Link]()); [Link]("Default port:- "+
[Link]());
// Retrieving the query part of URL
[Link]("Query: " + [Link]());
// Retrieving the path of URL
[Link]("Path: " + [Link]());
// Retrieving the file name
[Link]("File: " + [Link]());
// Retrieving the reference
[Link]("Reference: " + [Link]());
}
}

Lab 29
Write a
program to
display
source code
of a webpage by URLConnection class.

SOURCE CODE:
import [Link].*;
import [Link].*;

public class App {


public static void main(String[] args) throws Exception {
try {
URL url = new URL("[Link]
nepal/");
URLConnection urlcon = [Link]();
// Set User-Agent to mimic a browser
[Link]("User-Agent", "Chrome/58.0.3029.110 Safari/537.3");
InputStream stream = [Link]();
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
} catch (Exception e) {
[Link](e);
}

}
}

Lab 30
Write a program to demonstrate lifecycle of servlet.

SOURCE CODE:
[Link]:
<html>
<head>
<title>Lifecycle of Servlet</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="LifeCycleServlet">
<input type="submit" value="Invoke Life Cycle Servlet">
</form>
</body>
</html>

[Link]: (Servlet)

import [Link].*;
import [Link].*;

// now creating a servlet by implementing Servlet interface


public class LifeCycleServlet implements Servlet {
ServletConfig config = null;
// init method
public void init(ServletConfig sc)
{
config = sc;
[Link]("in init");
}
// service method
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<h3>Hello from Life Cycle Servlet</h3>");
[Link]("in service");
}
// destroy method
public void destroy()
{
[Link]("in destroy");
}
public String getServletInfo()
{
return "LifeCycleServlet";
}
public ServletConfig getServletConfig()
{
return config; // getServletConfig
}
}
Lab 31
Write a program to store and retrieve session in servlet.

SOURCE CODE:
[Link]:
<html>
<head>
<title>Session Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Servlet1" method= "GET" >
User Name: <input type="text" name= "userName" > <br/>
Password:<input type="password" name= "userPassword" > <br/>
<input type="submit" value="Go">
</form>
</body>
</html>

[Link]: (Servlet)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Servlet1 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter pwriter = [Link]();
String name = [Link]("userName");
String password = [Link]("userPassword");
[Link]("Hello " + name);
HttpSession session = [Link]();//Creating session
[Link]("uname", name);//Adding session with key value
[Link]("upass", password);
[Link]("<br/><a href='welcome'>Click to View details</a>");
[Link]();

}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

[Link]: (Servlet)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter pwriter = [Link]();
HttpSession session = [Link](false);
// The FALSE parameter indicates that you do not want to create a new session if one doesn’t
already exist.
String myName = (String) [Link]("uname");
//retrieving value from session using keyname “uname”
String myPass = (String) [Link]("upass");
[Link]("Name: " + myName + "<br/>Password: " + myPass);
[Link]();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

[Link]:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="6.0" xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Lab 32
Write a program to store, retrieve and delete cookies.

SOURCE CODE:
[Link]:
<html>
<head>
<title>Cookies Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Servlet1" method= "POST" >
Name: <input type="text" name= "userName" > <br/>
<input type="submit" value="Go">
</form>
</body>
</html>

[Link]: (Servlet)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Servlet1 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
String n = [Link]("userName");
// Ensure complete HTML structure
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Welcome Page</title>");
[Link]("</head>");
[Link]("<body>");
// Display welcome message
if (n != null && ![Link]()) {
[Link]("<h1>Welcome, " + n + "!</h1>");
// Create and add cookie
Cookie ck = new Cookie("uname", n);
[Link](ck);
// Add "Go" button
[Link]("<form action='Servlet2' method='GET'>");
[Link]("<input type='submit' value='Go'>");
[Link]("</form>");
} else {
[Link]("<h1>Name is missing! Please go back and try again.</h1>");
}
[Link]("</body>("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

[Link]: (Servlet)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
Cookie ck[]=[Link]();
[Link]("Hello "+ck[0].getValue());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

[Link]:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="6.0" xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/Servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/Servlet2</url-pattern>
</servlet-mapping>
</web-app>

OUTPUTS:
Lab 33
Write a program to 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.
SOURCE CODE:
[Link]:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form action="[Link]" 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>

[Link]:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<h1>Student Details!</h1>
Name: <%= [Link]("name") %><br>

Roll No.: <%= [Link]("roll") %><br>

Address: <%= [Link]("address") %><br>


</body>
</html>

OUTPUTS:

You might also like