JAGAN INSTITUTE OF MANAGEMENT STUDIES
SECTOR-5,ROHINI NEW DELHI
(AFFLIATED TO)
GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY
SECTOR-16 C, DWARKA ,NEW DELHI
PRACTICAL FILE OF OOPS & JAVA PROGRAMMING
Submitted To: Submitted By:
Ms Chandni kohli Name: Raghav Sharma
(Assistant professor-IT) Roll No: : 02314002021
Paper Code: BCA 272 BCA-2NDYear 1st Shift
1|P a g e Raghav sharma 02314002021
Index
S.No List of Practicals CO signature
1. Write a Java program to perform basic Calculator operations. Make CO1
a menu driven program to select operation to perform (+ - * / ).
Take 2 integers and perform operation as chosen by user
2. Write a program declaring a class Rectangle with data member’s CO1
length and breadth and member functions Input, Output and
CalcArea.
3. Write a program to demonstrate use of method overloading to CO1
calculate area of square, rectangle and triangle
4. Create a class employee which have name, age and address of CO1
employee, include methods getdata() and showdata(), getdata()
takes the input from the user, showdata() display the data in
following format: Name: Age: Address:
5. Write a program to demonstrate the use of static variable, static CO1
method and static block
6. Write a program to demonstrate concept of ``this``. CO1
7. Write a program to demonstrate multi- level and hierarchical CO2
inheritance.
8. Write a program to use super() to invoke base class constructor. CO2
9. Write a program to demonstrate run-time polymorphism. CO1
10. Write a program to demonstrate the concept of aggregation. CO2
11. Write a program to demonstrate the concept of abstract class with CO2
constructor and ``final`` method.
12. Write a program to demonstrate the concept of interface when two CO1
interfaces have unique methods and same data members
13. Write a program to demonstrate checked exception during file CO4
handling.
14. Write a program to demonstrate unchecked exception CO4
2|P a g e Raghav sharma 02314002021
15. Write a program declaring a Java class called SavingsAccount with CO4
members ``accountNumber`` and ``Balance``. Provide member
functions as ``depositAmount ()`` and ``withdrawAmount ()``. If
user tries to withdraw an amount greater than their balance then
throw a user-defined exception
16. Write a program to demonstrate creation of multiple child threads. CO6
17. Write a program creating 2 threads using Runnab le interface. Print CO6
your name in ``run ()`` method of first class and "Hello Java" in
``run ()`` method of second thread.
18. Write a program to use Byte stream class to read from a text file CO5
and display the content on the output screen.
19. Write a program to make use of BufferedStream to read lines from CO5
the keyboard until 'STOP' is typed
20. Write a program to demonstrate any event handling CO7
21. Write program that uses swings to display combination of RGB CO7
using 3 scrollbars.
22. Write a swing application that uses atleast 5 swing controls CO7
23. Write a program to implement border layout using Swing. CO7
24. Write a java program to insert and update details data in the CO7
database.
25. Write a java program to retrieve data from database and display it CO7
on GUI.
3|P a g e Raghav sharma 02314002021
ACKNOWLEDGEMENT
I , Raghav Sharma of BCA 2ND YEAR 1st SHIFT would like to convey my sincere thanks and
gratitude to Ms. Chandni Kohli for her support and assistance in the completing my practical
file on subject named java programming with paper code BCA 272.
I would like to acknowledge that this practical file was completed entirely by me and not by
someone else.
Signature:
Student Name: RAGHAV SHARMA
Enrollment No: 02314002021
Programme and shift: BCA 2nd year 1ST shift
4|P a g e Raghav sharma 02314002021
CERTIFICATE
This is to certify that JAVA Programming Practical File being submitted is a bonafide work
done by Raghav Sharma Student of BCA 4TH Semester 1st shift in partial fulfilment of the
award of the BCA degree.
She has worked under my guidance and supervision and has fulfilled the requirements of the
file that has been reached the requisite standards.
Ms Chandni Kohli
5|P a g e Raghav sharma 02314002021
Q1.Write a Java program to perform basic Calculator operations. Make a menu driven
program to select operation to perform (+ - * / ). Take 2 integers and perform operation as
chosen by user
import java.util.Scanner;// Raghav sharma 02314002021
public class Calculator{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.println("");
System.out.println("::CALCULATOR::");
System.out.println("Enter a number: ");
int a=scan.nextInt();
System.out.println("Enter second number: ");
int b=scan.nextInt();
while(true){
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int choice=scan.nextInt();
switch(choice){
case 1: System.out.println("Sum="+ (a+b));
break;
case 2: System.out.println("Difference="+ (a-b));
break;
case 3: System.out.println("Product="+ (a*b));
break;
case 4: System.out.println("Quotient="+ (a/b));
break;
case 5: System.exit(0);
default: System.out.println("Enter the correct choice option");
}
}
}
6|P a g e Raghav sharma 02314002021
}
7|P a g e Raghav sharma 02314002021
Q2.Write a program declaring a class Rectangle with data member’s length and breadth and
member functions Input, Output and CalcArea.
class Rectangle{ // Raghav sharma 02314002021
int length;
int width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calculateArea(){
System.out.println(length*width);
}
public static void main(String args[])
{
System.out.println("");
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(3,5);
r2.insert(3,10);
r1.calculateArea();
r2.calculateArea();
}
}
8|P a g e Raghav sharma 02314002021
Q3.Write a program to demonstrate use of method overloading to calculate area of square,
rectangle and triangle.
class shape{ // Raghav sharma 02314002021
int a,l,b;
float B,h;
void area(int a){System.out.println("Area of Square= "+ a*a);}
void area(int l,int b){System.out.println("Area of Rectangle= "+ l*b);}
void area(float B,float h){System.out.println("Area of Triangle= "+ 0.5*B*h);}
}
class overloading{
public static void main(String args[]){
System.out.println("");
shape s1=new shape();
s1.area(5);
s1.area(5,6);
s1.area(5.5f,6.5f);
}
}
9|P a g e Raghav sharma 02314002021
Q4.Create a class employee which have name, age and address of employee, include methods
getdata() and showdata(), getdata() takes the input from the user, showdata() display the data
in following format: Name: Age: Address:
import java.util.Scanner;
class Employee {
String name;
int age;
String address;
void getData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
name = scanner.nextLine();
System.out.print("Enter age: ");
age = scanner.nextInt();
scanner.nextLine(); // Consume the remaining newline character
System.out.print("Enter address: ");
address = scanner.nextLine();
}
void showData() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}
public class Q16 {
public static void main(String[] args) {
System.out.println("");
System.out.println("Japneet Kaur 04990302021");
Employee employee = new Employee();
employee.getData();
System.out.println("******EMPLOYEE DETAILS******");
employee.showData();
}
}
10 | P a g e Raghav sharma 02314002021
11 | P a g e Raghav sharma 02314002021
Q5.Write a program to demonstrate the use of static variable, static method and static block
import java.util.Scanner;
public class StaticStudent{
int rollno;
String name;
static String collegeName="IITM";
import java.util.Scanner; // Raghav sharma 02314002021
public class StaticStudent{
int rollno;
String name;
static String collegeName="jims";
StaticStudent(int rollno, String name){
this.rollno=rollno;
this.name=name;
}
static void updateCollegeName(){
collegeName="jims";
}
void display(){
System.out.println("Name: "+name);
System.out.println("Rollno: "+rollno);
System.out.println("College name: "+collegeName);
}
public static void main(String args[]){
System.out.println("");
Scanner sc=new Scanner(System.in);
System.out.print("Enter name: ");
String name=sc.nextLine();
System.out.print("Enter rollno: ");
int rollno=sc.nextInt();
StaticStudent s1=new StaticStudent(rollno,name);
System.out.println("*****STUDENT DETAILS*****");
s1.updateCollegeName();
s1.display();
}
}
12 | P a g e Raghav sharma 02314002021
13 | P a g e Raghav sharma 02314002021
Q6.Write a program to demonstrate concept of ``this``.
class ThisKeyword{
int id;
String name, departmentName;
ThisKeyword(int id, String name, String departmentName){
this.id=id;
this.name=name;
this.departmentName=departmentName;
}
void display(){
System.out.println("Employee id: "+id);
System.out.println("Employee name: "+name);
System.out.println("Employee department: "+departmentName);
}
public static void main(String[] args){
System.out.println("");
System.out.println("Japneet Kaur 04990302021");
ThisKeyword e=new ThisKeyword(49,"Japneet","IT");
e.display();
}
}
14 | P a g e Raghav sharma 02314002021
Q7.Write a program to demonstrate multi- level and hierarchical inheritance.
class A{ // Raghav sharma 02314002021
public void printA(){ System.out.println("Class A");}
}
class B extends A{
public void printB(){ System.out.println ("Class B");}
}
class C extends A{
public void printC(){ System.out.println ("Class C");}
}
class D extends C{
public void printD(){ System.out.println ("Class D");}
}
class inheritance{
public static void main(String args[]){
System.out.println("");
System.out.println("*****Hierarchical Inheritance******");
B b=new B();
b.printA();
b.printB();
System.out.println("");
C c=new C();
c.printA();
c.printC();
System.out.println("");
System.out.println("*****Multilevel Inheritance******");
D d=new D();
d.printA();
d.printC();
d.printD();
}
}
15 | P a g e Raghav sharma 02314002021
16 | P a g e Raghav sharma 02314002021
Q8.Write a program to use super() to invoke base class constructor.
class BaseClass{ // Raghav sharma 02314002021
BaseClass(){
System.out.println("This is base class constructor!!!");
}
}
class DerivedClass extends BaseClass{
DerivedClass(){
super();
System.out.println("This is derived class constructor!!!");
}
}
class Super{
public static void main(String[] args){
System.out.println("");
DerivedClass d=new DerivedClass();
}
}
17 | P a g e Raghav sharma 02314002021
Q9.Write a program to demonstrate run-time polymorphism.
class Vehicle{ // Raghav sharma 02314002021
void display(){System.out.println("This is Vehicle class display method!!!");}
}
class Car extends Vehicle{
void display(){System.out.println("This is Car class display method!!!");}
}
class Bus extends Vehicle{
void display(){System.out.println("This is Bus class display method!!!");}
}
class Polymorphism{
public static void main(String[] args){
System.out.println("");
Vehicle v=new Vehicle();
Vehicle c=new Car();
Vehicle b=new Bus();
v.display();
c.display();
b.display();
}
}
18 | P a g e Raghav sharma 02314002021
Q10.Write a program to demonstrate the concept of aggregation.
class Address{ // Raghav sharma 02314002021
String house_no, country, area_code;
public Address(String house_no, String country, String area_code){
this.house_no=house_no;
this.country=country;
this.area_code=area_code;
}
}
class Employee{
String name;
Address address;
public Employee(String name, Address address){
this.name=name;
this.address=address;
}
public void display(){
System.out.println("Employee name: "+name);
System.out.println("Employee address: "+address.house_no+",
"+address.country+", "+address.area_code);
}
}
public class TestingAggregation{
public static void main(String[] args){
System.out.println("");
Address address=new Address("Delhi","India","110088");
Employee e=new Employee("Raghav ",address);
e.display();
}
}
19 | P a g e Raghav sharma 02314002021
Q11.Write a program to demonstrate the concept of abstract class with constructor and
``final`` method.
abstract class AbsClass{ // Raghav sharma 02314002021
AbsClass(){
System.out.println("This is the constructor of abstract class!!!");
}
final void absDisplay(){
System.out.println("This is final method of abstract class!!!");
}
abstract void display();
}
class AbstractClass extends AbsClass{
void display(){
System.out.println("This is display method!!!");
}
}
public class TestingAbstractClass{
public static void main(String[] args){
System.out.println("");
AbsClass obj=new AbstractClass();
obj.display();
obj.absDisplay();
}
}
20 | P a g e Raghav sharma 02314002021
Q12.Write a program to demonstrate the concept of interface when two interfaces have
unique methods and same data members
interface IntOne{ // Raghav sharma 02314002021
public void displayOfOne(String s);
}
interface IntTwo{
public void displayOfTwo(String s);
}
class JavaInterface implements IntOne, IntTwo{
public void displayOfOne(String s){
System.out.println(s+", this is display method of interface one!!!");
}
public void displayOfTwo(String s){
System.out.println(s+", this is display method of interface two!!!");
}
}
public class TestingInterface{
public static void main(String[] args){
System.out.println("");
JavaInterface obj=new JavaInterface();
obj.displayOfOne("Hello");
obj.displayOfTwo("Hello");
}
}
21 | P a g e Raghav sharma 02314002021
Q13.Write a program to demonstrate checked exception during file handling.
import java.io.*; // Raghav sharma 02314002021
public class TestingCheckedException{
public static void main(String[] args){
System.out.println("");
File file=new File("not_existing_file.txt");
try{
FileInputStream stream=new FileInputStream(file);
}
catch(FileNotFoundException e){
System.out.println("File not found!!!");
}
}
}
22 | P a g e Raghav sharma 02314002021
Q14.Write a program to demonstrate unchecked exception
import java.util.Scanner; // Raghav sharma 02314002021
public class TestingUncheckedException{
public static void main(String[] args){
System.out.println("");
System.out.println("DIVISION CALCULATOR");
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
int a=sc.nextInt();
System.out.print("Enter second number: ");
int b=sc.nextInt();
try{
if(b==0){
throw new ArithmeticException();
}
else System.out.println("Division: "+a/b);
}
catch(ArithmeticException e){
System.out.println("You cannot divide a number by 0!!!");
}
}
}
23 | P a g e Raghav sharma 02314002021
Q15.Write a program declaring a Java class called SavingsAccount with members
``accountNumber`` and ``Balance``. Provide member functions as ``depositAmount ()`` and
``withdrawAmount ()``. If user tries to withdraw an amount greater than their balance then
throw a user-defined exception.
class InsufficientBalanceException extends Exception { // RAGHAV SHARMA
02314002021
public InsufficientBalanceException(String message) {
super(message);
}
}
class SavingsAccount {
private String accountNumber;
private double balance;
public SavingsAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void depositAmount(double amount) {
balance += amount;
System.out.println("Amount deposited: " + amount);
System.out.println("New balance: " + balance);
}
public void withdrawAmount(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance. Cannot withdraw
amount.");
} else {
balance -= amount;
System.out.println("Amount withdrawn: " + amount);
System.out.println("New balance: " + balance);
}
}
}
public class SavingAcc {
public static void main(String[] args) {
System.out.println("");
SavingsAccount account = new SavingsAccount("123456789", 1000.0);
24 | P a g e Raghav sharma 02314002021
try {
account.depositAmount(500.0);
account.withdrawAmount(200.0);
account.withdrawAmount(1500.0); // This will throw an exception
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
}
25 | P a g e Raghav sharma 02314002021
Q16.Write a program to demonstrate creation of multiple child threads.
class MyThread extends Thread { // Raghav sharma 0231402021
public void run() {
System.out.println("Child thread is running.");
}
}
public class MultipleThreads {
public static void main(String[] args) {
System.out.println("");
// Create and start multiple child threads
for (int i = 1; i <= 5; i++) {
MyThread thread = new MyThread();
thread.start();
} // Print a message from the main thread
System.out.println("Main thread is running.");
}
}
26 | P a g e Raghav sharma 02314002021
Q17.Write a program creating 2 threads using Runnable interface. Print your name in ``run
()`` method of first class and "Hello Java" in ``run ()`` method of second thread. class
MyNameRunnable implements Runnable { //
public void run() {
System.out.println("my name is Silviya");
}
}
class HelloJavaRunnable implements Runnable {
public void run() {
System.out.println("hello java");
}
}
public class Ques17 {
public static void main(String[] args) {
MyNameRunnable myNameRunnable = new MyNameRunnable();
HelloJavaRunnable helloJavaRunnable = new HelloJavaRunnable();
Thread thread1 = new Thread(myNameRunnable);
Thread thread2 = new Thread(helloJavaRunnable);
thread1.start();
thread2.start();
}
}
27 | P a g e Raghav sharma 02314002021
Q18.Write a program to use Byte stream class to read from a text file and display the content
on the output screen.
import java.io.FileInputStream; // Raghav sharma 02314002021
import java.io.IOException;
public class Ques18 {
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream("input.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
System.out.println("an error occurred while reading the file: " + e.getMessage());
}
}
}
28 | P a g e Raghav sharma 02314002021
Q19.Write a program to make use of BufferedStream to read lines from the keyboard until
'STOP' is typed
import java.io.BufferedReader; // Raghav sharma 02314002021
import java.io.IOException;
import java.io.InputStreamReader;
public class bufferedstream {
public static void main(String[] args) {
System.out.println("");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)))
{
String line;
System.out.println("Enter lines (type 'STOP' to exit):");
while (!(line = reader.readLine()).equals("STOP")) {
System.out.println("You entered: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
29 | P a g e Raghav sharma 02314002021
Q20.Write a program to demonstrate any event handling
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class eventhandling {
public static void main(String[] args) {
System.out.println("");
// Create a JFrame
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JLabel
JLabel label = new JLabel("Welcome to Event Handling!");
frame.getContentPane().add(label);
// Create a JButton
JButton button = new JButton("Click Me");
frame.getContentPane().add(button, "South");
// Create an ActionListener for the button
ActionListener buttonListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
};
// Register the ActionListener with the button
button.addActionListener(buttonListener);
// Set the size, visibility, and layout of the JFrame
frame.setSize(300, 200);
frame.setVisible(true);
frame.setLayout(null);
}
}
30 | P a g e Raghav sharma 02314002021
Q21.Write program that uses swings to display combination of RGB using 3 scrollbars.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class RGB implements AdjustmentListener
{
// application object fields
JScrollBar sbar1;
JScrollBar sbar2;
JScrollBar sbar3;
JPanel panel;
private static void createAndShowGUI()
{
// make frame..
JFrame frame = new JFrame("JScrollBar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,30,200,250);
frame.getContentPane().setLayout(null);
RGB app = new RGB();
app.sbar1 = new JScrollBar(java.awt.Adjustable.VERTICAL, 127, 1,0,255);
app.sbar1.setBounds(10,20, 10, 200);
app.sbar1.setBackground(Color.red);
app.sbar1.addAdjustmentListener(app);
frame.getContentPane().add(app.sbar1);
app.sbar2 = new JScrollBar(java.awt.Adjustable.VERTICAL, 127, 1,0,255);
app.sbar2.setBounds(30,20, 10, 200);
app.sbar2.setBackground(Color.green);
app.sbar2.addAdjustmentListener(app);
frame.getContentPane().add(app.sbar2);
app.sbar3 = new JScrollBar(java.awt.Adjustable.VERTICAL, 127, 1,0,255);
app.sbar3.setBounds(50,20, 10, 200);
app.sbar3.setBackground(Color.blue);
app.sbar3.addAdjustmentListener(app);
frame.getContentPane().add(app.sbar3);
app.panel = new JPanel();
app.panel.setBounds(80,20,50,200);
app.panel.setBackground(new Color(0,0,0));
frame.getContentPane().add(app.panel);
31 | P a g e Raghav sharma 02314002021
frame.setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
panel.setBackground(new Color(sbar1.getValue(),sbar2.getValue(), sbar3.getValue()));
}
public static void main(String[] args) {
// start off..
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
32 | P a g e Raghav sharma 02314002021
Q22.Write a swing application that uses atleast 5 swing controls
import javax.swing.JButton; // Raghav sharma 02314002021
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class swingcontrols5 {
public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Swing Controls Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JPanel
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
// Create a JLabel
JLabel nameLabel = new JLabel("Name:");
panel.add(nameLabel);
// Create a JTextField
JTextField nameTextField = new JTextField(20);
panel.add(nameTextField);
// Create a JButton
JButton submitButton = new JButton("Submit");
panel.add(submitButton);
// Create a JLabel to display result
JLabel resultLabel = new JLabel();
panel.add(resultLabel);
// Add an action listener to the submit button
submitButton.addActionListener(e -> {
String name = nameTextField.getText();
resultLabel.setText("Hello, " + name + "!"); });
// Set the size, visibility, and layout of the JFrame
frame.setSize(300, 200);
frame.setVisible(true);
frame.setLayout(null);
}
}
33 | P a g e Raghav sharma 02314002021
34 | P a g e Raghav sharma 02314002021
Q23.Write a program to implement border layout using Swing.
import java.awt.*; // Raghav sharma 02314002021
import javax.swing.*;
public class Border{
JFrame jframe;
// constructor
Border()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new Border();
}
}
35 | P a g e Raghav sharma 02314002021
36 | P a g e Raghav sharma 02314002021
Q24.Write a java program to insert and update details data in the database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
public class Ok {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/javapracticalfi le",
"root", "root");
Statement statement = connection.createStatement();
int age;
String name;
Scanner s = new Scanner(System.in);
System.out.println("Enter the name and age: ");
name = s.next();
age = s.nextInt();
String query = "insert into student values('" + name + "', '" + age +"');";
statement.executeUpdate(query);
System.out.println("Succesfully updated the table");
connection.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
37 | P a g e Raghav sharma 02314002021
38 | P a g e Raghav sharma 02314002021
Q25.Write a java program to retrieve data from dat
import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class Main extends JFrame {
private JTextArea textArea;
private static final String DB_URL = "jdbc:mysql://localhost:3306/javapracticalfile";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
public Main() {
setTitle("Database GUI Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
}
public void fetchDataFromDatabase() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
statement = connection.createStatement();
String query = "SELECT * FROM student";
resultSet = statement.executeQuery(query);
StringBuilder result = new StringBuilder();
while (resultSet.next()) {
String name = resultSet.getString("sname");
String age = resultSet.getString("age");
result.append("Name: ").append(name)
.append(", Age: ").append(age)
.append("\n");
}
textArea.setText(result.toString());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
39 | P a g e Raghav sharma 02314002021
resultSet.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main example = new Main();
example.setVisible(true);
example.fetchDataFromDatabase();
}
});
}
}
40 | P a g e Raghav sharma 02314002021