Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Java Assigment New

The document contains 20 items describing programming tasks and questions. Item 5 describes creating a package with two classes - one for mathematics methods to add numbers and the other to find the maximum of three numbers. Item 6 describes creating an Animal interface with run() and eat() methods, and implementing those methods in Dog and Cat classes. The program outputs include adding numbers, finding the maximum value in an array, and calling run() and eat() methods on Dog and Cat objects.

Uploaded by

mohitparihar8786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Java Assigment New

The document contains 20 items describing programming tasks and questions. Item 5 describes creating a package with two classes - one for mathematics methods to add numbers and the other to find the maximum of three numbers. Item 6 describes creating an Animal interface with run() and eat() methods, and implementing those methods in Dog and Cat classes. The program outputs include adding numbers, finding the maximum value in an array, and calling run() and eat() methods on Dog and Cat objects.

Uploaded by

mohitparihar8786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

SN Title Page No Remark 1

1 WAP to sort the elements of an array in ascending order.

2 WAP to find the transpose of a given matrix.

3 How to reverse a given String? (Without using a pre-defined


function)
4 WAP to How do you check if a given String is Palindrome or not
Create a package mca1 which will have 2 classes as class
5 Mathematics with a methods to add two numbers, add three
float numbers and class Maximum with a method to find
maximum of three numbers.
Write a Java program to create Animal interface that contains
6 run() and eat() method. And implement methods in Dog and
Cat class.
Write a Java program to create an abstract class Animal that
7 contains non abstract run() and abstract eat() method…Derive
two classes Dog and Cat from it.
8 Write a Java program to test any five of standard exception

9 User-defined exception

10 Write a Java program to create a Thread by extending the


Thread class. And print the name of currently executing thread.
Write a Java program to create a Thread by Implementing the
11 Runnable Interface. And print the name of currently executing
thread.
Write a multithreaded program to print even and odd numbers.
12 Create two threads, one thread prints even number and second
thread prints odd number
13 Write a code to remove duplicates from Array List in Java.

14 Write a code to sort a linked list and Reverse a linked list in


java.
15 Write a Java program to copy the contents of a file to another
file.
16 Write Java AWT code to accept Student information and display
Student details on the Screen.
17 Write a JAVA program to design a screen using Swing to
perform String operations.
18 Write a Java code to Read, Insert, Update and Delete any record
from the database.(Employee table).
19 Write a Java Servlet Application for login page with proper
validations.
20 Write a Java program to design Registration page using JSP
1

1. WAP to sort the elements of an array in ascending order.

package assignment1;
public class sorting {

public static void main(String[] args) {


int i,j,temp;
int a[]= {2,11,15,7,18,1};
System.out.println("Array data before sorting");
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("Array data after sorting");

for(i=0;i<a.length;i++) {
for(j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}System.out.println(a[i]);
}
}
}

Output:

Array data before sorting


2
11
15
7
18
1
Array data after sorting
1
2
7
11
15
18
2

2. WAP to find the transpose of a given matrix.


