0% found this document useful (0 votes)
79 views

JAVA PROGRAMMING LAB (PCS-353) (Pranav - Aggarwal)

This document describes a Java programming lab course for a 5th semester B.Tech program in Computer Science and Engineering. The course aims to develop programs using object-oriented concepts like inheritance, interfaces, exception handling, and GUI and web application development. It lists 4 experiments on topics like matrix multiplication using multi-dimensional arrays, implementing string class functionalities, demonstrating inheritance with access specifiers, and developing a banking application with exception handling for insufficient balance and withdrawal amounts greater than balance.

Uploaded by

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

JAVA PROGRAMMING LAB (PCS-353) (Pranav - Aggarwal)

This document describes a Java programming lab course for a 5th semester B.Tech program in Computer Science and Engineering. The course aims to develop programs using object-oriented concepts like inheritance, interfaces, exception handling, and GUI and web application development. It lists 4 experiments on topics like matrix multiplication using multi-dimensional arrays, implementing string class functionalities, demonstrating inheritance with access specifiers, and developing a banking application with exception handling for insufficient balance and withdrawal amounts greater than balance.

Uploaded by

Utsav Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

PCS-353 Java Programming Lab

B.Tech. Semester –V (Computer Science & Engg.)

L T P Class Work : 25 Marks


- - 2 Exam. : 25 Marks
Total : 50 Marks
Duration of Exam : 2 Hrs.

COURSE OUTCOMES Upon successful completion of the course, the students will be able to
• Develop programs using object oriented concepts using arrays and string classes
• Demonstrate features such as Inheritance, Interfaces with access specifiers and exception
handling
• Demonstrate multithreading programming concepts to solve real world problems
• Design and implement GUI based applications.
• Develop web application using JDBC and Servlets

LIST OF EXPERIMENTS

1-Write a program to implement matrix multiplication using multi-


dimensional arrays.
Ans –
Code
import java.util.Scanner;

class MatixMulti
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the matrices.");
n = input.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
System.out.println("Enter the numbers of the first matrix. Numbers will be added row wise \
n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
System.out.println("Enter the numbers of the 2nd matrix. Numbers will be added row wise.
\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = input.nextInt();
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product of the matrices is shown as below");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT

2. Write a program to implement all String class functionalities.


Ans – String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java,
string is an immutable object which means it is constant and can cannot be changed once it has
been created.
import java.io.*;
import java.util.*;
class Test
{
    public static void main (String[] args)
    {
        String s= "GBPIET";
        // or String s= new String ("GBPIET");
 
        // Returns the number of characters in the String.
        System.out.println("String length = " + s.length());
 
        // Returns the character at ith index.
        System.out.println("Character at 3rd position = "
                           + s.charAt(3));
 
        // Return the substring from the ith  index character
        // to end of string
        System.out.println("Substring " + s.substring(3));
 
        // Returns the substring from i to j-1 index.
        System.out.println("Substring  = " + s.substring(1,4));
 
        // Concatenates string2 to the end of string1.
        String s1 = "Pauri";
        String s2 = "Garhwal";
        System.out.println("Concatenated string  = " +
                            s1.concat(s2));
 
        // Returns the index within the string
        // of the first occurrence of the specified string.
        String s4 = "Learn Share Learn";
        System.out.println("Index of Share " +
                           s4.indexOf("Share"));
 
        // Returns the index within the string of the
        // first occurrence of the specified string,
        // starting at the specified index.
        System.out.println("Index of a  = " +
                           s4.indexOf('a',3));
 
        // Checking equality of Strings
        Boolean out = "GBPIET".equals("gbpiet");
        System.out.println("Checking Equality  " + out);
        out = "GBPIET".equals("GBPIET");
        System.out.println("Checking Equality  " + out);
 
        out = "GBpiet".equalsIgnoreCase("gbPIet");
        System.out.println("Checking Equality " + out);
         
        //If ASCII difference is zero then the two strings are similar
        int out1 = s1.compareTo(s2);
        System.out.println("the difference between ASCII value is="+out1);
        // Converting cases
        String word1 = "SacHin";
        System.out.println("Changing to lower Case " +
                            word1.toLowerCase());
 
        // Converting cases
        String word2 = "gbpiet";
        System.out.println("Changing to UPPER Case " +
                            word2.toUpperCase());
 
        // Trimming the word
        String word4 = " Learn Share Learn ";
        System.out.println("Trim the word " + word4.trim());
 
        // Replacing characters
        String str1 = "Heppo";
        System.out.println("Original String " + str1);
        String str2 = "feeksforfeeks".replace('p' ,'l') ;
        System.out.println("Replaced p with l -> " + str2);
    }
}

Output-
String length = 6
Character at 3rd position = I
Substring IET
Substring = BPI
Concatenated string = PauriGarhwal
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality true
the difference between ASCII value is=9
Changing to lower Case sachin
Changing to UPPER Case GBPIET
Trim the word Learn Share Learn
Original String Heppo
Replaced p with l -> hello

3- Write a program to demonstrate the working of access specifiers in


Inheritance.
Ans –
The keywords that define the access scope is known as access specifier.
Access specifier or modifier is the access type of the method.
It specifies the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.

import java.io.*;
import java.util.*;
public class Test{
   
   void display(){      //default method
     System.out.println("hi");
   }

   private int sum;    //Private Access Specifier

   public String name = "JAVA";  //Public Access Specifier

   protected void sum(int x,int y){   //Protected Access specifier


          s=x+y;
          System.out.println(s);
     }
}

public class Class2 extends Test{


    public static void main(String[] args){
        Test t1=new Class2();
        t1.display();
    t1.sum(10,10);
    System.out.println(t1.name);
   }
}

OUTPUT
hi
20
JAVA

4. Develop a program for banking application with exception handling. Handle the exceptions in
following cases:
a) Account balance <1000

Code
Bank.java

public class Bank {


public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);

try {
System.out.println("Depositing 200...");
c.deposit(200.00);
}catch(InsufficientBalanceException e) {
System.out.println("Your Acoount has low balance, it is short by "+e.getAmount());
e.printStackTrace();
}
}}
CheckingAccount.java

