0% found this document useful (0 votes)
4 views27 pages

Java Lab Manual Final

The document is a lab manual for Java programming at Vaagdevi College of Engineering, outlining course objectives, experiments, and outcomes for B.Tech students. It includes practical exercises on OOP principles, exception handling, multithreading, GUI programming, and database operations using JDBC. Additionally, it provides reference books and sample code for various Java applications and concepts.

Uploaded by

24641a6683
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)
4 views27 pages

Java Lab Manual Final

The document is a lab manual for Java programming at Vaagdevi College of Engineering, outlining course objectives, experiments, and outcomes for B.Tech students. It includes practical exercises on OOP principles, exception handling, multithreading, GUI programming, and database operations using JDBC. Additionally, it provides reference books and sample code for various Java applications and concepts.

Uploaded by

24641a6683
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

VAAGDEVI COLLEGE OF ENGINEERING

(Autonomous)
Bollikunta, Warangal – 506 005 Telangana State, India

OPERATING SYSTEM LAB MANUAL

JAVA PROGRAMMING

LAB MANUAL

(R22 REGULATION)

OPERATING SYSTEM LAB MANUAL


VAAGDEVI COLLEGE OF ENGINEERING
(AUTONOMOUS)
JAVA PROGRAMMING LAB
[Link]. L T P C

0 0 2 1

CourseObjectives:

● TounderstandOOP principles.
● TounderstandtheExceptionHandlingmechanism.
● TounderstandJavacollectionframework.
● Tounderstandmultithreadedprogramming.
● Tounderstandswingcontrols inJava.

ListofExperiments:
1. Use Eclipse or Net bean platform and acquaintyourself with the various menus. Create
a test project, add a test class, and run it. See how you can useauto suggestions, auto
fill. Try code formatter and code refactoringlikerenaming variables, methods, and
classes. Trydebug step by step with a small programofabout 10to
15lineswhichcontainsat least one ifelseconditionand a for loop.

2. Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation,


Inheritance, Polymorphism and Abstraction]

3. WriteaJavaprogramto handlecheckedanduncheckedexceptions. Also, demonstrate the


usage of custom exceptions in real time scenario.

4. Write a Java program on Random Access Fileclass to perform different read and write
operations.

5. Write a Java programto demonstrate the working ofdifferent collection classes. [Use
packagestructure to store multiple classes].

6. Write a program to synchronize the threads acting on the same object. [Consider the
exampleof anyreservations like railway, bus, movie ticket booking, etc.]

7. WriteaprogramtoperformCRUDoperationsonthestudent tableinadatabaseusingJDBC.

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 ofthe window when a mouse event is fired. [Use Adapter classes].
CourseOutcomes:
CO-1:Ableto writetheprogramsforsolvingrealworldproblemsusingJavaOOPprinciples.

CO-2:AbletowriteprogramsusingExceptionalHandlingapproach.

CO-3:Abletowritemultithreadedapplications.

CO-4:AbletowriteGUIprogramsusingswingcontrolsinJava.

REFERENCEBOOKS:
1. JavaforProgrammers,[Link], 10thEditionPearsoneducation.
2. ThinkinginJava,BruceEckel, PearsonEducation.
3. JavaProgramming,[Link],CengageLearning.
4. CoreJava,Volume1,9thedition,[Link],Pearson.
Week-1. 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.
Trycode formatter and code refactoring like renaming variables, methods and classes. Try
debug step by step with a smallprogram of about 10 to 15lines which contains at leastone if
else condition and a for loop.

[Link] a java program to find the even and odd numbers for a given range of number.

public class ForLoopDemo


{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) // Iterating through numbers 1 to 10
{
if (i % 2 == 0) // Checking if the number is even or odd
{
[Link](i + " is even");
}
else
{
[Link](i + " is odd");
}
}
}
}

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Week-2:

write a java program to demonstrate the OOP principles (i.e., encapsulation, inheritance,
polymorphism and abstraction).