package assignment1;
import java.util.Scanner;
public class TRANSPOSE_MATRIX {

public static void main(String[] args) {


int i,j;
int a[][]={{2,3,4},
{6,7,4},
{7,9,3}};
int b[][]=new int[3][3];
Scanner s=new Scanner (System.in);
System.out.println("First Matrix.... ");
for(i=0;i<a.length;i++)
{
for(j=0;j<a.length;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println("");
}
System.out.println("Transpose Matrix.... ");
for(i=0;i<b.length;i++)
{
for(j=0;j<b.length;j++)
{
b[i][j]=a[j][i];
System.out.print(b[i][j]+"\t");
}System.out.println(" ");
}

Output:

First Matrix....
2 3 4
6 7 4
7 9 3
Transpose Matrix....
2 6 7
3 7 9
4 4 3
3

3. How to reverse a given String? (Without using a pre-defined function).

package assignment1;

import java.util.Scanner;

public class REVERSE_string {

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
String s;
int i;
System.out.print("Enter a String: ");
s=sc.nextLine();
System.out.print("After reverse string is: ");
for(i=s.length();i>0;i--)
{
System.out.print(s.charAt(i-1));
}
}
}

Output:

Enter a String: john


After reverse string is: nhoj
4

4. WAP to How do you check if a given String is Palindrome or not

import java.util.Scanner;

class Palindrom_string {
public static boolean isPalindrome(String str)
{
String rev = "";
boolean ans = false;

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


rev = rev + str.charAt(i);
}
if (str.equals(rev)) {
ans = true;
}
return ans;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

String str;
System.out.print("Enter string:");
str=sc.next();
str = str.toLowerCase();

boolean A = isPalindrome(str);
if (A==true)
{
System.out.println(str+" is palindrom");
}
else
{
System.out.println(str+" is not palindrom");
}
}
}

Output:

Enter string:Nitin
Nitin is palindrom
5

5.Create a package mca1 which will have 2 classes as class Mathematics with a methods to
add two numbers, add three float numbers and class Maximum with a method to find
maximum of three numbers.

package MCA1;
import java.util.*;

public class Mathematics {


public static void main(String[] args)
{
maths m=new maths();
Maximum m1=new Maximum();
m.add();
m.add1();
m1.max();
}
}
class maths
{
Scanner s=new Scanner(System.in);
public void add()
{
int a,b,c;
System.out.println("Enter the numbers for addition:");
System.out.println("Enter first integer number:");
a=s.nextInt();
System.out.println("Enter second integer number:");
b=s.nextInt();
c=a+b;
System.out.println(" Addition of integer numbers:"+c);
System.out.println("---------------------------------"); System.out.println("");
}
public void add1()
{
float a,b,c;
System.out.println("Enter the numbers for addition:");
System.out.println("Enter first float number:");
a=s.nextFloat();
System.out.println("Enter second float number:");
b=s.nextFloat();
c=a+b;
System.out.println(" Addition of floating numbers:"+c);
System.out.println("---------------------------------");
System.out.println("");
}

}
6

class Maximum
{
Scanner s=new Scanner(System.in);
public void max()
{
int i,max=0;
int a[]= {2,5,3};
for(i=0;i<a.length;i++)
{
System.out.println("Array element are:"+a[i]);
}
max=a[0];
int sc2=0;
for(i=0;i<a.length;i++)
{
if(max<a[i])
{
max=a[i];

}
}
System.out.println(" maximum element in the array: "+max);
}
}

Output:

Enter the numbers for addition:


Enter first integer number:
22
Enter second integer number:
31
Addition of integer numbers:53
------------------------------------------------------------
Enter the numbers for addition:
Enter first float number:
12
Enter second float number:
42
Addition of floating numbers:54.0
------------------------------------------------------------
Array element are:2
Array element are:5
Array element are:3
maximum element in the array: 5
7

6. Write a Java program to create Animal interface that contains run() and eat() method.
And implement methods in Dog and Cat class.

package assignment2;
public class interface_demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
dogg d=new dogg();
catt c=new catt();
System.out.println("Class Dog...");
d.run();
d.eat();
System.out.println("Class Cat...");
c.run();
c.eat();
}
}
interface AAnimall
{
public void run();
public void eat();
}
class dogg implements AAnimall
{
public void run()
{
System.out.println("Dog is running...");
}
public void eat()
{
System.out.println("Dog is eating....");
}
}
class catt implements AAnimall
{
public void run()
{
System.out.println("Cat is running...");
}
public void eat()
{
System.out.println("Cat is running...");
}
}

Output:

Class Dog...
Dog is running...
Dog is eating....
Class Cat...
Cat is running...
Cat is running...
8

7. Write a Java program to create an abstract class Animal that contains non abstract run()
and abstract eat() method…Derive two classes Dog and Cat from it.

