II II Java Lab Manual
II II Java Lab Manual
LAB MANUAL
II Year II Semester
INSTITUTION VISION
To be a premier Institution in Engineering & Technology and Management with competency,
valuesand social consciousness.
INSTITUTION MISSION
IM1 Provide high quality academic programs, training activities and research facilities.
IM3 Contribute to the Economical and technological development of the region, state and nation.
DEPARTMENT VISION
To be a recognized knowledge center in the field of Information Technology with self -
motivated, employable engineers to society.
DEPARTMENT MISSION
The Department has following Missions:
DM1 To offer high quality student centric education in Information Technology.
PEO1: Higher Studies: Graduates with an ability to apply knowledge of Basic sciences
and programming skills in their career and higher education.
PEO2: Lifelong Learning: Graduates with an ability to adopt new technologies for ever
changing IT industry needs through Self-Study, Critical thinking and Problem solving skills.
PEO3: Professional skills: Graduates will be ready to work in projects related to
complex problems involving multi-disciplinary projects with effective analytical skills.
PEO4: Engineering Citizenship: Graduates with an ability to communicate well and
exhibitsocial, technical and ethical responsibility in process or product.
PROGRAM OUTCOMES (POs) & PROGRAM SPECIFIC OUTCOMES (PSOs)
PO Description
PO 1
Engineering Knowledge:Apply knowledge of mathematics, natural science, computing, engineering
fundamentals and an engineering specialization as specified in WK1 to WK4 respectively to
develop to the solution of complex engineering problems.
PO 2 Problem Analysis: Identify, formulate, review research literature and analyze complex engineering
problems reaching substantiated conclusions with consideration for sustainable development.
(WK1 to WK4)
PO 3 Design/Development of Solutions: Design creative solutions for complex engineering problems and
design/develop systems/components/processes to meet identified needs with consideration for
the public health and safety, whole-life cost, net zero carbon, culture, society and environment
as required. (WK5)
PO 4 Conduct Investigations of Complex Problems: Conduct investigations of complex engineering problems
using research-based knowledge including design of experiments, modelling, analysis &
interpretation of data to provide valid conclusions. (WK8).
PO 5 Engineering Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering & IT tools, including prediction and modelling recognizing their limitations to solve
complex engineering problems. (WK2 and WK6)
PO 6 The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving
complex engineering problems for its impact on sustainability with reference to economy,
health, safety, legal framework, culture and environment. (WK1, WK5, and WK7).
PO 7 Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and
inclusion; adhere to national & international laws. (WK9)
PO 8 Individual and Collaborative Team work: Function effectively as an individual, and as a member or
leader in diverse/multi-disciplinary teams.
PO 10 Project Management and Finance: Apply knowledge and understanding of engineering management
principles and economic decision-making and apply these to one’s own work, as a member and
leader in a team, and to manage projects and in multidisciplinary environments.
PO 11 Life-Long Learning: Recognize the need for, and have the preparation and ability for i) independent
and life-long learning ii) adaptability to new and emerging technologies and iii) critical thinking in
the broadest context of technological change. (WK8)
Program Specific Outcomes
Software Development: To apply the knowledge of Software Engineering, Data Communication, Web
PSO 1
Technology and Operating Systems for building IOT and Cloud Computing applications.
PSO 2 Industrial Skills Ability: Design, develop and test software systems for world-wide network of
computers to provide solutions to real world problems.
PSO 3 Project implementation: Analyze and recommend the appropriate IT Infrastructure required for the
implementation of a project.
Course Code & Name: R22CSI2228 & JAVA PROGRAMMING LAB
Illustrate the concepts of layout managers, and applets for a given problem. (L3-Apply)
C2228.1
Examine the Exception handling mechanism and multithreading environment by using a java
C2228.2 programs. (L3-Apply)
Justify the concept of OOPs as well as the purpose and usage principles of inheritance,
C2228.3 polymorphism, encapsulation and method overloading. (L5-Evaluate).
Develop the database management system concepts like create insert delete update select for
C2228.4 standalone applications. (L6-Create)
Create GUI based applications through the knowledge on event handling mechanism andApplets.
C2228.5 (L6-Create)
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P10 P11 PSO1 PSO2 PSO3
C22L8 .1 3 1 2 1 3 - - - - - - - 1 -
C22L8 .2 3 1 1 1 3 - - - - - - - 1 -
C22L8 .3 1 1 2 3 3 - - - - - - - 1 1
C22L8 .4 1 - 1 1 3 - - - - - - 1 1 1
C22L8.5 1 1 2 1 3 - - - - - - 1 1 1
C22L8 .6 1 - - 3 3 - - - - - - - - -
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
thosewho come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure,Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed inthe lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allottedto you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book,and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should beutilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severepunishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody
foundloitering outside the lab / class without permission during working hours will be
treated seriously andpunished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
Course Objectives:
● To understand OOP principles.
● To understand the Exception Handling mechanism.
● To understand Java collection framework.
● To understand multithreaded programming.
● To understand swing controls in Java.
Course Outcomes:
● Able to write the programs for solving real world problems using Java OOP principles.
● Able to write programs using Exceptional Handling approach.
● Able to write multithreaded applications.
● Able to write GUI programs using swing controls in Java.
List of Experiments:
1. Use Eclipse or Net bean platform and acquaint yourself with the various menus. Create a test project, add a test
class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods, and classes. Try debug step by step with a small program of about 10 to 15 lines
which contains at least one if else condition and a for loop.
2. Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance, Polymorphism and
Abstraction]
3. Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the usage of custom
exceptions in real time scenario.
4. Write a Java program on Random Access File class to perform different read and write operations.
5. Write a Java program to demonstrate the working of different collection classes. [Use package structure to store
multiple classes].
6. Write a program to synchronize the threads acting on the same object. [Consider the example of any reservations
like railway, bus, movie ticket booking, etc.]
7. Write a program to perform CRUD operations on the student table in a database using JDBC.
8. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for
the +, -,*, % operations. Add a text field to display the result. Handle any possible exceptions like divided by zero.
9. Write a Java program that handles all mouse events and shows the event name at the center of the window when a
mouse event is fired. [Use Adapter classes]
REFERENCE BOOKS:
1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson education.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.
4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.
JAVA PROGRAMMING LAB
(R22CSI2228)
EXPERIMENT 1:
Aim:
Use eclipse or Netbean platform and acquaint with the various menus, create a test project, add a test
class and run it see how you can use auto suggestions, auto fill. Try code formatter and code refactoring
like renaming variables, methods and classes. Try debug step by step with a small program of about
10 to 15 lines which contains at least one if else condition and a for loop.
Source Code:
Sample_Program.java
import [Link];
import [Link];
class Sample_Program
{
public static void main(String args[])
{
int i,count=0,n;
Scanner sc=new Scanner([Link]);
[Link]("Enter Any Number : ");
n=[Link]();
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
[Link](n+" is prime");
else
[Link](n+" is not prime");
}
}
Output:
Viva Questions:
2.i) Encapsulation.
Aim:
Source Code:
File Name : [Link]
class Account
{
}
public class Encapsulation
{
public static void main(String[] args)
{
Account acc=new Account();
acc.setAcc_no(7560504000L);
[Link]("Sonoo Jaiswal");
[Link](500000f);
Output:
C:\jdk.19\bin>javac [Link]
C:\jdk.19\bin>java Encapsulation
[Link] : 7560504000
Name : Sonoo Jaiswal
Amount : 500000.0
[Link]) Inheritance
Aim:
Source Code:
File Name : My_Calculation.java
class Calculation
{
int z;
Output :
C:\jdk.19\bin>javac My_Calculation.java
C:\jdk.19\bin>java My_Calculation
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
[Link]) Polymorphism
Aim:
Source Code:
File Name : [Link]
class Polygon
{
public void render()
{
[Link]("Rendering Polygon...");
}
}
Output:
C:\jdk.19\bin>javac [Link]
C:\jdk.19\bin>java Shape
Rendering Polygon...
Rendering Square...
Rendering Circle...
Aim:
Source Code:
File Name : [Link]
class Abstraction
{
public static void main(String args[])
{
Bike obj = new Honda();
[Link]();
[Link]();
}
}
Output:
C:\jdk.19\bin>javac [Link]
C:\jdk.19\bin>java Abstraction
bike is created
running safely..
gear changed
Viva Questions:
1. Why do we need to use OOPs?
2. What is the difference between overloading and overriding?
3. What is compile time polymorphism?
4. List the types of Inheritance with neat diagram.
5. How is encapsulation different from data abstraction.
EXPERIMENT 3:
Aim:
Write a Java program to handle checked and unchecked exceptions. Also, demonstrate the usage of
custom exceptions in real time scenario.
Source Code:
import [Link].*;
class Checked
{
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("[Link]");
}
catch(FileNotFoundException fnfe)
{
[Link]("The specified file is not " +"present at the given path");
}
int k;
try
{
while(( k = [Link]() ) != -1)
{
[Link]((char)k);
}
[Link]();
}
catch(IOException ioe)
{
[Link]("I/O error occurred: "+ioe);
}
}
}
class Unchecked
{
public static void main(String args[])
{
try
{
int arr[] ={1,2,3,4,5};
[Link](arr[7]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("The specified index does not exist ");
}
}
}
Output:
C:\jdk.19\bin>javac [Link]
C:\jdk.19\bin>java Unchecked
The specified index does not exist
Output:
Viva Questions:
Aim :
Write a Java program on Random Access File class to perform different read and write
operations.
Source Code:
The [Link] contains text "This class is used for reading and writing to random access file."
Output:
C:\jdk.19\bin>java [Link]
C:\jdk.19\bin>java Randomfile
welcome to sri ind
Viva Questions:
Aim:
Write a Java program to demonstrate the working of different collection classes. [Use package
structure to store multiple classes].
Source Code:
i). ArrayList
import [Link].*;
class TestJavaCollection1
{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
ii). LinkedList
import [Link].*;
public class TestJavaCollection2
{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
iii). Vector
import [Link].*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
iv). Stack
import [Link].*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Viva Questions:
Aim:
Write a program to synchronize the threads acting on the same object. [Consider the example
of any reservations like railway, bus, movie ticket booking, etc.]
Source Code:
class SeatReservation
{
public static void main(String[] args)
{
Reservation reserve = new Reservation(); // LINE A
Person thread1 = new Person(reserve, 5); // LINE B
[Link]();
Person thread2 = new Person(reserve, 4);
[Link]();
Person thread3 = new Person(reserve, 2);
[Link]();
}
}
class Reservation
{
Reservation reserve;
int requestedSeats;
@Override
public void run() // LINE C
{
[Link](requestedSeats);
}
}
Output:
Thread-0 entered.
Availableseats : 10 Requestedsetas : 5
Seat Available. Reserve now :-)
5 seats reserved.
Thread-0 leaving.
Thread-2 entered.
Availableseats : 5 Requestedsetas : 2
Seat Available. Reserve now :-)
2 seats reserved.
Thread-2 leaving.
Thread-1 entered.
Availableseats : 3 Requestedsetas : 4
Requested seats not available :-(
Thread-1 leaving.
Viva Questions:
1. What is Multithreading?
2. Define Multitasking?
3. Differentiate MultiProcessing & MultiThreading?
4. List thread methods in java.
5. Define thread sleep() and run() methods.
EXPERIMENT 7:
Aim:
Develop a java stand alone application that connects with the database (Oracle / mySql) and perform the
CRUD operation on the database tables.
MySQL Code:
This SQL code creates a table with three columns: s_id for student ID (primary key), s_name for
student name, and s_address for student address.
[Link]
import [Link].*;
import [Link];
String insertQuery = "INSERT INTO student VALUES(" + sid + ",'" + sname + "','" + saddr +
"')";
[Link](insertQuery);
[Link]
import [Link].*;
while ([Link]()) {
[Link]([Link]("s_id") + " \t " + [Link]("s_name") + " \t " +
[Link]("s_address"));
[Link]("________________________________________");
}
}
Output :
[Link]
import [Link].*;
import [Link];
String updateQuery = "UPDATE student SET s_name='" + sname + "', s_address='" + saddr + "'
WHERE s_id=" + sid;
[Link](updateQuery);
Output :
[Link]
import [Link].*;
import [Link];
public class DeleteData {
public static void main(String[] args) {
try (Connection con = [Link]("jdbc:mysql://localhost/mydb", "root", "");
Statements = [Link]()) {
Output :
Viva Questions:
1. Expand CRUD.
2. Define JDBC Driver.
3. Write the syntax for Connecting database.
4. Define Driver Manager.
5. Expand JDBC.
EXPERIMENT 8:
Aim:
Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the , -,*, % operations. Add a text field to display the result. Handle any
possible exceptions like divided by zero.
Source Code:
import [Link].*;
import [Link].*;
import [Link].*;
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
char ch=[Link](0);
if ( [Link](ch)) [Link]([Link]()+str);
else
if([Link]("+"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("-"))
{
v1=[Link]([Link]());
OP='-';
[Link]("");
}
else if([Link]("*"))
{
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("/"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("%"))
{
v1=[Link]([Link]());
OP='%';
[Link]("");
}
if([Link]("="))
{
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}
if([Link]("Clear"))
{
[Link]("");
}
}
}
Output:
Viva Questions:
What is an Applet ?
What is the difference between an Applet and a Java Application ?
Name three Component subclasses that support painting.
What is the relationship between an event-listener interface and an
event-adapterclass ?
How can a GUI component handle its own events ?
EXPERIMENT 9:
Aim:
Write a java program that handles all mouse events and shows the event name at the center of
the window when a mouse event is fired (Use Adapter classes).
Source Code:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout([Link]));
l1 = new JLabel();
Font f = new Font("Verdana", [Link], 20);
[Link](f);
[Link]([Link]);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
[Link]("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
[Link]("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
[Link]("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
[Link]("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output:
.
Viva Questions:
1. Define event.
2. List the event handling methods.
3. Define Key event handling methods.
4. Define Mouse event handling methods.
5. Define Actionlistener.
Additional Programs
Exercise : 1
import [Link].*;
class GFG {
// Function to swap two numbers
// Using temporary variable
static void swapValuesUsingThirdVariable(int m, int n)
{
// Swapping the values
int temp = m;
m = n;
n = temp;
[Link]("Value of m is " + m
+ " and Value of n is " + n);
}
// Main driver code
public static void main(String[] args)
{
// Random integer values
int m = 9, n = 5;
// Calling above function to
// reverse the numbers
swapValuesUsingThirdVariable(m, n);
}
}
Output
Value of m is 5 and Value of n is 9
Exercise : 2
Output
The product is: 3.0
Exercise : 3
Output
Entered Number is Even
Exercise : 4
Exercise : 6
Exercise : 7
Output
Factorial of 5 is 120
Exercise : 8
import [Link].*;
// Java code to demonstrate right star triangle
public class GeeksForGeeks {
// Function to demonstrate printing pattern
public static void StarRightTriangle(int n)
{
int a, b;
// outer loop to handle number of rows
// k in this case
for (a = 0; a < n; a++) {
}
}
// Driver Function
public static void main(String args[])
{
int k = 5;
StarRightTriangle(k);
}
}
Output
*
**
***
****
*****
Exercise : 9
// Java program to convert a decimal
// number to binary number
import [Link].*;
class GFG
{
// function to convert decimal to binary
static void decToBinary(int n)
{
// array to store binary number
int[] binaryNum = new int[1000];
// counter for binary array
int i = 0;
while (n > 0)
{
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
[Link](binaryNum[j]);
}
// driver program
public static void main (String[] args)
{
int n = 17;
[Link]("Decimal - " + n);
[Link]("Binary - ");
decToBinary(n);
}
}
Output
Decimal - 17
Binary - 10001
Exercise : 10
Output
It is a Consonant.
It is a Vowel.