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

Java Lab Manual Aiml

The document is a lab manual for the Java Programming course for II Year CSE (AIML) students at Sri Indu College of Engineering & Technology for the academic year 2023-24. It includes course objectives, outcomes, a list of experiments, and general laboratory instructions. Additionally, it outlines the department's vision and mission, program outcomes, and specific outcomes related to the course.

Uploaded by

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

Java Lab Manual Aiml

The document is a lab manual for the Java Programming course for II Year CSE (AIML) students at Sri Indu College of Engineering & Technology for the academic year 2023-24. It includes course objectives, outcomes, a list of experiments, and general laboratory instructions. Additionally, it outlines the department's vision and mission, program outcomes, and specific outcomes related to the course.

Uploaded by

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

JAVA PROGRAMMING LAB MANUAL

II YEAR CSE (AIML) –Semester II


DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING (AIML)
ACADEMIC YEAR 2023-24
DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING(AIML )

LAB MANUAL

Branch: CSE(AIML) Class: B.Tech- II Year-II sem

Subject: JAVA PROGRAMMING Code:R22CSI2228

Academic Year: 2023-24 Regulation: R22

Core/Elective/H&S: Core Credits: 1.5

Prepared By

Name: G.JYOTHSNA

Verified By

Head of the Department:


DEPARTMENTOF AIML

LAB MANUAL-INDEX

S.No Contents
1 Vision,Mission,PEOs,POs,PSOs&Cos
2 Institution Academic Calendar
3 Department Academic Calendar
4 Syllabus Copy
5 Index
6 Programs
7 Model Paper For LabInternal-1
Model Paper For LabInternal-2
Sri Indu College of Engineering & Technology
Sheriguda(V),R.R.Dist

INSTITUTION VISION

To evolve into a center of excellence in Science and Technology through


creative and innovative practices in teaching & learning, towards promotion of
academic achievement &research excellence to produce globally accepted,
competitive and world class professionals, who are psychologically strong and
emotionally balanced, imbibed with social consciousness and ethical values.

INSTITUTION MISSION

To provide high quality academic programs, training activities, research


facilities and opportunities supported by continuous industry-institute interaction
aim data promoting employability, entrepreneurship, leadership and research
aptitude among students and contribute to the economic and technological
development of the region, state and Nation.

PRINCIPAL
Sri Indu College of Engineering & Technology
Sheriguda(V),R.R.Dist

Department Of Computer Science And Engineering(AIML)

DEPARTMENTVISION

To empower the students to be technologically adopt, innovative, self-motivated


andresponsibleglobalcitizenspossessinghumanvaluesandcontributesignificantlytowardshighquality
withever changing world.

DEPARTMENTMISSION

DM1Toofferhighqualityeducationinthecomputingfieldsbyprovidinganenvironmentwhere the
knowledge is gained and applied to participate in research, for both students andFaculty.

DM2To develop the problem solving skills in the students to be ready to deal with cutting
edgeTechnologiesof theindustry

DM3To make the students and faculty excel in their professional fields by inculcating
theCommunication Of skills, leadership skills, team building skills with the
organizationvariousco-curricularprogrammers

DM4To provide the students with theoretical and applied knowledge, and adopt an
education Approach that promotes lifelong learning and ethical growth.

HOD
Sri Indu College of Engineering& Technology
Sheriguda(V),R.R.Dist

DepartmentofComputerScience&Engineering(AIML&CS)

PROGRAMOUTCOMES(POs)&PROGRAMSPECIFICOUTCOMES (PSOs)

PROGRAMOUTCOMES(POs)

PO Description
EngineeringKnowledge: Tobeable to apply knowledge f computing,mathematics,
PO 1 Science and Engineering appropriatetothe discipline