// Encapsulation: Using access modifiers to encapsulate data within classes


class Person {
private String name;
private int age;

public Person(String name, int age) {


[Link] = name;
[Link] = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}

// Inheritance: Subclass inheriting from a superclass


class Student extends Person {
private int studentId;

public Student(String name, int age, int studentId) {


super(name, age);
[Link] = studentId;
}

public int getStudentId() {


return studentId;
}
}

// Polymorphism: Using a common interface to refer to different objects


interface Movable {
void move();
}

class Car implements Movable {


@Override
public void move() {
[Link]("Car is moving");
}
}

class Bicycle implements Movable {


@Override
public void move() {
[Link]("Bicycle is moving");
}
}

// Abstraction: Hiding implementation details and showing only essential features


abstract class Shape {
abstract double calculateArea();
}

class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


[Link] = width;
[Link] = height;
}

@Override
double calculateArea() {
return width * height;
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
public class OOPDemo {
public static void main(String[] args) {
// Encapsulation
Person person = new Person("John", 25);
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());

// Inheritance
Student student = new Student("Alice", 20, 12345);
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
[Link]("Student ID: " + [Link]());

// Polymorphism
Movable car = new Car();
Movable bicycle = new Bicycle();
[Link]();
[Link]();

// Abstraction
Shape rectangle = new Rectangle(5, 4);
Shape circle = new Circle(3);
[Link]("Area of Rectangle: " + [Link]());
[Link]("Area of Circle: " + [Link]());
}
}

output :
Name: John
Age: 25
Name: Alice
Age: 20
Student ID: 12345
Car is moving
Bicycle is moving
Area of Rectangle: 20.0
Area of Circle: 28.274333882308138
Week-3:
write a java program to handle checked and unchecked exceptions. Also, demonstrate the usage
of custom exceptions in real time scenario.

// Custom checked exception


class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

// Custom unchecked exception


class InvalidInputException extends RuntimeException {
public InvalidInputException(String message) {
super(message);
}
}

// Bank account class with withdrawal method


class BankAccount {
private double balance;

public BankAccount(double balance) {


[Link] = balance;
}
// Withdraw method that throws a checked exception for insufficient funds
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds to withdraw");
}
balance -= amount;
[Link]("Withdrawal successful. Remaining balance: " + balance);
}
}