import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) throws InsufficientBalanceException{


balance += amount;
if(balance<1000.00)
throw new InsufficientBalanceException(1000.00-balance);
}

public double getBalance() {


return balance;
}

public int getNumber() {


return number;
}
}
InsufficientBalanceException.java
import java.io.*;
public class InsufficientBalanceException extends Exception {
private double amount;

public InsufficientBalanceException(double amount) {


this.amount=amount;
}

public double getAmount() {


return amount;
}
}

OUTPUT

b) Withdrawal amount is greater than balance amount

Code
Bank.java

public class Bank {


public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 2000...");
c.deposit(2000.00);
try {
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 600...");
c.withdraw(600.00);
System.out.println("\nWithdrawing 1000...");
c.withdraw(1000.00);
}catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short money by "+e.getAmount());
e.printStackTrace();
}
}}

CheckingAccount.java

import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException


{
if(amount <= balance)
{
balance -= amount;
}else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}}

public double getBalance() {


return balance;
}

public int getNumber() {


return number;
}
}
InsufficientFundsException.java

import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;

public InsufficientFundsException (double amount) {


this.amount=amount;
}

public double getAmount() {


return amount;
}
}

OUTPUT
c) Transaction count exceeds 3

Code
Bank.java
public class Bank {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 4000...");
c.deposit(4000.00);
try {
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
}catch(TransactioncountException e) {
System.out.println("Your Transactions limit exeded ");
e.printStackTrace();
}
}}

CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
int count=0;
public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) {


count++;
balance += amount;
}

public void withdraw(double amount) throws TransactioncountException {


count++;
if(count>3) {
throw new TransactioncountException();
}
}
public double getBalance() {
return balance;
}

public int getNumber() {


return number;
}
}

TransactioncountException.java

import java.io.*;
public class TransactioncountException extends Exception {
private double amount;

public TransactioncountException () {
}

public double getAmount() {


return amount;
}
}

