JAVA PROGRAMMING LAB (PCS-353) (Pranav - Aggarwal)
JAVA PROGRAMMING LAB (PCS-353) (Pranav - Aggarwal)
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
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
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
import java.io.*;
import java.util.*;
public class Test{
void display(){ //default method
System.out.println("hi");
}
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
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;
}
OUTPUT
Code
Bank.java
CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
import java.io.*;
public class InsufficientFundsException extends Exception {
private double 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;
}
TransactioncountException.java
import java.io.*;
public class TransactioncountException extends Exception {
private double amount;
public TransactioncountException () {
}
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;
}
OneDayTransactionException.java
import java.io.*;
public class OneDayTransactionException extends Exception {
private double amount;
public OneDayTransactionException() {
}
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..
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
OUTPUT
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.
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
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.*;
"Contacts",
"Message",
"Call Log",
"Games",
"Settings",
"Applications",
"Music",
"Gallery",
"Organiser"
};
private Container c;
super("GridLayout");
c = getContentPane();
c.setLayout(grid3);
b = new JButton[names.length];
b[i].addActionListener(this);
c.add(b[i]);
setSize(400, 400);
show();
if (toggle)
c.setLayout(grid3);
else if (toggle)
c.setLayout(grid2);
else
c.setLayout(grid1);
toggle = !toggle;
c.validate();
G.addWindowListener(new WindowAdapter() {
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.*;
Frame f;
public Flow() {
f = new Frame();
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);
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.
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.*;
CardLayout crd;
// button variables to hold the references of buttons
Container cPane;
CardLayoutExample1()
cPane = getContentPane();
cPane.setLayout(crd);
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
// 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
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
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setLayout(layout);
contentPane.add(label);
contentPane.add(textField);
layout.putConstraint(SpringLayout.NORTH, label,6,SpringLayout.NORTH,
contentPane);
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);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
createAndShowGUI();
});
OUTPUT:-
ScrollPaneLayout
Constructor
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public ScrollPaneDemo() {
super("ScrollPane Demo");
getContentPane().add(png);
setSize(300,250);
setVisible(true);
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");
while (result.next())
{
System.out.println (result.getInt(1)+" "+
result.getString(2)+" "+
result.getString(3)+" "+
result.getString(4));
}
10. Write an RMI application to fetch the stored procedure from the remote
server side.
Ans –
PROGRAMS: -
1)REMOTE INTERFACE: -
import java.rmi.Remote;
import java.rmi.RemoteException;
2)REMOTE OBJECT: -
3)SERVER PROGRAM: -
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
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;
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
OUTPUT