public class ExceptionDemo {


// Method that throws a unchecked exception for invalid input
public static void validateInput(int age) {
if (age < 0) {
throw new InvalidInputException("Age cannot be negative");
}
[Link]("Valid age: " + age);
}

public static void main(String[] args) {


// Handling checked exception
try {
BankAccount account = new BankAccount(1000);
[Link](1500);
} catch (InsufficientFundsException e) {
[Link]("Exception caught: " + [Link]());
}

// Handling unchecked exception


try {
validateInput(-5);
} catch (InvalidInputException e) {
[Link]("Unchecked exception caught: " + [Link]());
}
// Demonstrating custom exception in a real-time scenario
try {
processOrder(5); // Assume we have only 3 items in stock
} catch (OutOfStockException e) {
[Link]("Custom exception caught: " + [Link]());
}
}

// Real-time scenario: Custom exception for out of stock items


public static void processOrder(int itemsOrdered) throws OutOfStockException {
int availableItems = 3; // Assume we have only 3 items in stock
if (itemsOrdered > availableItems) {
throw new OutOfStockException("Out of stock! Only " + availableItems + " items
available.");
}
[Link]("Order processed successfully for " + itemsOrdered + " items.");
}
}

// Custom checked exception for out of stock items


class OutOfStockException extends Exception {
public OutOfStockException(String message) {
super(message);
}
}
.output :
Exception caught: Insufficient funds to withdraw
Unchecked exception caught: Age cannot be negative
Custom exception caught: Out of stock! Only 3 items available.
Week-4:

Write a java program on random access file class to perform different read and write operations.

import [Link];
import [Link];

public class RandomAccessFileDemo {


public static void main(String[] args) {
String fileName = "[Link]";

// Writing data to the file


writeDataToFile(fileName);

// Reading data from the file


readDataFromFile(fileName);

// Modifying data in the file


modifyDataInFile(fileName);
}

// Method to write data to the file


public static void writeDataToFile(String fileName) {
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");

// Writing data to the file


[Link]("Hello, World!"); // Writing a UTF string
[Link](123); // Writing an integer
[Link](3.14); // Writing a double
[Link]();
} catch (Exception e) {
[Link]("Error writing to file: " + [Link]());
}
}

// Method to read data from the file


public static void readDataFromFile(String fileName) {
try {
RandomAccessFile file = new RandomAccessFile(fileName, "r");

// Reading data from the file


String str = [Link](); // Reading a UTF string
int intValue = [Link](); // Reading an integer
double doubleValue = [Link](); // Reading a double

// Displaying the read data


[Link]("String read from file: " + str);
[Link]("Integer read from file: " + intValue);
[Link]("Double read from file: " + doubleValue);

[Link]();
} catch (Exception e) {
[Link]("Error reading from file: " + [Link]());
}
}

// Method to modify data in the file


public static void modifyDataInFile(String fileName) {
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
// Moving the file pointer to the beginning of the integer value
[Link](8); // UTF string (2 bytes) + Integer (4 bytes) = 6 bytes, so seek to 6th byte

// Modifying the integer value


[Link](456);

[Link]();

// Reading modified data to verify


readDataFromFile(fileName);
} catch (Exception e) {
[Link]("Error modifying data in file: " + [Link]());
}
}
}
output :
String read from file: Hello, World!
Integer read from file: 123
Double read from file: 3.14
Error reading from file: malformed input around byte 11
Week-5:
Write a Java program to demonstrate the working of different collection classes. [Use
packagestructure to store multiple classes].

import [Link];
import [Link];
import [Link];
import [Link];

public class CollectionDemo {


public static void main(String[] args) {
// ArrayList demonstration
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("ArrayList: " + arrayList);

// LinkedList demonstration
LinkedList<Integer> linkedList = new LinkedList<>();
[Link](10);
[Link](20);
[Link](30);
[Link]("LinkedList: " + linkedList);

// HashSet demonstration
HashSet<String> hashSet = new HashSet<>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("HashSet: " + hashSet);

// HashMap demonstration
HashMap<Integer, String> hashMap = new HashMap<>();
[Link](1, "One");
[Link](2, "Two");
[Link](3, "Three");
[Link]("HashMap: " + hashMap);
} }

Output:

ArrayList: [Apple, Banana, Orange]


LinkedList: [10, 20, 30]
HashSet: [Green, Blue, Red]
HashMap: {1=One, 2=Two, 3=Three}
Week-6:
Write a program to synchronize the threads acting on the same object. [Consider the exampleof
any reservations like railway, bus, movie ticket booking, etc.]

class RailwayReservation {
private int availableSeats;

public RailwayReservation(int totalSeats) {


[Link] = totalSeats;
}

public synchronized void bookSeat(int seatsToBook, String passengerName) {


if (seatsToBook > availableSeats) {
[Link]("Sorry, not enough seats available for " + passengerName);
return;
}

[Link](seatsToBook + " seat(s) booked for " + passengerName);


availableSeats -= seatsToBook;
}
}

class ReservationThread extends Thread {


private RailwayReservation reservation;
private int seatsToBook;
private String passengerName;

public ReservationThread(RailwayReservation reservation, int seatsToBook, String


passengerName) {
[Link] = reservation;
[Link] = seatsToBook;
[Link] = passengerName;
}

public void run() {


[Link](seatsToBook, passengerName);
}
}