OUTPUT
d) One day transaction exceeds 1 lakh.
Code
Bank.java
public class Bank {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 200000...");
c.deposit(200000.00);
try {
System.out.println("\nWithdrawing 50000...");
c.withdraw(50000.00);
System.out.println("\nWithdrawing 50000...");
c.withdraw(50000.00);
System.out.println("\nWithdrawing 5000...");
c.withdraw(5000.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
}catch(OneDayTransactionException e) {
System.out.println("Your One Day Transactions exeded ");
e.printStackTrace();
}
}}

CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
double transaction=0.0;
public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws OneDayTransactionException {


transaction=transaction+amount;
if(transaction>100000) {
throw new OneDayTransactionException();
}
}

public double getBalance() {


return balance;
}

public int getNumber() {


return number;
}
}

OneDayTransactionException.java

import java.io.*;
public class OneDayTransactionException extends Exception {
private double amount;

public OneDayTransactionException() {
}

public double getAmount() {


return amount;
}
}

OUTPUT
5. Write a program to implement Thread class and runnable interface.
Ans –
1) Java Thread Example by extending Thread class:
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start(); SS
}
}
Output: thread is running..

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

6. Write a program to implement producer-consumer problem using Inter


threaded communication
CODE

//Producer and consumer problem


class Program
{
public static void main(String ar[])
{
Q q= new Q();
new Producer(q);
new Consumer(q);
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q =q;
new Thread(this," producer").start();
}
public void run()
{
int i= 0;
while(true)
{
q.put(i++);
if(i== 5)
System.exit(0);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q= q;
new Thread(this, "consumer").start();
}
public void run()
{
while(true)
q.get();
}
}

class Q
{
int n;
boolean valueset= false;
synchronized int get()
{
while(!valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
System.out.println("GET " +n);
valueset= false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
this.n= n;
valueset =true;
System.out.println("PUT " +n);
notify();
}
}

OUTPUT
7. Write a program to demonstrate the usage of event handling.
Ans –
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.
CODE

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

OUTPUT

8. Write a program to depict all the cases of layout manager.


Ans-
A layout manager is an object that controls the size and position of the components in the container.
Every container object has a layout manager object that controls its layout.

 
Actually, layout managers are used to arrange the components in a specific manner.  It is an interface
that is implemented by all the classes of layout managers.  There are some classes that represent the
layout managers.

There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Border Layout Manager

In the Border Layout Manager, the components are positioned in five different areas
(regions).   In other words, North, South, East, West and Center.  Each region may
contain only one component. 

If you enlarge the window, you will notice that the center area gets as much of the newly
available space, as possible. The other area will expand, only as much as necessary, to
keep the available space filled.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Border extends JFrame
implements ActionListener {
private JButton b[];
private String names[] = {
"Hide North Border",
"Hide South Border",
"Hide East Border",
"Hide West Border",
"Hide Center Border"
};
private BorderLayout layout;
public Border() {
super("BorderLayout");
layout = new BorderLayout(5, 5);
Container c = getContentPane();
c.setLayout(layout);
b = new JButton[names.length];
for (int i = 0; i < names.length; i++) {
b[i] = new JButton(names[i]);
b[i].addActionListener(this);
}
c.add(b[0], BorderLayout.NORTH);
c.add(b[1], BorderLayout.SOUTH);
c.add(b[2], BorderLayout.EAST);
c.add(b[3], BorderLayout.WEST);
c.add(b[4], BorderLayout.CENTER);
setSize(400, 300);
show();
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < b.length; i++)
if (e.getSource() == b[i])
b[i].setVisible(false);
else
b[i].setVisible(true);
layout.layoutContainer(getContentPane());
}
public static void main(String args[]) {
Border bord = new Border();
bord.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

OUTPUT

Grid Layout Manager


 
Grid Layout is used to place the components in a grid of cells (rectangular).  Each
component takes the available space within its cell.  Each cell, has exactly the same
size and displays only one component.  If the Grid Layout window is expanded, the Grid
Layout changes the cell size, so that the cells are as large as possible.

In other words, the layout manager divides the container into a grid, so that components
can be placed in rows and columns.  Each component will have the same width and
height.  The components are added to the grid starting at the top-left cell and
proceeding left-to-right, until the row is full.  Then go to the next row.  This type of layout
is known as, the Grid Layout Manager.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Grid extends JFrame implements ActionListener {

private JButton b[];

private String names[] = {

"Contacts",

"Message",

"Call Log",

"Games",

"Settings",

"Applications",

"Music",

"Gallery",

"Organiser"

};

private boolean toggle = true;

private Container c;

private GridLayout grid1, grid2, grid3;


public Grid() {

super("GridLayout");

grid1 = new GridLayout(2, 3, 5, 5);

grid2 = new GridLayout(3, 2);

grid3 = new GridLayout(3, 5);

c = getContentPane();

c.setLayout(grid3);

b = new JButton[names.length];

for (int i = 0; i < names.length; i++) {

b[i] = new JButton(names[i]);

b[i].addActionListener(this);

c.add(b[i]);

setSize(400, 400);

show();

public void actionPerformed(ActionEvent e) {

if (toggle)

c.setLayout(grid3);

else if (toggle)

c.setLayout(grid2);

else

c.setLayout(grid1);

toggle = !toggle;

c.validate();

public static void main(String args[]) {


Grid G = new Grid();

G.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

OUTPUT
Flow Layout manager
 

The flow layout, is the most basic layout manager in which components are placed from
left to right, as they were added.  When the horizontal row is too small, to put all the
components in one row, then it uses multiple rows.  You can align the components left,
right, or center (default).

import java.awt.*;

import javax.swing.*;

public class Flow {

Frame f;

public Flow() {

f = new Frame();

Button b1 = new Button("Red");

JButton b2 = new JButton("Green");

JButton b3 = new JButton("Yellow");

JButton b4 = new JButton("Purple");

JButton b5 = new JButton("Blue");

JButton b6 = new JButton("Pink");

JButton b7 = new JButton("Brown");

f.add(b1);

f.add(b2);

f.add(b3);

f.add(b4);
f.add(b5);

f.add(b6);

f.add(b7);

f.setLayout(new FlowLayout(FlowLayout.LEFT));

f.setSize(400, 200);

f.setVisible(true);

public static void main(String[] args) {

new Flow();

OUTPUT:-
Java CardLayout

The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known
as CardLayout.

Constructors of CardLayout Class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.


2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

Commonly Used Methods of CardLayout Class

o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of
the given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class CardLayoutExample1 extends JFrame implements ActionListener

CardLayout crd;
// button variables to hold the references of buttons

JButton btn1, btn2, btn3;

Container cPane;

// constructor of the class

CardLayoutExample1()

cPane = getContentPane();

//default constructor used

// therefore, components will

// cover the whole area

crd = new CardLayout();

cPane.setLayout(crd);

// creating the buttons

btn1 = new JButton("Hello");

btn2 = new JButton("There");

btn3 = new JButton("Bot");

// adding listeners to it

btn1.addActionListener(this);
btn2.addActionListener(this);

btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1

cPane.add("b", btn2); // first card is the button btn2

cPane.add("c", btn3); // first card is the button btn3

public void actionPerformed(ActionEvent e)

// Upon clicking the button, the next card of the container is shown

// after the last card, again, the first card of the container is shown upon clicking

crd.next(cPane);

// main method

public static void main(String argvs[])

// creating an object of the class CardLayoutExample1

CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300

crdl.setSize(300, 300);
crdl.setVisible(true);

crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);

OUTPUT:-
Java SpringLayout
A SpringLayout arranges the children of its associated container according to a set of
constraints. Constraints are nothing but horizontal and vertical distance between two-component
edges. Every constraint is represented by a SpringLayout.Constraint object.

Each child of a SpringLayout container, as well as the container itself, has exactly one set of
constraints associated with them.

Each edge position is dependent on the position of the other edge. If a constraint is added to
create a new edge, than the previous binding is discarded. SpringLayout doesn't automatically set
the location of the components it manages.

Constructor

SpringLayout(): The default constructor of the class is used to instantiate the SpringLayout


class.

import java.awt.Container;
import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.SpringLayout;

public class MySpringDemo {

private static void createAndShowGUI() {

JFrame frame = new JFrame("MySpringDemp");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container contentPane = frame.getContentPane();

SpringLayout layout = new SpringLayout();

contentPane.setLayout(layout);

JLabel label = new JLabel("Label: ");

JTextField textField = new JTextField("My Text Field", 15);

contentPane.add(label);

contentPane.add(textField);

layout.putConstraint(SpringLayout.WEST, label,6,SpringLayout.WEST, contentPane);

layout.putConstraint(SpringLayout.NORTH, label,6,SpringLayout.NORTH,
contentPane);

layout.putConstraint(SpringLayout.WEST, textField,6,SpringLayout.EAST, label);

layout.putConstraint(SpringLayout.NORTH, textField,6,SpringLayout.NORTH,
contentPane);

layout.putConstraint(SpringLayout.EAST, contentPane,6,SpringLayout.EAST,
textField);
layout.putConstraint(SpringLayout.SOUTH, contentPane,6,SpringLayout.SOUTH,
textField);

frame.pack();

frame.setVisible(true);

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

});

OUTPUT:-
ScrollPaneLayout

The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine


components: a viewport, two scrollbars, a row header, a column header, and four
"corner" components.

Constructor

ScrollPaneLayout(): The parameterless constructor is used to create a new


ScrollPanelLayout.

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class ScrollPaneDemo extends JFrame

public ScrollPaneDemo() {

super("ScrollPane Demo");

ImageIcon img = new ImageIcon("hello.png");

JScrollPane png = new JScrollPane(new JLabel(img));

getContentPane().add(png);

setSize(300,250);

setVisible(true);

public static void main(String[] args) {

new ScrollPaneDemo();

}
9-Create a Student database and store the details of the students in a table.
Perform the SELECT, INSERT, UPDATE and DELETE operations using
JDBC connectivity.
Ans-
import java.sql.*;
class StudentRecord
{
     public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
     public static final String DBUSER = "local";
     public static final String DBPASS = "test";
     public static void main(String args[])
     {
          try
          {
               //Loading the driver
               Class.forName("oracle.jdbc.driver.OracleDriver");
               //Cretae the connection object
               Connection con = DriverManager.getConnection(DBURL, DBUSER,
DBPASS);
               //Insert the record
               String sql = "INSERT INTO emp (student_id, studentname, email,
city) VALUES (?, ?, ?, ?)";
               PreparedStatement statement = con.prepareStatement(sql);
               statement.setInt(1, 100);
               statement.setString(2, "Prashant");
               statement.setString(3, "[email protected]");
               statement.setString(4, "Pune");

               int rowsInserted = statement.executeUpdate();


               if (rowsInserted > 0)
               {
                    System.out.println("A new Student was inserted
successfully!\n");
               }
               // Display the record
               String sql1 = "SELECT * FROM Student";
               Statement stmt = con.createStatement();
               ResultSet result = stmt.executeQuery(sql1);

               while (result.next())
               {
                    System.out.println (result.getInt(1)+" "+
                    result.getString(2)+" "+
                    result.getString(3)+" "+
                    result.getString(4));
               }

               //Update the record


               String sql2 = "Update Student set email = ? where studentname
= ?";
               PreparedStatement pstmt = con.prepareStatement(sql2);
               pstmt.setString(1, "[email protected]");
               pstmt.setString(2, "Jaya");
               int rowUpdate = pstmt.executeUpdate();
               if (rowUpdate > 0)
               {
                    System.out.println("\nRecord updated successfully!!\n");
               }

               //Delete the record


               String sql3 = "DELETE FROM Student WHERE studentname=?";
               PreparedStatement statement1 = con.prepareStatement(sql3);
               statement1.setString(1, "Prashant");

               int rowsDeleted = statement1.executeUpdate();


               if (rowsDeleted > 0)
               {
                    System.out.println("A Student was deleted successfully!\n");
               }
          }
          catch(Exception ex)
          {
               ex.printStackTrace();
          }
     }
}

10. Write an RMI application to fetch the stored procedure from the remote
server side.
Ans –

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed


application in java. The RMI allows an object to invoke methods on an object running in another
JVM.The RMI provides remote communication between the applications using two
objects stub and skeleton.

PROGRAMS: -
1)REMOTE INTERFACE: -

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

// Creating Remote interface for our application


public interface Hello extends Remote {
void printMsg() throws RemoteException;
}

2)REMOTE OBJECT: -

// Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
System.out.println("This is an example RMI program");
}
}

3)SERVER PROGRAM: -

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

4)CLIENT PROGRAM: -

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

STEP1: -START THE rmiregistry: -

STEP2: -START THE SERVER: -


STEP3: -START THE CLIENT: -

10.Design a login page using servlets and validate the username and
password by comparing the details stored in the database.
Ans –
JAVA CODE

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
   
    private static final long serialVersionUID = 1L;      
   
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
   
    // From login.jsp, as a post method only the credentials are passed
    // Hence the parameters should match both in jsp and servlet and
      // then only values are retrieved properly
    protected void doPost(HttpServletRequest request, HttpServletResponse
response)
            throws ServletException, IOException {
        // We can able to get the form data by means of the below ways.
        // Form arguments should be matched and then only they are
recognised
        // login.jsp component names should match and then only
          // by using request.getParameter, it is matched
        String emailId = request.getParameter("emailId");
        String password = request.getParameter("password");
        // To verify whether entered data is printing correctly or not
        System.out.println("emailId.." + emailId);
        System.out.println("password.." + password);
        // Here the business validations goes. As a sample,
          // we can check against a hardcoded value or pass
          // the values into a database which can be available in
local/remote  db
        // For easier way, let us check against a hardcoded value
        if (emailId != null && emailId.equalsIgnoreCase("[email protected]")
&& password != null && password.equalsIgnoreCase("admin")) {
            // We can redirect the page to a welcome page
            // Need to pass the values in session in order
              // to carry forward that one to next pages
            HttpSession httpSession = request.getSession();
            // By setting the variable in session, it can be forwarded
            httpSession.setAttribute("emailId", emailId);
            request.getRequestDispatcher("welcome.jsp").forward(request,
response);
        }
    }
}

HTML CODE

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
 
<!-- css related code which we can have either in
     same jsp or separately also in a css file -->
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
 
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
 
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}
 
button:hover {
  opacity: 0.8;
}
 
.cancelbutton {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}
 
.container {
  padding: 16px;
}
 
span.psw {
  float: right;
  padding-top: 16px;
}
 
/* Change styles for span and cancel button
   on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbutton {
     width: 100%;
  }
}
</style>
   
<!-- End of css related code which we can have either in
     same jsp or separately also in a css file -->
 
<!-- Client side validations that need to be handled in javascript,
      it can be handled in separate file or in same jsp -->
<script type="text/javascript">
function ValidateEmail(emailId)
{
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(emailId.value.match(mailformat))
    {
        document.getElementById('password').focus();
        return true;
    }
    else
    {
        alert("You have entered an invalid email address!");
        document.getElementById('emailId').focus();
        return false;
    }
}
</script>
 
<!-- End of client side validations that need to be handled
     in javascript, it can be handled in separate file or in same jsp -->
</head>
<body>
 
    <!-- We should have a servlet in order to process the form in
          server side and proceed further -->
    <form action="loginServlet" method="post"
onclick="ValidateEmail(document.getElementById('emailId'))">
         <div class="container">
    <label for="username"><b>Email</b></label>
    <input type="text" placeholder="Please enter your email" name="emailId"
id = "emailId" required>
 
    <label for="password"><b>Password</b></label>
    <input type="password" placeholder="Please enter Password"
name="password" id="password" required>
         
    <button type="submit">Login</button>
    <label>
      <input type="checkbox" checked="checked" name="rememberme"> Remember
me
    </label>
  </div>
 
  <div class="container" style="background-color:#f1f1f1">
    <button type="button" class="cancelbutton">Cancel</button>
    <span class="psw">Forgot <a
href="<%=request.getContextPath()%>/forgotpassword.jsp">password?</a></span>
  </div>
    </form>
</body>
</html>

OUTPUT

You might also like