ProblemAnalysis:To beableidentify,formulate
PO 2 &analyzeaproblem,andascertainanddefinethecomputing requirements appropriatetoits
solution.
Design & Development Solutions: To be able to design, implement, and evaluate
PO 3 acomputer‐basedsystem,process, component,orprogram tomeetdesired needs.
Investigationofcomplexproblems: Tobeabletoidentifyandanalyzeuserneeds
PO 4 andconsiderthem inthe selection, creation,evaluation and administrationof
Computer‐basedsystems forprovidingvalidsolutionstocomplexproblems.
Modern Tool Usage: To possess skills for creating and in using
PO 5 contemporarytechniques,skills, and toolsnecessaryforcomputingpractice.
Engineering&Society:Toapplyconceptualknowledgerelevanttoprofessionalengineeringp
PO 6 racticesinsocietal,health,safety,legalandculturalissuesandtheirconsequences
Environment&Sustainability: To beableto
PO 7 analyzethelocalandglobalimpactofcomputing on individuals, organizations, and
society and work towards sustainable development.
Ethics:Tounderstandcontemporaryprofessional,ethical,legal,securityandsocialissue
PO 8 sand responsibilities.
Individual & Team work: To Be able to function effectively as an individual and
PO 9 onteamsto accomplish a common goal.
Communication: To communicate precisely and effectively both in oral and
PO 10 writtenformwith a rangeof audiences.

Project management & finance: To apply engineering and management principles


PO 11 formanaging and leading economically feasible projects in multi-disciplinary
environmentswithan effectiveprojectplan.
Life Long Learning: To recognize the need for and an ability to engage in
PO 12 independent&lifelong learning forcontinuing professional development.
Program Specific Outcomes
Develop software projects using standard practices and suitable programming
PSO 1 environment.
PSO 2 Identify , formulate and solve the real life problems faced in the society, industry and
other areas by applying the skills of the programming languages, networks and
databases learned.
PSO 3 To apply computer science knowledge in exploring and adopting latest technologies in
different co-curricular activities.
SriInduCollege ofEngineering& Technology
Sheriguda(V),R.R.Dist

DepartmentofComputerScience&Engineering(AIML)

COsand POs & PSOsMapping

SUBName:JAVA PROGRAMMING LAB

SUBCODE: R22CSI2228

Courseout comes (COs):

C22L3.1 Write programs for solving real world programs using collection frame work.
C22L3.2 Write programs using abstract classes and multithreaded programs.
C22L3.3 Able to write GUI programs using swing controls in java.

Faculty
TABLE OF CONTENTS

S.No Topics

1 Dimensions of the Lab

2 Capacity of the lab

3 Equipment

4 Configuration

5 Software

6 Ambience

7 Academic Calendar

8 Syllabus

9 Timetable

10 General laboratory instructions

11 Lab schedule

12 Core lab manual

13 Viva questions

14 Additional programs
1. DIMENSIONS OF THE LAB
Area of the lab in Sqmts : 66 Sqm

2. CAPACITY OF THE LAB : 30 Students


3. EQUIPMENTS

Computer Systems (Clients) : 31


CPU : 31
Monitors : 31
Key Board : 31
Mouse : 31

4. SYSTEM CONFIGURATION : DELL


Speed: 3.10 GHz, 2GB RAM
Hard Disk: 500 GB
HCL LED Monitor Size-18.5
5. SOFTWARE : Turbo C, Linux OS, Windows OS,

Open Office
6. AMBIENCE

Printers : 01
Projector : 00
Computer Tables : 30

Student Chairs : 30
Charts : 02
Photo Frames : 01
Switch/Hub : 03
White Boards : 01
A/C s : 01

Power Backup : UPS


JAVA PROGRAMMING

LAB MANUAL
SYLLABUS

SRI INDU COLLEGE OF ENGINEERING & TECHNOLOGY


(An Autonomous Institution under UGC, New Delhi)
B.Tech. - II Year – II Semester L T P C
0 0 2 1
(R22CSI2228) JAVA PROGRAMMING LAB

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.
GENERAL LABORATORY INSTRUCTION
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who 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, 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 in
the lab.

c. Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted
to 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 be
utilized 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 severe
punishment.

9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished 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.

HOD PRINCIPAL
CORE LAB MANUAL

EXPERIMENT-1

Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, and
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.

Program:

Import java. util.*;

public class Testp {

public static void main(String[] args) {

System.out.println("Welcome to Sri InduEngineering College");

System.out.println("--------Prime Number ");

Scanner sc = new Scanner(System.in);

System.out.println("Enter valid Number");

int n = sc.nextInt();

int c = 0;

for (int i = 1; i <= n; i++)

if (n % i == 0)

c++;

}}

