[Go to site: main page, start]

0% found this document useful (0 votes)
10 views33 pages

Java OOP, Exceptions, Collections, Threads

The document consists of multiple Java programs demonstrating various concepts such as OOP principles, exception handling, file operations, collections, thread synchronization, and CRUD operations with JDBC. Each week outlines a specific aim and provides source code for the respective Java program. Additionally, it includes a simple calculator program using a graphical user interface.

Uploaded by

clgwrk12
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)
10 views33 pages

Java OOP, Exceptions, Collections, Threads

The document consists of multiple Java programs demonstrating various concepts such as OOP principles, exception handling, file operations, collections, thread synchronization, and CRUD operations with JDBC. Each week outlines a specific aim and provides source code for the respective Java program. Additionally, it includes a simple calculator program using a graphical user interface.

Uploaded by

clgwrk12
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

WEEK 1

WEEK 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]();

}
WEEK 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:
WEEK 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]();

}
}WEEK 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:
WEEK 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 representing the ticket booking system

class TicketBookingSystem {

private int availableSeats; // Variable to keep track of available seats

// Constructor to initialize available seats

public TicketBookingSystem(int availableSeats) {

[Link] = availableSeats;

// Method to book tickets, synchronized to ensure thread safety

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

// Check if requested seats are available

if (availableSeats >= requestedSeats) {

// If available, book the tickets

[Link](requestedSeats + " tickets booked successfully for " + name);

availableSeats -= requestedSeats; // Update available seats

} else {

// If not available, notify user

[Link]("Sorry, " + requestedSeats + " tickets not available for " + name);
} }

// Class representing a customer/thread trying to book tickets

class Customer extends Thread {

private TicketBookingSystem bookingSystem;

private int requestedSeats; // Number of seats requested by the customer

private String name; // Name of the customer

// Constructor to initialize customer details

public Customer(TicketBookingSystem bookingSystem, int requestedSeats, String name) {

[Link] = bookingSystem;

[Link] = requestedSeats;

[Link] = name;

// Method to execute when the thread starts

public void run() {

// Attempt to book tickets

[Link](requestedSeats, name);

// Main class

public class Main {


public static void main(String[] args) {

TicketBookingSystem bookingSystem = new TicketBookingSystem(10); // Create ticket


booking system with 10 available seats

// Create multiple threads (customers) trying to book tickets

Customer customer1 = new Customer(bookingSystem, 3, "Alice");

Customer customer2 = new Customer(bookingSystem, 4, "Bob");

Customer customer3 = new Customer(bookingSystem, 2, "Charlie");

Customer customer4 = new Customer(bookingSystem, 5, "David");

// Start the threads

[Link]();

[Link]();

[Link]();

[Link]();

}
WEEK 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:
Week 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].*;

import [Link].*;

import [Link].*;

/*

<applet code="MyCalculator" width=300 height=300>

</applet>

*/

public class MyCalculator extends Applet implements ActionListener {

int num1,num2,result;

TextField T1;

Button NumButtons[]=new Button[10];

Button Add,Sub,Mul,Div,clear,EQ;

char Operation;

Panel nPanel,CPanel,SPanel;

public void init() {


nPanel=new Panel();

T1=new TextField(30);

[Link](new FlowLayout([Link]));

[Link](T1);

CPanel=new Panel();

[Link]([Link]);

[Link](new GridLayout(5,5,3,3));

for(int i=0;i<10;i++) {

NumButtons[i]=new Button(""+i);

Add=new Button("+");

Sub=new Button("-");

Mul=new Button("*");

Div=new Button("/");

clear=new Button("clear");

EQ=new Button("=");

[Link](this);

for(int i=0;i<10;i++) {

[Link](NumButtons[i]);

[Link](Add);

[Link](Sub);

[Link](Mul);

[Link](Div);

[Link](EQ);
SPanel=new Panel();

[Link](new FlowLayout([Link]));

[Link]([Link]);

[Link](clear);

for(int i=0;i<10;i++) {

NumButtons[i].addActionListener(this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](new BorderLayout());

add(nPanel,[Link]);

add(CPanel,[Link]);

add(SPanel,[Link]);

public void actionPerformed(ActionEvent ae) {

String str=[Link] ();

char ch=[Link](0);

if([Link](ch))

[Link]([Link]()+str);

else

if([Link]("+")){
num1=[Link] ([Link]());

Operation='+';

[Link] ("");

if([Link]("-")){

num1=[Link]([Link]());

Operation='-';

[Link]("");

if([Link]("*")){

num1=[Link]([Link]());

Operation='*';

[Link]("");

if([Link]("/")){

num1=[Link]([Link]());

Operation='/';

[Link]("");

if([Link]("%")){

num1=[Link]([Link]());

Operation='%';

[Link]("");

if([Link]("=")) {
num2=[Link]([Link]());

switch(Operation)

case '+':result=num1+num2;

break;

case '-':result=num1-num2;

break;

case '*':result=num1*num2;

break;

case '/':try {

result=num1/num2;

catch(ArithmeticException e) {

result=num2;

[Link](this,"Divided by zero");

break;

[Link](""+result);

if([Link]("clear")) {

[Link]("");

}
WEEK 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();


}

Common questions

Powered by AI

The MouseEventPerformer class extends JFrame and implements MouseListener to handle mouse events without adapter classes. Instead of using a MouseAdapter, it defines all abstract methods of MouseListener directly, which could be made more efficient by an abstract class, but captures each event distinctly and updates a JLabel accordingly to show dynamic feedback .

The RandomAccessFileExample.java file creates a RandomAccessFile object in read-write mode, writing data to the file using 'writeUTF()'. It moves the file pointer using 'seek()' to read from the beginning and after appending new data. Reading from and writing to specific file pointers demonstrates non-sequential file handling capabilities .

GridLayout is used in MyCalculator.java to arrange button components in a matrix-like format, ensuring a neat, evenly distributed button layout. Each button occupies a grid cell, facilitating intuitive placement and easy alignment without manual pixel adjustments .

The program handles checked exceptions using a try-catch block for FileNotFoundException when attempting to open a file. Unchecked exceptions, such as ArrayIndexOutOfBoundsException, are also caught using a try-catch block when accessing an invalid array index. Additionally, a custom exception, InvalidAgeException, is thrown and caught to handle specific invalid conditions like age restrictions .

In MyCalculator.java, division operations are wrapped in a try-catch block to catch ArithmeticException. When a division by zero occurs, the exception is caught, and the error is indicated via a JOptionPane, while the calculator operation is aborted, preventing the program from crashing .

Using HashSet in SetExample.java ensures all elements in the collection are unique by automatically discarding duplicate entries at the point of addition. This behavior is especially crucial in situations requiring data integrity and uniqueness, like maintaining a list of distinct user IDs or using it to prevent data duplication errors. Such constraints can affect both performance and memory usage if incorrectly handled .

Polymorphism enables the class 'Employee', which extends 'Person', to override the 'displayInfo()' method from the superclass. This allows 'Employee' to provide a specific implementation that includes displaying salary information in addition to name and age, thus altering behavior based on the object's actual type at runtime .

The InsertData.java file connects to a MySQL database using JDBC by loading the JDBC driver and creating a Connection object. It uses a Statement object to execute an SQL 'INSERT' query, which adds data to the student table. User input is read using a Scanner object, allowing dynamic specification of data fields .

The Java class structure demonstrates Encapsulation by making the fields of the class 'Person' private and providing public getter and setter methods to access these fields. This restricts direct access to the fields, allowing controlled access and modification through methods .

The synchronized keyword in the ticket booking system prevents concurrent threads from executing the 'bookTickets' method simultaneously. This ensures that updates to the shared resource (availableSeats) are atomic and consistent, thereby preventing race conditions during the ticket booking process .

You might also like