public class Main {


public static void main(String[] args) {
RailwayReservation reservation = new RailwayReservation(50);

ReservationThread thread1 = new ReservationThread(reservation, 3, "Alice");


ReservationThread thread2 = new ReservationThread(reservation, 5, "Bob");
ReservationThread thread3 = new ReservationThread(reservation, 4, "Charlie");
[Link]();
[Link]();
[Link]();
}
}

Output:

3 seat(s) booked for Alice


5 seat(s) booked for Bob
4 seat(s) booked for Charlie
Week-7) .Write a java program that connects to a database using JDBC and does add,
deletes, modify and retrieve operations?
Program:-

import [Link].*;

public class DatabaseOperations {

// JDBC URL, username, and password of MySQL server


private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";

public static void main(String[] args) {


try {
// Connect to MySQL database
Connection connection = [Link](JDBC_URL, USERNAME,
PASSWORD);

// Add operation
addStudent(connection, "Alice", 22);

// Retrieve operation
[Link]("Retrieving students:");
retrieveStudents(connection);

// Modify operation
updateStudent(connection, 1, "Bob", 25);

// Retrieve again to see changes


[Link]("Retrieving students after modification:");
retrieveStudents(connection);

// Delete operation
deleteStudent(connection, 1);

// Retrieve again to see changes


[Link]("Retrieving students after deletion:");
retrieveStudents(connection);

// Close the connection


[Link]();
} catch (SQLException e) {
[Link]();
}
}

// Method to add a student to the database


private static void addStudent(Connection connection, String name, int age) throws
SQLException {
PreparedStatement statement = [Link]("INSERT INTO students
(name, age) VALUES (?, ?)");
[Link](1, name);
[Link](2, age);
[Link]();
[Link]("Student added successfully");
}

// Method to retrieve students from the database


private static void retrieveStudents(Connection connection) throws SQLException {
Statement statement = [Link]();
ResultSet resultSet = [Link]("SELECT * FROM students");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
}

// Method to update a student in the database


private static void updateStudent(Connection connection, int id, String name, int age) throws
SQLException {
PreparedStatement statement = [Link]("UPDATE students SET
name=?, age=? WHERE id=?");
[Link](1, name);
[Link](2, age);
[Link](3, id);
int rowsUpdated = [Link]();
if (rowsUpdated > 0) {
[Link]("Student updated successfully");
} else {
[Link]("Student with ID " + id + " not found");
}
}

// Method to delete a student from the database


private static void deleteStudent(Connection connection, int id) throws SQLException {
PreparedStatement statement = [Link]("DELETE FROM students
WHERE id=?");
[Link](1, id);
int rowsDeleted = [Link]();
if (rowsDeleted > 0) {
[Link]("Student deleted successfully");
} else {
[Link]("Student with ID " + id + " not found");
}
}
}

Output:

Student added successfully


Retrieving students:
ID: 1, Name: Alice, Age: 22
Student updated successfully
Retrieving students after modification:
ID: 1, Name: Bob, Age: 25
Student deleted successfully
Week-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 divide by zero.
Program:-

import
[Link].*;
import [Link].*;
import
[Link].*;
//<appletcode=Calculatorheight=300width=200></applet
> public class Calculator extends JApplet
{
publicvoidinit()
{

CalculatorPanel calc=new CalculatorPanel();


getContentPane().add(calc);
}

classCalculatorPanelextendsJPanelimplementsActionListener
{

JButtonn1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,eq
ual; static JTextField result=new JTextField("0",45);
static String
lastCommand=null;
JOptionPane p=new
JOptionPane(); double
preRes=0,secVal=0,res; private
static void assign(String no)
{

if(([Link]()).equals("0"
)) [Link](no);
elseif(lastCommand=="=")
{

[Link](no);
lastCommand=null;
}

else
[Link]([Link]()+no);
}

publicCalculatorPanel()
{

setLayout(new
BorderLayout());
[Link](false);

[Link](300,200);
add(result,[Link]);
JPanel panel=new JPanel();
[Link](new
GridLayout(4,4));
n7=new JButton("7");
[Link](n7);
[Link](this);
n8=new JButton("8");
[Link](n8);
[Link](this);
n9=new JButton("9");
[Link](n9);
[Link](this);
div=new JButton("/");
[Link](div);
[Link](this);
n4=new JButton("4");
[Link](n4);
[Link](this);
n5=new JButton("5");
[Link](n5);
[Link](this);
n6=new JButton("6");
[Link](n6);
[Link](this);
mul=new JButton("*");
[Link](mul);
[Link](this);
n1=new JButton("1");
[Link](n1);
[Link](this);
n2=new JButton("2");
[Link](n2);
[Link](this);
n3=new
JButton("3");[Link](n3);
[Link](this);
minus=new JButton("-");
[Link](minus);
[Link](this);
dot=new
JButton(".");[Link](dot);
[Link](this);n0=
new
JButton("0");[Link](n0);
[Link](this);
equal=new JButton("=");
[Link](equal);
[Link](this);
plus=new JButton("+");
[Link](plus);
[Link](this);
add(panel,[Link]
ER);
}
publicvoidactionPerformed(ActionEventae)
{
if([Link]()==n1)assign("1");
else if([Link]()==n2)
assign("2"); else
if([Link]()==n3) assign("3");
else if([Link]()==n4)
assign("4"); else
if([Link]()==n5) assign("5");
else if([Link]()==n6)
assign("6"); else
if([Link]()==n7) assign("7");
else if([Link]()==n8)
assign("8"); else
if([Link]()==n9) assign("9");
else if([Link]()==n0)
assign("0"); else
if([Link]()==dot)
{
if((([Link]()).indexOf("."))==-1)
[Link]([Link]()+".");
}

elseif([Link]()==minus)
{

preRes=[Link]([Link]
t()); lastCommand="-";
[Link]("0");
}

elseif([Link]()==div)
{

preRes=[Link]([Link]());
lastCommand="/";
[Link]("0");
}

elseif([Link]()==equal)
{

secVal=[Link]([Link]());
if([Link]("/"))
res=preRes/secVal;
else if([Link]("*"))
res=preRes*secVal;
else
if([Link]("-
")) res=preRes-secVal;
else if([Link]("+"))
res=preRes+secVal;
[Link](""+res);
lastCommand="=";
}

elseif([Link]()==mul)
{

preRes=[Link]([Link]());
lastCommand="*";
[Link]("0");
}

elseif([Link]()==plus)
{
preRes=[Link]([Link]());
lastCommand="+";
[Link]("0");
}

Output:-
Week-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).
Program:-

import [Link].*;

import [Link].*;

import [Link].*;
/*<appletcode="MouseDemo"width=300height=300>

</applet>*/

public class MouseDemo extends Applet implements MouseListener,MouseMotionListener

intmx=0;

intmy=0;String msg="";

public void init()

addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEventme)

mx=20; my=40;
msg="Mouse
Clicked"; repaint();
}

public void mousePressed(MouseEventme)


{

mx=30; my=60;
msg="MousePressed";
repaint();

public void mouseReleased(MouseEventme)

mx=30; my=60;
msg="Mouse Released";
repaint();
}

public void mouseEntered(MouseEventme)

mx=40; my=80;
msg="Mouse
Entered"; repaint();
}

public void mouseExited(MouseEventme)

mx=40; my=80;

msg="Mouse
Exited"; repaint();
}

public void mouseDragged(MouseEventme)

mx=[Link]();
my=[Link]();

showStatus("Currentlymousedragged"+mx+""+my);
repaint();}

public void mouseMoved(MouseEventme)


{

mx=[Link]();

my=[Link]();

showStatus("Currently mouse is at"+mx+""+my);


repaint();
}

public void paint(Graphicsg)


{

[Link]("Handling Mouse Events",30,20);


[Link](msg,60,40);
}

Output:

You might also like