if (c == 2) {

System.out.println(n + "is Prime Number");

} else {

System.out.println(n + "is not Prime Number");

}
}

Output:

VIVA QUESTIONS:

1. What do you mean by Platform Independence?

2. What is JIT Compiler?

3. What all memory areas are allocated by JVM?

4. What is the base class of all classes?

5. What are two different ways to call garbage collector?

6. Use of finalize() method in java?

7. List two java ID Es?

8. What are java buzzwords?

9. Is byte code is similar to .obj file in C?


Experiment-2

2.Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation, Inheritance,
Polymorphism and Abstraction].
PROGRAM
Inheritance, polymorphism, abstraction, encapsulation,over riding, over loading all implemented in
single program.

The file name must be MainClass.java

Program:

Inheritance, polymorphism, abstraction, encapsulation,over riding, over loading all implemented in


single program.

The file name must be MainClass.java

Program:

class One {

public void display() {

System.out.println("One");

//inheritance

class Two extends One {


@Override

public void display() {

System.out.println("Two");

public int add(int x, int y) {

return x+y;

//Overload

public double add(double x,double y) {

return x+y;

//encapsulation example

class EncapTest {

private String name;

public String getName() {

return name;
}

public void setName(String newName) {

name = newName;

//abstraction

abstract class TwoWheeler {

public abstract void run();

class Honda extends TwoWheeler{

public void run(){

System.out.println("\nbike is Running..");

class MainClass {

public static void main(String[] args) {

One a=new One();

a.display();
Two b=new Two();

b.display();

System.out.println(b.add(4,2));

System.out.println(b.add(5.,2.)); //polymorphism

EncapTest encap = new EncapTest();

encap.setName("Sandeep's");

System.out.print("Name : " + encap.getName() );

TwoWheeler test = new Honda();

test.run();

}
Output:

One

Two

7.0
\
Name : Sandeep's
bike is Running.
Experiment-3

3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}

3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {

this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}

Experiment-3

3.Write a Java program to handle checked and unchecked exceptions also demonstrate
the usage of custom exception in real time scenario
// Custom exception class
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to withdraw money, handling InsufficientBalanceException
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
}
// Method to simulate an unchecked exception (ArithmeticException)
public void divideByZero() {
int result = 10 / 0; // This will cause an ArithmeticException
}
}
// Main class to demonstrate exception handling
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Create a bank account with an initial balance
BankAccount account = new BankAccount(1000);
// Handle checked exception (InsufficientBalanceException)
try {
account.withdraw(1500);
} catch (InsufficientBalanceException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
// Handle unchecked exception (ArithmeticException)
try {
account.divideByZero();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}
Output:
1. What are the types of Exceptions in Java?
2. How do you implement user-defined exception handling in Java?
3. What are the dissimilarities between the two types of Java exceptions?
4. What are the different keywords in Exception handling in Java?
5. What is the difference between throws and throw keywords in Java?
6. How to differentiate between the finally, final, and finalize keywords?

Experiment-4
4.Write a Java program on random access file class to perform different read and write
Program:
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "randomAccessFileExample.txt";
// Perform write operations
writeData(filePath, "Hello, World!");
// Perform read operations
readData(filePath);
}
private static void writeData(String filePath, String data) {
try (RandomAccessFile file = new RandomAccessFile(filePath, "rw")) {
// Move the file pointer to the end of the file
file.seek(file.length());
// Write data to the file
file.writeUTF(data);
System.out.println("Data written to file: " + data);
// Move the file pointer to a specific position
file.seek(0);
// Write more data at the beginning of the file
file.writeUTF("New data");
System.out.println("New data written to file.");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readData(String filePath) {
try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
// Read data from the file
String data = file.readUTF();
System.out.println("Read data from file: " + data);
// Move the file pointer to a specific position
file.seek(0);
// Read more data from the beginning of the file
String newData = file.readUTF();
System.out.println("Read new data from file: " + newData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
VIVA QUESTIONS:
1. What is Exception Handling?
2. What is difference between Checked Exception and Unchecked Exception?
3. What is the base class for Error and Exception?
4. What is finally block?
5.Can finally block be used without catch?
6.Is there any case when finally will not be executed?
7.What is exception propagation?
8.What is nested class? 9.What is nested interface?
10.Can an Interface have a class?

Experiment-5

5. write a Java program to demonstrate the working of different collection classes (usage
package structure to store multiple classes
// Create a package named "collectionsdemo"
package collectionsdemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Class to represent a Product
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + '}';
}
}
// Class to demonstrate different collection classes
public class CollectionsDemo {
public static void main(String[] args) {
// Create a list of products
List<Product> productList = new ArrayList<>();
productList.add(new Product("Laptop", 999.99));
productList.add(new Product("Phone", 499.99));
// Create a map of products with unique IDs
Map<Integer, Product> productMap = new HashMap<>();
productMap.put(1, new Product("Tablet", 299.99));
productMap.put(2, new Product("Headphones", 79.99));
// Display products from the list

System.out.println("Products from the list:");


for (Product product : productList) {
System.out.println(product);
}
// Display products from the map
System.out.println("\nProducts from the map:");
for (Map.Entry<Integer, Product> entry : productMap.entrySet()) {
System.out.println("Product ID: " + entry.getKey() + ", Product: " + entry.getValue());
}
}
}

Output:
VIVA QUESTIONS:
1. What is multithreading?
2. What is thread?
3. What is the difference between preemptive scheduling and time slicing?
4. What does join() method?
5. Is it possible to start a thread twice?
6. Can we call the run() method instead of start()?
7. What about the daemon threads?
8. What is shutdown hook?
9. When should we interrupt a thread?

Experiment-6
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)
class MovieTicketBooking {
private int availableSeats;
public MovieTicketBooking(int totalSeats) {
this.availableSeats = totalSeats;
}
// Synchronized method to book tickets
public synchronized void bookTickets(String customerName, int numSeats) {
if (numSeats > 0 && numSeats <= availableSeats) {
System.out.println(customerName + " booked " + numSeats + " tickets.");
availableSeats -= numSeats;
System.out.println("Remaining seats: " + availableSeats);
} else {
System.out.println(customerName + " couldn't book tickets. Not enough seats
available.");
}
}
}
class CustomerThread extends Thread {
private MovieTicketBooking booking;
private String customerName;
private int numSeats;
public CustomerThread(MovieTicketBooking booking, String customerName, int numSeats) {
this.booking = booking;
this.customerName = customerName;
this.numSeats = numSeats;
}
@Override
public void run() {
booking.bookTickets(customerName, numSeats);
}
}
public class MovieTicketBookingDemo {
public static void main(String[] args) {
// Create a MovieTicketBooking object with 10 total seats
MovieTicketBooking ticketBooking = new MovieTicketBooking(10);
// Create multiple threads representing customers trying to book tickets
Thread customer1 = new CustomerThread(ticketBooking, "Customer 1", 3);
Thread customer2 = new CustomerThread(ticketBooking, "Customer 2", 5);
Thread customer3 = new CustomerThread(ticketBooking, "Customer 3", 2);
// Start the threads
customer1.start();
customer2.start();
customer3.start();
}
}
VIVA QUESTIONS: 1. What is a Linked list?
2. Can you represent a Linked list graphically?
3.How many pointers are required to implement a simple Linked list?
4. How many types of Linked lists are there?
5. How to delete a node from linked list?
6.How to reverse a singly linked list?
7. Compare Linked lists and Dynamic Arrays
8. What is a Circular Linked list?

Experiment-7
7.write a Java program to demonstrate the working of different collection classes (usage
package structure to store multiple classes
import java.sql.*;
public class StudentCRUD {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
// JDBC variables for opening, closing, and managing connection
private static Connection connection;
public static void main(String[] args) {
try {
// Open a connection
connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
// Perform CRUD operations
createStudent("John Doe", 20);
readStudents();
updateStudent(1, "Updated Name", 25);
readStudents();
deleteStudent(1);
readStudents();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// Close the connection
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Create operation
private static void createStudent(String name, int age) throws SQLException {
String insertQuery = "INSERT INTO student (name, age) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.executeUpdate();
System.out.println("Student created successfully.");
}
}
// Read operation
private static void readStudents() throws SQLException {
String selectQuery = "SELECT * FROM student";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery)) {
System.out.println("Student Table:");
System.out.println("ID\tName\tAge");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println(id + "\t" + name + "\t" + age);
}
System.out.println();
}
}
// Update operation
private static void updateStudent(int id, String newName, int newAge) throws SQLException {
String updateQuery = "UPDATE student SET name=?, age=? WHERE id=?";

try (PreparedStatement preparedStatement = connection.prepareStatement(updateQuery))


{
preparedStatement.setString(1, newName);
preparedStatement.setInt(2, newAge);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
System.out.println("Student updated successfully.");
}
}
// Delete operation
private static void deleteStudent(int id) throws SQLException {
String deleteQuery = "DELETE FROM student WHERE id=?";
try (PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery))
{
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
System.out.println("Student deleted successfully.");
}
}
}

Output:
EXPERIMENT-8
Write a Java Program that works as simple calculator .Use grid layout to arrange buttons for

thedigits and for the +,-,*,% operations .Add text field to display the results, Handle any

possible exceptions like divide by zero.

AIM : 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.

THEORY: GridLayout is one of the Layout managers.A layout manager automatically arranges your
controls with in a window by using some type of algorithm.Grid Layout lays out component in a two
dimensional grid. When you instantiate a GridLayout,you define the number of rows and columns

Program:

importjavax.swing.*;
importjavax.swing.event.*;
importjava.awt.*;
importjava.awt.event.*;
class A extends JFrame implements ActionListener {
publicJButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
publicJTextField tf1;
publicJPanel p;
public String v = "";
public String v1 = "0";
public String op = "";
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2");
b2.addActionListener(this);
add(b2);
b3 = new JButton("3");
b3.addActionListener(this);
add(b3);
b4 = new JButton("4");
b4.addActionListener(this);
add(b4);
b5 = new JButton("5");
b5.addActionListener(this);
add(b5);
b6 = new JButton("6");
b6.addActionListener(this);
add(b6);
b7 = new JButton("7");
b7.addActionListener(this);
add(b7);
b8 = new JButton("8");
b8.addActionListener(this);
add(b8);
b9 = new JButton("9");
b9.addActionListener(this);
add(b9);
b10 = new JButton("0");
b10.addActionListener(this);
add(b10);
b11 = new JButton("+");
b11.addActionListener(this);
add(b11);
b12 = new JButton("-");
b12.addActionListener(this);
add(b12);
b13 = new JButton("*");
b13.addActionListener(this);
add(b13);
b14 = new JButton("/");
b14.addActionListener(this);
add(b14);
b16 = new JButton("%");
b16.addActionListener(this);
add(b16);
b15 = new JButton("=");
b15.addActionListener(this);
add(b15);
setVisible(true);
}
public void actionPerformed(ActionEventae) {
String b = ae.getActionCommand();
switch (b) {
case "1": {
v = v + "1";
tf1.setText(v);
}
break;
case "2": {
v = v + "2";
tf1.setText(v);
}
break;
case "3": {
v = v + "3";
tf1.setText(v);
}
break;
case "4": {
v = v + "4";
tf1.setText(v);
}
break;
case "5": {
v = v + "5";
tf1.setText(v);
}
break;
case "6": {
v = v + "6";
tf1.setText(v);
}
break;
case "7": {
v = v + "7";
tf1.setText(v);
}
break;
case "8": {
v = v + "8";
tf1.setText(v);
}
break;
case "9": {
v = v + "9";
tf1.setText(v);
}
break;
case "0": {
v = v + "0";
tf1.setText(v);
}
break;
case "+": {
op = "+";
v1 = tf1.getText();
v = "";
}
break;
case "-": {
op = "-";
v1 = tf1.getText();
v = "";
}
break;
case "*": {
op = "*";
v1 = tf1.getText();
v = "";
}
break;
case "/": {
op = "/";
v1 = tf1.getText();
v = "";
}
break;
case "%": {
op = "%";
v1 = tf1.getText();
v = "";
}
break;
case "=": {
switch (op) {
case "+": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) + Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "-": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) - Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "*": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "/": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
case "%": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc {
public static void main(String[] args) {
A a = new A();
}
}
Output:

VIVA QUESTIONS:

1. What is object cloning?

2. When parseInt() method can be used?

3. java.util.regex consists of which classes?

5. Define immutable object?

6. Explain Set Interface?

7. What is function overloading?

8. What is function overriding?

9.What is the difference between yielding and sleeping?

10.What are Wrapper classes?


EXPERIMENT-10
Write a Java Program that handles all mouse events and show event name at the center of the
window when the mouse event is fired.(Use Adapter Classes)

Aim :Write a java program for handling mouse events

Theory:To handle mouse events you must implement the MouseListener and the
MouseMotionListenerinterfaces.These two interfaces contain methods that receive and process the
various types of mouse events.

Program:

importjavax.swing.*;
importjava.awt.*;
importjavax.swing.event.*;
importjava.awt.event.*;
class A extends JFrame implements MouseListener {
JLabel l1;
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m) {
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m) {
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m) {
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m) {
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m) {
l1.setText("Mouse Clicked");
}
}
public class Mevents {
public static void main(String[] args) {
A a = new A();
}
}

Output:

VIVA QUESTIONS

1. MOUSE_CLICKED events occurs when

2. MOUSE_DRAGGED events occurs when

3. events occur when mouse enters a component.

4. events occur when the mouse exists a component

5. MOUSE_MOVED event occurs when

6. MOUSE_PRESSED even occurs when

7. The events occur when mouse was released.

8. The event occurs when mouse wheel is moved.

9. An event source is

10. A is an object that describes the state change in a source


Additional Programs
1. Write a java program to prime number or not.

Program:
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){

System.out.println(n+" is not prime number");


}else{ for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;

break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}

}
}

Output:

3 is prime number

2. Write a java program to print Fibonacci Series without using recursion

Program:
class FibonacciExample1{
public static void main(String args[]) {
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);

for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}

Output:
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34

3. Write a java program to print Factorial Program using loop


Program:
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

Output:

Factorial of 5 is:120

4. Write a java to print Palindrome Program

Program:
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}

Output:

Palindrome number

5. Write a java program to Print ASCII Value

Program:
public class PrintAsciiValueExample1
{
public static void main(String[] args)
{
char ch1 = 'a';
char ch2 = 'b';
int asciivalue1 = ch1;
int asciivalue2 = ch2;
System.out.println("The ASCII value of " + ch1 + " is: " + asciivalue1);
System.out.println("The ASCII value of " + ch2 + " is: " + asciivalue2);
}
}

Output:

The ASCII value of a is: 97


The ASCII value of b is: 98

6. Write a java program to print Right Triangle Star Pattern

Program:
public class RightTrianglePattern
{
public static void main(String args[])
{
int i, j, row=6;
for(i=0; i<row; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}

Output:

7. Write a Java Program to Find Sum of Natural Numbers.

Program:

public class SumOfNaturalNumber1

public static void main(String[] args)

{
int i, num = 10, sum = 0;

for(i = 1; i <= num; ++i)

sum = sum + i;

System.out.println("Sum of First 10 Natural Numbers is = " + sum);

Output:

Sum of First 10 Natural Numbers is = 55

8. Java Program to Display Even Numbers From 1 to 100

Program:

public class DisplayEvenNumbersExample1

public static void main(String args[])

int number=100;

System.out.print("List of even numbers from 1 to "+number+": ");

for (int i=1; i<=number; i++)

if (i%2==0)

System.out.print(i + " ");

}
}

Output:

List of even numbers from 1 to 100: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44


46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

9. Write a java program to print Armstrong Number.

Program:
import java.util.Scanner;
import java.lang.Math;

public class ArmstsrongNumberExample


{
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;

temp=n;
while(temp>0)

{
temp = temp/10;
digits++;
}

temp = n;
while(temp>0)
{
last = temp % 10;

sum += (Math.pow(last, digits));


temp = temp/10;
}
if(n==sum)
return true;

else return false;


}
public static void main(String args[])
{

int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");

for(int i=0; i<=num; i++)


if(isArmstrong(i))
System.out.print(i+ ", ");
}
}

Output:
Enter the limit: 999
Armstrong Number up to 999 are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407

You might also like