0% found this document useful (0 votes)
2 views30 pages

Java Lab Manual

The document outlines various Java programming lab exercises, including creating a prime number checker, demonstrating OOP principles, handling exceptions, performing file operations, and managing collections. It also covers thread synchronization in a ticket booking system and CRUD operations using JDBC for a student database. Additionally, it includes a simple calculator implementation using a graphical user interface.

Uploaded by

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

Java Lab Manual

The document outlines various Java programming lab exercises, including creating a prime number checker, demonstrating OOP principles, handling exceptions, performing file operations, and managing collections. It also covers thread synchronization in a ticket booking system and CRUD operations using JDBC for a student database. Additionally, it includes a simple calculator implementation using a graphical user interface.

Uploaded by

siasia26262626
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming [ Lab Programs ]

1. Aim:Use eclipse or Net bean 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:

/* java program to check given number is prime or not */


//Importing packages
import [Link];
import [Link];
// Creating Class
class Sample_Program {
// main method
public static void main(String args[])
{
int i,count=0,n;
// creating scanner object
Scanner sc=new Scanner([Link]);
// get input number from user
[Link]("Enter Any Number : ");
n=[Link]();
// logic to check prime or not
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:
2. Aim:Write a Java program to demonstrate the OOP principles. [i.e., Encapsulation,
Inheritance, Polymorphism and Abstraction]

Source Code:[Link]

/* Encapsulation:
The fields of the class are private and accessed through getter and setter methods.*/
class Person {
// private fields
private String name;
private int age;
// constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
/* Abstraction:
The displayInfo() method provides a simple interface to interact with the object.*/
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

/* Inheritance:
Employee is a subclass of Person, inheriting its properties and methods.*/
class Employee extends Person {
// private field
private double salary;
// constructor
public Employee(String name, int age, double salary) {
super(name, age);
[Link] = salary;
}
// getter and setter methods
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
[Link] = salary;
}

/* Polymorphism:
Overriding the displayInfo() method to provide a specific implementation for Employee.*/
@Override
public void displayInfo() {
[Link]();
[Link]("Salary: " + salary);
}
}

public class OopPrinciplesDemo {


public static void main(String[] args) {
// Demonstrating encapsulation and abstraction
Person person = new Person("Madhu", 30);
[Link]("Person Info:");
[Link]();
[Link]("====================");

// Demonstrating inheritance and polymorphism


Employee employee = new Employee("Naveen", 26, 50000);
[Link]("Employee Info:");
[Link]();
}
}

Output:
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:[Link]

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

// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class ExceptionsDemo {


// Method to demonstrate custom exception
public static void register(String name, int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("User must be at least 18 years old.");
} else {
[Link]("Registration successful for user: " + name);
}
}
public static void main(String[] args) {
//Handling Checked Exception
try {
File file = new File("[Link]");
// This line can throw FileNotFoundException
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}
//Handling Unchecked Exception
try {
int[] arr = {1, 2, 3};
// Accessing an out-of-bound index
[Link](arr[6]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " + [Link]());
}
// Finally block to perform cleanup operations
finally {
[Link]("Cleanup operations can be performed here.");
}
// Demonstrate custom exception handling
[Link]("Demonstrating Custom Exception:");
try {
// Invalid age for registration
register("Madhu", 17);
} catch (InvalidAgeException e) {
[Link]("Custom Exception Caught: " + [Link]());
}
}
}

Output:
4. Aim:Write a Java program on Random Access File class to perform different read and
write operations.

Source Code:[Link]

import [Link].*;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
// Create a RandomAccessFile object with read-write mode
RandomAccessFile file = new RandomAccessFile("[Link]", "rw");
// Write data to the file
String data1 = "Hello";
String data2 = "World";
[Link](data1);
[Link](data2);
// Move the file pointer to the beginning of the file
[Link](0);
// Read data from the file
String readData1 = [Link]();
String readData2 = [Link]();
[Link]("Data read from file:");
[Link](readData1);
[Link](readData2);
// Move the file pointer to the ending of the file
[Link]([Link]());
// Append new data to the file
String newData = "Java!";
[Link](newData);
// Move the file pointer to the beginning of the file
[Link](0);
// Read data from the file again after appending
readData1 = [Link]();
readData2 = [Link]();
String readData3 = [Link]();
[Link]("Data read from file after appending:");
[Link](readData1);
[Link](readData2);
[Link](readData3);
// Close the file
[Link]();
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
[Link]();
}
}
}

Output:
5. Aim:Write a Java program to demonstrate the working of different collection classes.
[Use package structure to store multiple classes].

Source Code:[Link]

package collections;
import [Link];
public class ListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
// to display
[Link]("List Example:");
for (String fruit : list) {
[Link](fruit);
}
}
}

[Link]

package collections;
import [Link];
public class SetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple"); // This won't be added since sets don't allow duplicates
// To display
[Link]("Set Example:");
for (String fruit : set) {
[Link](fruit);
}
}
}

[Link]

package collections;
import [Link];
public class MapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Orange");
// To display
[Link]("Map Example:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}
}
}

[Link]

package collections;