package assignment2;
public class abstract_class {

public static void main(String[] args) {


DOG d=new DOG();
CAT c=new CAT();
d.run();
d.eat();
c.eat();
}
}
abstract class animal
{
void run()
{
System.out.println("abstract class method running");
}
abstract void eat();
}
class DOG extends animal
{
@Override
void eat()
{
System.out.println("dog is eating");
}
}
class CAT extends animal
{
@Override
void eat()
{
System.out.println("cat is eating");
}
}

Output:

abstract class method running


dog is eating
cat is eating
9

8. Write a Java program to test any five of standard exception

package assignment2;
import java.lang.*;
public class exception {

public static void main(String[] args) {


exception d=new exception();
d.arithmatic1();
d.arrayindex();
d.nullpointer();
d.numberformat();
d.arithmatic();
}
void arithmatic1()
{
int num=10;
try {
int a=num/0;
}
catch(ArithmeticException e)
{
System.out.println("arithmatic exception is created");
}
}
void nullpointer()
{
try {
String a = null; //null value
System.out.println(a.charAt(1));
}
catch(NullPointerException e)
{
System.out.println("nullpointer exception is created");
}
}

void arrayindex()
{
int[] num= {2,4,5,2,5};
try {
System.out.println("arrayvalue:"+num[6]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(" ArrayIndexOutOfBoundsException exception is created");
}
}

void numberformat()
{
10

try {
int num1 = Integer.parseInt ("akki") ;
}
catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
void arithmatic()
{
try {
String a = "hey charlie "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

Output:

arithmatic exception is created


ArrayIndexOutOfBoundsException exception is created
nullpointer exception is created
Number format exception
StringIndexOutOfBoundsException
11

9. User-defined exception

class MyException extends Exception {


public MyException(String s)
{
super(s);
}
}
class Main {
public static void main(String args[])
{
try {
throw new MyException("Problem arrived... please solve");
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}

Output:

Caught
Problem arrived... please solve
12

10. Write a Java program to create a Thread by extending the Thread class. And print the
name of currently executing thread.

package assignment2;
import java.lang.Thread;
public class thread1_demo {

public static void main(String[] args) {


thread11 t=new thread11();
t.start();
}

}
class thread11 extends Thread
{
public void run()
{
try {
System.out.println( "The name of Thread is:"+Thread.currentThread().getName());
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

The name of Thread is:Thread-0


13

11. Write a Java program to create a Thread by Implementing the Runnable Interface. And
print the name of currently executing thread.

package assignment2;
public class thread_demo2 {

public static void main(String[] args) {

thread_run t=new thread_run();


Thread th=new Thread(t);
th.start();
}

}
class thread_run implements Runnable
{
public void run()
{
try {
System.out.println( "The name of Thread is:"+Thread.currentThread().getName());
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

The name of Thread is:Thread-0


14

12. Write a multithreaded program to print even and odd numbers. Create two threads,
one thread prints even number and second thread prints odd number

package assignment2;
public class Multi {
public static void main(String[]args)
{
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}}
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<=20;i++)
{
if (i % 2 == 0)
System.out.println(i);
}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int i=0;i<=20;i++){
if (i % 2 != 0)
System.out.println(i);
}
}
}

Output:

0 6
2 8
1 10
3 12
5 14
7 16
9 18
1 20
13
15
17
19
4
15

13. Write a code to remove duplicates from Array List in Java.

package assignment2;
import java.util.ArrayList;
class array_list{
public static void main(String[] args)
{
ArrayList<Integer> s=new ArrayList<Integer>();

//arr.add(value)-ToaddvalueintotheArrayList arr.add(5);
s.add(35);
s.add(-5);
s.add(14);
s.add(3);
s.add(12);
s.add(-5);

System.out.println("BeforeRemovingduplicate elements:"+s);

for(int i=0;i<s.size();i++){ //arr.size


for(int j=i+1;j<s.size();j++){
if(s.get(i).equals(s.get(j))){
}
}
}
System.out.println("AfterRemovingduplicate elements:"+s);
}
}

Output:

BeforeRemovingduplicate elements:[35, -5, 14, 3, 12, -5]


AfterRemovingduplicate elements:[35, -5, 14, 3, 12, -5]
16

14. Write a code to sort a linked list and Reverse a linked list in java.
package assignment2;

import java.util.LinkedList;

public class linkedlist {

public static void main(String[] args) {


{
LinkedList<Integer>list=new LinkedList<Integer>();
LinkedList<Integer>ReversedList=new LinkedList<Integer>();
//list.add(element)-ToaddelementintotheLinkedList list.add(15);
list.add(32);
list.add(17);
list.add(5);
list.add(14);
list.add(7);
list.add(-5);
for(int i=0;i<list.size();i++){ //list.size()-TogetsizeofanLinkedList
for(int j=i+1;j<list.size();j++){
if(list.get(i)>list.get(j)){

int temp=list.get(i); list.set(i, list.get(j));


list.set(j,temp);
}
}
}
for(int i=list.size()-1;i>=0;i--)
{ ReversedList.add(list.get(i));
}

//Printing Reversed LinkedList elements


System.out.print("\nReversedLinkedList:"+ReversedList);

}
}

Output:

ReversedLinkedList:[32, 17, 14, 7, 5, -5]


17

15. Write a Java program to copy the contents of a file to another file.

package assignment2;

import java.io.*;

import java.util.*;

public class copyfile {

public static void copyData(File file1, File file2) throws Exception

FileInputStream inputStream = new FileInputStream(file1);

FileOutputStream outputStream = new FileOutputStream(file2);

try {

// declare variable for indexing

int i;

while ((i = inputStream.read()) != -1) {

outputStream.write(i);

// catch block to handle exceptions

catch(Exception e) {

System.out.println("Error Found: "+e.getMessage());

finally {

if (inputStream != null) {

// use close() method of FileInputStream class to close the stream

inputStream.close();

// use close() method of FileOutputStream class to close the stream

if (outputStream != null) {

outputStream.close();
18

System.out.println("File Copied");

// main() method start

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

// create scanner class object to take file name from user

Scanner sc = new Scanner(System.in);

System.out.println("Enter the name of the file from where the data

would be copied :");

String file1 = sc.nextLine();

File a = new File("C:\\Users\\pc\\OneDrive\\Desktop\\"+file1);

System.out.println("Enter the name of the file from where the data

would be written :");

String file2 = sc.nextLine();

File b = new File("C:\\Users\\pc\\OneDrive\\Desktop\\"+file2);

sc.close();

copyData(a, b);

Output:

Enter the name of the file from where the data would be copied :
picture
Enter the name of the file from where the data would be written :
downloads
19

16. Write Java AWT code to accept Student information and display Student details on the Screen.

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

class StudentInformation extends JFrame implements


ActionListener { JLabel title, ul, l1, l2, l3, l4, l5, l6, l7, l8;
JTextField t1, t2, t3, t4, t5, t6;
JRadioButton jr1, jr2;
JCheckBox ch1, ch2, ch3, ch4;
JButton b1, b2;

StudentInformation() {
setLocation(550, 100); // Set Loaction of the
Frame setSize(450, 580); // Set Size of the
Frame

// Create a new panel on the


Frame JPanel p = new JPanel();
p.setLayout(null);

// create a label to display text


title = new JLabel("Student Information");
title.setBounds(130, 10, 300, 20); // Set label at (x axis, y axis, width, height)
title.setFont(new Font("TimesRoman", Font.BOLD, 25)); // Set a font, thickness and
size
p.add(title); // Add a Jlabel to the JPanel

ul = new JLabel("
")
; ul.setBounds(130, 18, 300, 20);
ul.setFont(new Font("TimesRoman", Font.BOLD,
15)); p.add(ul);

l1 = new JLabel("Roll No :");


l1.setBounds(20, 60, 100,
20);
l1.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(l1);
// create a
TextField t1 = new
JTextField();
t1.setBounds(150, 60, 200,
20); p.add(t1);

l2 = new JLabel("Name :");


20

p.add(l3);

t3 = new JTextField();
t3.setBounds(150, 140, 200,
20); p.add(t3);

l4 = new JLabel("Phone
Number :"); l4.setBounds(20, 180,
150, 20);
l4.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(l4);

t4 = new JTextField();
t4.setBounds(150, 180, 200,
20); p.add(t4);

l5 = new JLabel("Email ID :");


l5.setBounds(20, 220, 100, 20);
l5.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(l5);

t5 = new JTextField();
t5.setBounds(150, 220, 200,
20); p.add(t5);

l6 = new JLabel("Gender :");


l6.setBounds(20, 260, 100, 20);
l6.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(l6);

// create a radio button


jr1 = new JRadioButton("Male");
jr1.setBounds(150, 260, 100, 20);
jr1.setFont(new Font("TimesRoman", Font.BOLD,
20)); jr1.setBackground(Color.WHITE);
p.add(jr1);

jr2 = new JRadioButton("Female");

ch3 = new JCheckBox("Reading");


ch4 = new
JCheckBox("Travelling");
ch1.setBounds(150, 300, 150, 20);
ch2.setBounds(150, 340, 250, 20);
ch3.setBounds(150, 380, 150, 20);
ch4.setBounds(150, 420, 200, 20);
21

ch1.setFont(new Font("TimesRoman", Font.BOLD, 20)); //


setFont ch2.setFont(new Font("TimesRoman", Font.BOLD,
20)); // setFont ch3.setFont(new Font("TimesRoman",
Font.BOLD, 20)); // setFont ch4.setFont(new
Font("TimesRoman", Font.BOLD, 20)); // setFont
ch1.setBackground(Color.WHITE); // Changing background
color ch2.setBackground(Color.WHITE); // Changing
background color ch3.setBackground(Color.WHITE); //
Changing background color
ch4.setBackground(Color.WHITE); // Changing background
color

p.add(ch1); // Add checkbox to the JPanel


p.add(ch2); // Add checkbox to the
JPanel p.add(ch3); // Add checkbox to
the JPanel p.add(ch4); // Add
checkbox to the JPanel

// create a Submit Button


b1 = new JButton("Submit");
b1.setBounds(100, 480, 100, 30);
b1.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(b1);

// create a Reset Button


b2 = new JButton("Reset");
b2.setBounds(250, 480, 100, 30);
b2.setFont(new Font("TimesRoman", Font.BOLD,
20)); p.add(b2);

// Set a Panel Background


p.setBackground(Color.WHITE);
else
gender = "Not Selected";

if(ch1.isSelected()
){ flag++;
hobbies += "\n\t"+flag+"."+ch1.getText();
}
if(ch2.isSelected()
){ flag++;
hobbies += "\n\t"+flag+"."+ch2.getText();
}
22

if(ch3.isSelected()
){ flag++;
hobbies += "\n\t"+flag+"."+ch3.getText();
}
if(ch4.isSelected()
){ flag++;
hobbies += "\n\t"+flag+"."+ch4.getText();
}
if(flag == 0)
hobbies = "Not Selected";
String details = "------- Student Details "+"\n"
+"RollNo : "+t1.getText()+"\n"
+"Name : "+t2.getText()+"\n"
+"Address : "+t3.getText()+"\n"
+"Phone Number : "+t4.getText()+"\n"
+"Email : "+t5.getText()+"\n"
+"Gender : "+gender+"\n"
+"Hobbies : "+hobbies+"\n";

JOptionPane.showMessageDialog(null, details); // Prompt a message screen


}
else if (e.getSource() == b2)
JOptionPane.showMessageDialog(null, "Cleared !!"); // Prompt a message screen
t1.setText(null);
t2.setText(null);
t3.setText(null);
t4.setText(null);
t5.setText(null);
jr1.setSelected(false);
jr2.setSelected(false);
ch1.setSelected(false);
ch2.setSelected(false);
ch3.setSelected(false);
ch4.setSelected(false);
}

public static void main(String[] args) {


new StudentInformation().setVisible(true);
}
}
23
24

17.Write a JAVA program to design a screen using Swing to perform String operations.

import java.awt.*; import


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

public class StringOperations extends JFrame implements ActionListener {


JLabel title, line, l1;
JTextField t1, t2, t3, t4, t5;
JButton b1, b2, b3, b4;

StringOperations() {
setLocation(250, 100); // Set Loaction of the Frame
setSize(430, 330); // Set Size of the Frame

// Create a new panel on the Frame

JPanel p = new JPanel();


p.setLayout(null);
// create a label to display text
title = new JLabel("String Operations :");
title.setBounds(120, 10, 250, 30); // Set label at (x axis, y axis, width, height)
title.setFont(new Font("TimesRoman", Font.BOLD, 25)); // Set a font, thickness
and
size
p.add(title); // Add a Jlabel to the JPanel

line = new JLabel(" ");


line.setBounds(0, 40, 500, 20);
line.setFont(new Font("TimesRoman", Font.BOLD, 15));
p.add(line);

l1 = new JLabel("Enter String :");


l1.setBounds(20, 70, 150, 30);
l1.setFont(new Font("TimesRoman", Font.BOLD, 20));
p.add(l1);
// create a TextField t1
= new JTextField();
t1.setBounds(180, 70, 180, 25);
p.add(t1);
// create a Button
b1 = new JButton("LOWER"); b1.setBounds(20, 110, 100, 25); p.add(b1);

t2 = new JTextField();
t2.setBounds(180, 110, 180, 25);
p.add(t2)
25

1b2 = new
JButton("UPPER");
b2.setBounds(20, 150, 100,
25); p.add(b2);

t3 = new JTextField();
t3.setBounds(180, 150, 180,
25); p.add(t3);

b3 = new JButton("Italic");
b3.setBounds(20, 190, 100, 25);
t5.setFont(new Font("TimesRoman", Font.BOLD, 15)); //BOLD
}
}

public static void main(String[] args) {


new
StringOperations().setVisible(true);
26

18.Write a Java code to Read, Insert, Update and Delete any record from the database.(Employee table).

package mca1;

import java.sql.*;
import java.util.*;
class Employee{
Connection c;
Statement s;
Scanner sc = new Scanner (System.in);
public Employee(){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
c
=DriverManager.getConnection("jdbc:mysql:///mca1","root","");
s =c.createStatement();
}catch(Exception e){
System.out.println(e);
}
}

public void read(){ System.out.println("Employee


Records are: ");
System.out.println("Emp_ID\tEmp_Name\tAddress\t\tSalary");
try{
PreparedStatement ps=c.prepareStatement("select * from
Employee"); ResultSet rs=ps.executeQuery();
while(rs.next()){ System.out.println(rs.getInt("emp_no")+"\
t"+rs.getString("emp_name")+
"\t\t"+rs.getString("address")+"\t\t"+rs.getInt("salary"));
}
}catch(Exception e){
System.out.println(e);
}

public void insert(){


System.out.print("Enter your employee no.: "); int id = sc.nextInt();
System.out.print("Enter name : ");
String name = sc.next();

System.out.print("Enter your address :


"); String address = sc.next();
System.out.print("Enter your salary :
"); int salary = sc.nextInt();
try{
PreparedStatement ps = c.prepareStatement("insert into
Employee values('"+id+"','"+name+"', '"+address+"',
'"+salary+"')");
27

ps.executeUpdate();
System.out.println("***Employee record inserted Successfully !!***");
}catch(Exception e){
System.out.println(e
);
}
}

public void update(){


System.out.print("Enter your employee no.:
"); int id = sc.nextInt();
System.out.print("Enter name :
"); String name = sc.next();
System.out.print("Enter your address :
"); String address = sc.next();
System.out.print("Enter your salary :
"); int salary = sc.nextInt();
try{
PreparedStatement ps = c.prepareStatement("update Employee set
emp_name = '"+name+"', address = '"+address+"', salary = '"+salary+"' where
emp_no = '"+id+"'");
ps.executeUpdate();
System.out.println("***Record of employee no : "+id+" updated Successfully
!!***");
}catch(Exception e){
System.out.println(e
);
}
}

public void delete(){


System.out.print("Enter your employee no.:
"); int id = sc.nextInt();
try{
PreparedStatement ps = c.prepareStatement("delete from Employee where
emp_no = '"+id+"'");
ps.executeUpdate();
System.out.println("***Record of employee no : "+id+" deleted Successfully !!***");
}catch(Exception e){
System.out.println("\n ");
System.out.print(" 0. Exit\n 1. Read\n 2. Insert\n 3. Update\n 4. Delete\n
Enter your choice : ");
ch = sc.nextInt();
System.out.println(" ")
; switch(ch){
case 1:
e.read(
);
break;
case 2:
e.insert(
28

); break;
case 3:
e.update(
); break;
case 4:
e.delete(
); break;
case 0:
System.exit(0);

Default:System.out.println(“please enter valid number”);

}
}
}
29

Output:
30

19: Write a Java Servlet Application for login page with proper validations.

Login1>login.html

<html>
<body>
<form
action=http://localhost:8080/Login1/Logi
n> Email: <input type=email name=email
required>
<br>
Password: <input type=password name=pass required><br>
<input type=submit value=LOGIN>
</form>
<p>correct Email: abcd@gmail.com<br>password:1234
</body
</html>

Login1>WEB-INF>web.xml

<?xml version="1.0" ?>


<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>

Login1>WEB-INF>classes>Login.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
31

class Login extends HttpServlet{


public class Login extends HttpServlet{

public void doGet(HttpServletRequest


request,HttpServletResponse response){ try{
PrintWriter out=
response.getWrite
r();
out.println("<htm
l><body>");

String email =
request.getParameter("e
mail"); String pass =
request.getParameter("p
ass");
out.println("<p>You entered:<br>Email: "+email+"<br>Password:
"+pass+"</p>");

if(email.equals("abcd@gmail.com") &&
pass.equals("1234")){
out.println("<p>Login Successfull!!
</p>");
}
else{
out.println("<p>Incorrect LoginId or Password!!</p>");
}
out.println("</html></body>");
}
catch(Exception e){
System.out.printl
n("Exception :
"+e);
}
}
}

Ouput:

1.Login Form
32

2.After entering correct ID and Password

3.Validation 4.Validation

5.Incorrect ID/Password
33

20. Write a Java program to design Registration page using JSP.

Register>register.html

<html>
<body>
<form action=http://localhost:8080/Register/register.jsp>
<h2>REGISTERATION PAGE:</h2><br>
Email: <input type=email name=email required>
<br>
Password: <input type=password name=pass required><br>
<input type=submit value=LOGIN>
</form>
</body
</html>

Register>register.jsp

<%@page import="java.util.*,java.text.*,java.sql.*" %>

<%String email = request.getParameter("email");

String pass = request.getParameter("pass");

try{

Connection con; Statement st; ResultSet rs;

Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection("jdbc:postgresql:te512","postgres","");

st=con.createStatement();

rs= st.executeQuery("select * from login where email='"+email+"'");

if(!rs.next()){ //if no such email is already present

st.executeUpdate("insert into login values('"+email+"','"+pass+"')");

out.println("Registeration Successfull! ");

}else{ //if there is already same email in dB

out.println("Registeration Failed! <br> The Email entered Alreadys exist!!");

out.println("<br><br>Email:"+email+"<br>Password:"+pass);

}catch(Exception e){

out.println("Some eXCEPTION Occured"+e);

}
34

Output:

1. Enter Email and Password 2. Registration Successful

3. Entering already existing mail 4. Registration Failed

You might also like