JAVA PROGRAMMING LAB MANUAl
JAVA PROGRAMMING LAB MANUAl
LAB MANUAL
1
PCS-353 JAVA PROGRAMMING LAB L T P
Total Contact Hours - 20 0 0 2
Prerequisite –Fundamentals of Computing and Programming, Object
OrientedProgramming Using C++
Lab Manual Designed by – Dept. of Computer Science and Engineering.
OBJECTIVES
The main objective of this lab manual is to develop Core Java Programming Concepts.
COURSE OUTCOMES (COs)
CO1 Develop programs using object oriented concepts using arrays and string classes.
CO2 Demonstrate features such as Inheritance, Interfaces with access specifiers and
exception handling
2
LIST OF EXPERIMENTS
1. Write a program to implement matrix multiplication using multi-dimensional arrays.
2. Write a program to implement all String class functionalities.
3. Write a program to demonstrate the working of access specifiers in Inheritance.
4. Develop a program for banking application with exception handling. Handle the exceptions in following
cases:
a) Account balance <1000
b) Withdrawal amount is greater than balance amount
c) Transaction count exceeds 3
d) One day transaction exceeds 1 lakh.
5. Write a program to implement Thread class and runnable interface.
6. Write a program to implement producer-consumer problem using Inter threaded communication
7. Write a program to demonstrate the usage of event handling.
8. Write a program to depict all the cases of layout manager.
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.
10. Write an RMI application to fetch the stored procedure from the remote server side.
11. Design a login page using servlets and validate the username and password by comparing the details
stored in the database.
3
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++)
4
{
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
5
6
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");
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());
// 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
8
Replaced p with l -> hello
9
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{
10
}
}
OUTPUT
hi
20
JAVA
11
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;
}
12
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;
OUTPUT
13
b) Withdrawal amount is greater than balance amount
Code
Bank.java
CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
14
this.number = number;
}
InsufficientFundsException.java
import java.io.*;
15
public class InsufficientFundsException extends Exception {
private double amount;
OUTPUT
Code
Bank.java
public class Bank {
16
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;
}
17
public void deposit(double amount) {
count++;
balance += amount;
}
TransactioncountException.java
import java.io.*;
public class TransactioncountException extends Exception {
private double amount;
public TransactioncountException () {
}
OUTPUT
19
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
21
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..
22
6. Write a program to implement producer-consumer problem using Inter threaded
communication
CODE
class Q
{
int n;
boolean valueset= false;
synchronized int get()
{
while(!valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
System.out.println("GET " +n);
24
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
25
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
27
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
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() {
28
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() {
29
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
OUTPUT
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.*;
30
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);
31
}
});
}
}
OUTPUT
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);
32
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:-
33
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, "prasant@saxena.com");
statement.setString(4, "Pune");
while (result.next())
{
System.out.println (result.getInt(1)+" "+
result.getString(2)+" "+
result.getString(3)+" "+
result.getString(4));
}
34
String sql2 = "Update Student set email = ? where studentname = ?";
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, "Jaya@gmail.com");
pstmt.setString(2, "Jaya");
int rowUpdate = pstmt.executeUpdate();
if (rowUpdate > 0)
{
System.out.println("\nRecord updated successfully!!\n");
}
35
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;
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;
36
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;
37
STEP2: -START THE SERVER: -
38
11. 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 {
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
HTML CODE
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 {
40
opacity: 0.8;
}
.cancelbutton {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
<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>
42
OUTPUT
43