public class CollectionsDemo {


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

Output:
6. 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 MovieTicketBooking {

int totalSeats = 10;

// Synchronized method to book tickets

public synchronized void bookTickets(String name, int numberOfSeats) {

if (numberOfSeats <= totalSeats) {

[Link](name + " successfully booked " + numberOfSeats + " seat(s).");

totalSeats -= numberOfSeats;

[Link]("Seats remaining: " + totalSeats);

} else {

[Link]("Sorry " + name + ", only " + totalSeats + " seat(s) available.");

}
// User class that tries to book tickets

class User extends Thread {

MovieTicketBooking booking;

String name;

int seatsToBook;

public User(MovieTicketBooking booking, String name, int seatsToBook) {

[Link] = booking;

[Link] = name;

[Link] = seatsToBook;

public void run() {

[Link](name, seatsToBook);

// Main class
public class TicketBookingApp {

public static void main(String[] args) {

MovieTicketBooking bookingSystem = new MovieTicketBooking();

// Creating user threads

User user1 = new User(bookingSystem, "Alice", 4);

User user2 = new User(bookingSystem, "Bob", 5);

User user3 = new User(bookingSystem, "Charlie", 3);

// Starting threads

[Link]();

[Link]();

[Link]();

Output:

Alice successfully booked 4 seat(s).

Seats remaining: 6
Bob successfully booked 5 seat(s).

Seats remaining: 1

Sorry Charlie, only 1 seat(s) available.

7. Aim:Write a program to perform CRUD operations on the student table in a database


using JDBC.

Source Code:[Link]

import [Link].*;
import [Link];
public class InsertData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost/mydb", "root",
"");
Statement s = [Link]();

// To read insert data into student table


Scanner sc = new Scanner([Link]);
[Link]("Inserting Data into student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute insert query
[Link]("insert into student values("+sid+",'"+sname+"','"+saddr+"')");
[Link]("Data inserted successfully into student table");

[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}

[Link]

import [Link].*;
import [Link];
public class UpdateData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost/mydb", "root",
"");
Statement s = [Link]();

// To read insert data into student table


Scanner sc = new Scanner([Link]);
[Link]("Update Data in student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
[Link]("Enter student name : ");
String sname = [Link]();
[Link]("Enter student address : ");
String saddr = [Link]();
// to execute update query
[Link]("update student set s_name='"+sname+"',s_address = '"+saddr+"' where s_id =
"+sid);
[Link]("Data updated successfully");
[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}

[Link]

import [Link].*;
import [Link];
public class DeleteData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost/mydb", "root",
"");
Statement s = [Link]();

// To read insert data into student table


Scanner sc = new Scanner([Link]);
[Link]("Delete Data from student table : ");
[Link]("________________________________________");
[Link]("Enter student id : ");
int sid = [Link]();
// to execute delete query
[Link]("delete from student where s_id = "+sid);
[Link]("Data deleted successfully");
[Link]();
[Link]();
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}
}
}

[Link]

import [Link].*;
import [Link];
public class DisplayData {
public static void main(String[] args) {
try {
// to create connection with database
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost/mydb", "root",
"");
Statement s = [Link]();

// To display the data from the student table


ResultSet rs = [Link]("select * from student");
if (rs != null) {
[Link]("SID \t STU_NAME \t ADDRESS");
[Link]("________________________________________");
while ([Link]())
{
[Link]([Link](1) +" \t "+ [Link](2)+ " \t "+[Link](3));
[Link]("________________________________________");
}
[Link]();
[Link]();
}
} catch (SQLException err) {
[Link]("ERROR: " + err);
} catch (Exception err) {
[Link]("ERROR: " + err);
}

}
}

Output:
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:[Link]

/* Program to create a Simple Calculator */


import [Link].*;
import [Link].*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
[Link](50,100,100,30);

tf1=new TextField();
[Link](160,100,100,30);

lbl2=new Label("Number 2: ");


[Link](50,170,100,30);

tf2=new TextField();
[Link](160,170,100,30);

btn1=new Button("+");
[Link](50,250,40,40);
btn2=new Button("-");
[Link](120,250,40,40);

btn3=new Button("*");
[Link](190,250,40,40);

btn4=new Button("/");
[Link](260,250,40,40);

lbl3=new Label("Result : ");


[Link](50,320,100,30);

tf3=new TextField();
[Link](160,320,100,30);

[Link](this);
[Link](this);
[Link](this);
[Link](this);

add(lbl1); add(lbl2); add(lbl3);


add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);

setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
num1 = [Link]([Link]());
num2 = [Link]([Link]());

if([Link]() == btn1)
{
result = num1 + num2;
[Link]([Link](result));
}
if([Link]() == btn2)
{
result = num1 - num2;
[Link]([Link](result));
}
if([Link]() == btn3)
{
result = num1 * num2;
[Link]([Link](result));
}
if([Link]() == btn4)
{
result = num1 / num2;
[Link]([Link](result));
}
}

public static void main(String args[]) {


MyCalculator calc=new MyCalculator();
}
}
Output:

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:[Link]
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:

You might also like