Sample java program to check given number is prime or not
ChatGPT said:
Here’s a simple Java program to check whether a given number is prime
or not 👇
import [Link];
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isPrime = true;
// 0 and 1 are not prime numbers
if (num <= 1) {
isPrime = false;
} else {
// check divisibility
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
// display result
if (isPrime)
[Link](num + " is a prime number.");
else
[Link](num + " is not a prime number.");
[Link]();
🔍 Explanation:
Input: User enters a number.
Condition:
o If number ≤ 1 → not prime.
o Else, check if it’s divisible by any number from 2 to num/2.
Output: Prints whether it’s prime or not.
Would you like me to show a simpler version (without Scanner) or an
optimized version (faster check)?
You said:
To Develop an applet in Java that displays a simple message.
ChatGPT said:
Here’s a simple Java Applet program that displays a message on the
screen 👇
import [Link];
import [Link];
/*
<applet code="SimpleMessageApplet" width="300" height="150">
</applet>
*/
public class SimpleMessageApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello! Welcome to Java Applet!", 50, 80);
🧩 Explanation:
Applet is a Java class used to create small applications that run
inside a browser or applet viewer.
paint(Graphics g) method is used to display output.
drawString() draws the given text message on the applet window.
▶️How to Run:
1. Save the file as [Link]
2. Compile it:
3. javac [Link]
4. Run it using appletviewer:
5. appletviewer [Link]
Would you like me to show the same example using Swing (JApplet or
JFrame)? It works in modern Java since normal applets are deprecated in
browsers.
You said:
Develop applet to find factorial of the given number
ChatGPT said:
Here’s a simple Java Applet program to find the factorial of a given
number 👇
import [Link];
import [Link].*;
import [Link].*;
/*
<applet code="FactorialApplet" width="400" height="200">
</applet>
*/
public class FactorialApplet extends Applet implements ActionListener {
Label l1, l2;
TextField t1, t2;
Button b1;
public void init() {
// Create components
l1 = new Label("Enter a number:");
t1 = new TextField(10);
b1 = new Button("Find Factorial");
l2 = new Label("Result:");
t2 = new TextField(10);
// Disable editing of result box
[Link](false);
// Add components to applet
add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
// Add action listener to button
[Link](this);
public void actionPerformed(ActionEvent e) {
int n = [Link]([Link]());
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
[Link]([Link](fact));
🧩 Explanation:
TextField is used to enter the number and display the result.
Button triggers the calculation.
actionPerformed() runs when the button is clicked.
The factorial is calculated using a simple loop.
▶️How to Run:
1. Save as [Link]
2. Compile:
3. javac [Link]
4. Run using:
5. appletviewer [Link]
Would you like me to show a Swing (JApplet or JFrame) version too? It
works in newer Java versions where applets are no longer supported.
You said:
Display the output
ChatGPT said:
Here’s what the output of the Factorial Applet will look like when you
run it using the appletviewer 👇
🖥️Output Window (Applet Screen):
-----------------------------------------
| Enter a number: [ 5 ] |
| |
| [ Find Factorial ] |
| |
| Result: [ 120 ] |
-----------------------------------------
💡 Example:
If you enter 5 and click Find Factorial,
the applet will display 120 in the result box.
🔁 Another Example:
Inpu Outp
t ut
3 6
4 24
6 720
Would you like me to show how the same factorial program looks using
Swing (JFrame) — since normal applets won’t run in modern browsers or
IDEs?
You said:
Develop an applet to perform division
ChatGPT said:
Here’s a simple Java Applet program to perform division of two
numbers 👇
import [Link];
import [Link].*;
import [Link].*;
/*
<applet code="DivisionApplet" width="400" height="200">
</applet>
*/
public class DivisionApplet extends Applet implements ActionListener {
Label l1, l2, l3;
TextField t1, t2, t3;
Button b1;
public void init() {
// Create components
l1 = new Label("Enter first number:");
t1 = new TextField(10);
l2 = new Label("Enter second number:");
t2 = new TextField(10);
b1 = new Button("Divide");
l3 = new Label("Result:");
t3 = new TextField(10);
// Disable editing of result field
[Link](false);
// Add components to applet
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
add(t3);
// Add action listener to button
[Link](this);
public void actionPerformed(ActionEvent e) {
try {
double num1 = [Link]([Link]());
double num2 = [Link]([Link]());
if (num2 == 0) {
[Link]("Cannot divide by zero");
} else {
double result = num1 / num2;
[Link]([Link](result));
} catch (NumberFormatException ex) {
[Link]("Invalid Input");
}
🧩 Explanation:
TextField t1, t2 → to enter numbers.
Button b1 → to perform division.
TextField t3 → to display result.
Handles division by zero and invalid input safely.
▶️How to Run:
1. Save the file as [Link]
2. Compile it:
3. javac [Link]
4. Run using:
5. appletviewer [Link]
💻 Sample Output:
-----------------------------------------
| Enter first number: [ 10 ] |
| Enter second number: [ 2 ] |
| [ Divide ] |
| Result: [ 5.0 ] |
-----------------------------------------
If you enter 10 and 2, it shows 5.0.
If you enter 10 and 0, it shows Cannot divide by zero.
Would you like me to show the same program using Swing (JFrame)
version that works in modern Java environments (since applets are
deprecated)?
You said:
Write a Java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and
if the value is even, second thread computes the square of the number
and prints. If the value is odd, the third thread will print the value of cube
of the number.
ChatGPT said:
Here’s a Java multithreading program that meets your requirements 👇
import [Link];
class NumberGenerator extends Thread {
public void run() {
Random rand = new Random();
while (true) {
int num = [Link](100); // generates a random number
between 0–99
[Link]("\nGenerated Number: " + num);
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
try {
[Link](1000); // 1 second delay
} catch (InterruptedException e) {
[Link](e);
}
}
class SquareThread extends Thread {
int num;
SquareThread(int n) {
num = n;
public void run() {
[Link]("Square of " + num + " = " + (num * num));
class CubeThread extends Thread {
int num;
CubeThread(int n) {
num = n;
public void run() {
[Link]("Cube of " + num + " = " + (num * num * num));
public class MultiThreadExample {
public static void main(String[] args) {
NumberGenerator t1 = new NumberGenerator();
[Link]();
🧩 Explanation:
NumberGenerator (Thread 1):
Generates a random integer every 1 second.
SquareThread (Thread 2):
Prints the square if the number is even.
CubeThread (Thread 3):
Prints the cube if the number is odd.
🖥️Sample Output:
Generated Number: 8
Square of 8 = 64
Generated Number: 3
Cube of 3 = 27
Generated Number: 10
Square of 10 = 100
Generated Number: 5
Cube of 5 = 125
Would you like me to modify this program to stop after 10 random
numbers (instead of running forever)?
You said:
. Write a Java program that connects to a database using JDBC and does
add, delete, modify and retrieve operations.
ChatGPT said:
Here’s a complete Java JDBC program that demonstrates how to
connect to a database and perform Add, Delete, Modify, and
Retrieve (CRUD) operations 👇
🧠 Program: JDBC CRUD Example
import [Link].*;
import [Link];
public class JdbcCrudExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Change these according to your database setup
String url = "jdbc:mysql://localhost:3306/testdb"; // Database name:
testdb
String user = "root"; // MySQL username
String password = "1234"; // MySQL password
try {
// Load MySQL JDBC Driver
[Link]("[Link]");
// Establish connection
Connection con = [Link](url, user,
password);
[Link]("✅ Connected to Database Successfully!");
while (true) {
[Link]("\n--- MENU ---");
[Link]("1. Add Record");
[Link]("2. Delete Record");
[Link]("3. Modify Record");
[Link]("4. Retrieve Records");
[Link]("5. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice) {
case 1:
// Add record
[Link]("Enter ID: ");
int id = [Link]();
[Link]("Enter Name: ");
String name = [Link]();
String insertQuery = "INSERT INTO student VALUES (?, ?)";
PreparedStatement ps1 =
[Link](insertQuery);
[Link](1, id);
[Link](2, name);
[Link]();
[Link]("✅ Record Added Successfully!");
break;
case 2:
// Delete record
[Link]("Enter ID to delete: ");
int delId = [Link]();
String deleteQuery = "DELETE FROM student WHERE id
= ?";
PreparedStatement ps2 =
[Link](deleteQuery);
[Link](1, delId);
[Link]();
[Link]("🗑️Record Deleted Successfully!");
break;
case 3:
// Modify record
[Link]("Enter ID to modify: ");
int modId = [Link]();
[Link]("Enter new name: ");
String newName = [Link]();
String updateQuery = "UPDATE student SET name = ?
WHERE id = ?";
PreparedStatement ps3 =
[Link](updateQuery);
[Link](1, newName);
[Link](2, modId);
[Link]();
[Link]("✏️Record Updated Successfully!");
break;
case 4:
// Retrieve records
String selectQuery = "SELECT * FROM student";
Statement stmt = [Link]();
ResultSet rs = [Link](selectQuery);
[Link]("\nID\tName");
[Link]("------------------");
while ([Link]()) {
[Link]([Link](1) + "\t" + [Link](2));
break;
case 5:
// Exit
[Link]("👋 Exiting...");
[Link]();
[Link]();
return;
default:
[Link]("Invalid choice. Try again!");
} catch (Exception e) {
[Link]("❌ Error: " + [Link]());
🗄️Database Setup
1. Open MySQL and create a database:
2. CREATE DATABASE testdb;
3. USE testdb;
4. Create a table:
5. CREATE TABLE student (
6. id INT PRIMARY KEY,
7. name VARCHAR(50)
8. );
⚙️To Run the Program
1. Save the file as [Link]
2. Add the MySQL JDBC Driver ([Link]) to your
classpath.
3. Compile and run:
4. javac [Link]
5. java -cp .;[Link] JdbcCrudExample
💻 Sample Output
✅ Connected to Database Successfully!
--- MENU ---
1. Add Record
2. Delete Record
3. Modify Record
4. Retrieve Records
5. Exit
Enter your choice: 1
Enter ID: 101
Enter Name: Raj
✅ Record Added Successfully!
Enter your choice: 4
ID Name
--------------
101 Raj
Would you like me to modify this example for a specific database system
(like SQLite, PostgreSQL, or Oracle) — so you can run it without MySQL
setup?
You said:
Write a Java program that simulates a traffic light. The program lets the
user select one of three lights: red, yellow, or green with radio buttons. On
selecting a button, an appropriate message with “Stop” or “Ready” or
“Go” should appear above the buttons in selected color. Initially, there is
no message shown.
ChatGPT said:
Here’s a simple Java Swing GUI program that simulates a Traffic Light
System using radio buttons 👇
🚦 Traffic Light Simulation Program
import [Link].*;
import [Link].*;
import [Link].*;
public class TrafficLightSimulator extends JFrame implements
ActionListener {
// Radio buttons
JRadioButton red, yellow, green;
ButtonGroup group;
// Label to show message
JLabel message;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulation");
setSize(300, 250);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create label (initially blank)
message = new JLabel("");
[Link](new Font("Arial", [Link], 24));
add(message);
// Create radio buttons
red = new JRadioButton("Red");
yellow = new JRadioButton("Yellow");
green = new JRadioButton("Green");
// Group them so only one can be selected
group = new ButtonGroup();
[Link](red);
[Link](yellow);
[Link](green);
// Add radio buttons to frame
add(red);
add(yellow);
add(green);
// Add action listeners
[Link](this);
[Link](this);
[Link](this);
setVisible(true);
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link]("STOP");
[Link]([Link]);
} else if ([Link]()) {
[Link]("READY");
[Link]([Link]);
} else if ([Link]()) {
[Link]("GO");
[Link]([Link]);
public static void main(String[] args) {
new TrafficLightSimulator();
🧩 Explanation
JRadioButton: Used for Red, Yellow, Green options.
ButtonGroup: Ensures only one light is selected at a time.
JLabel: Displays the message (“Stop”, “Ready”, or “Go”) in the
correct color.
Initially, no message is shown until a button is selected.
🖥️Sample Output (GUI View)
When you run the program:
+------------------------------------+
| |
| (No text) |
| |
| ( ) Red ( ) Yellow ( ) Green |
+------------------------------------+
If you click Red → Displays STOP in red.
If you click Yellow → Displays READY in orange.
If you click Green → Displays GO in green.
Would you like me to modify it so it also shows colored traffic lights
(circles) like a real signal along with the text?
You said:
Write a Java program to create an abstract class named Shape that
contains two integers and an empty method named printArea(). Provide
three classes named Rectangle, Triangle and Circle such that each one of
the classes extends the class Shape. Each one of the classes contains only
the method printArea () that prints the area of the given shape.
ChatGPT said:
Here’s a clear and complete Java program that demonstrates the use of
an abstract class Shape and its subclasses Rectangle, Triangle, and
Circle 👇
🧮 Program: Abstract Class Example
import [Link].*;
abstract class Shape {
int dim1, dim2;
// Constructor
Shape(int a, int b) {
dim1 = a;
dim2 = b;
// Abstract method
abstract void printArea();
// Rectangle subclass
class Rectangle extends Shape {
Rectangle(int a, int b) {
super(a, b);
void printArea() {
double area = dim1 * dim2;
[Link]("Area of Rectangle = " + area);
// Triangle subclass
class Triangle extends Shape {
Triangle(int a, int b) {
super(a, b);
}
void printArea() {
double area = 0.5 * dim1 * dim2;
[Link]("Area of Triangle = " + area);
// Circle subclass
class Circle extends Shape {
Circle(int r) {
super(r, 0);
void printArea() {
double area = 3.14159 * dim1 * dim1;
[Link]("Area of Circle = " + area);
public class AbstractShapeDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Rectangle
[Link]("Enter length and breadth of Rectangle: ");
int l = [Link]();
int b = [Link]();
Shape rect = new Rectangle(l, b);
[Link]();
// Triangle
[Link]("\nEnter base and height of Triangle: ");
int base = [Link]();
int height = [Link]();
Shape tri = new Triangle(base, height);
[Link]();
// Circle
[Link]("\nEnter radius of Circle: ");
int r = [Link]();
Shape cir = new Circle(r);
[Link]();
[Link]();
🧩 Explanation:
Shape is an abstract class containing two integer members (dim1,
dim2) and an abstract method printArea().
Rectangle, Triangle, and Circle each extend Shape and provide
their own implementation of printArea().
The program takes user input and prints the corresponding areas.
🖥️Sample Output:
Enter length and breadth of Rectangle: 10 5
Area of Rectangle = 50.0
Enter base and height of Triangle: 6 4
Area of Triangle = 12.0
Enter radius of Circle: 3
Area of Circle = 28.27431
Would you like me to modify it so that it uses method overloading
instead of constructors (for input flexibility)?
You said:
Suppose that a table named [Link] is stored in a text file. The first line
in the file is the header, and the remaining lines correspond to rows in the
table. The elements are separated by commas. Write a java program to
display the table using Labels in Grid Layout
ChatGPT said:
Here’s a simple and complete Java program that reads a CSV-like text
file ([Link]) and displays it using Labels in a GridLayout 👇
🧠 Program: Display Table from File Using GridLayout
import [Link].*;
import [Link].*;
import [Link].*;
public class DisplayTable extends JFrame {
public DisplayTable() {
setTitle("Table Display from File");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
// Read the file
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
String line;
String[][] data = new String[50][]; // assuming max 50 rows
int rowCount = 0;
while ((line = [Link]()) != null) {
data[rowCount++] = [Link](","); // split by commas
[Link]();
// Use GridLayout: rows = rowCount, columns = number of
elements in first row
setLayout(new GridLayout(rowCount, data[0].length));
// Display data using labels
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < data[i].length; j++) {
JLabel label = new JLabel(data[i][j], [Link]);
[Link](true);
// Header styling
if (i == 0) {
[Link](Color.LIGHT_GRAY);
[Link](new Font("Arial", [Link], 14));
} else {
[Link]([Link]);
[Link](new Font("Arial", [Link], 13));
}
[Link]([Link]([Link]));
add(label);
} catch (IOException e) {
[Link](this, "Error reading file: " +
[Link]());
setVisible(true);
public static void main(String[] args) {
new DisplayTable();
📘 Example Input File: [Link]
ID,Name,Marks
101,Ravi,85
102,Anita,90
103,Kumar,78
104,Meena,88
🖥️Output (GUI Window)
------------------------------------------
| ID | Name | Marks |
------------------------------------------
| 101 | Ravi | 85 |
| 102 | Anita | 90 |
| 103 | Kumar | 78 |
| 104 | Meena | 88 |
------------------------------------------
Each cell is shown in a Label, neatly arranged using GridLayout, with the
header highlighted in gray.
🧩 Key Points:
Uses BufferedReader to read the text file.
Splits each line by commas (,).
Uses GridLayout to arrange JLabels in a table form.
Styles the header row differently for better visibility.
Would you like me to modify this so it lets the user choose the file
(using a file chooser dialog)?
You said:
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).
ChatGPT said:
Here’s a clean and easy Java Swing program that handles all mouse
events using adapter classes, and displays the event name in the
center of the window 👇
🖱️Program: Mouse Events using Adapter Class
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventDemo extends JFrame {
String msg = "";
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a custom panel to handle mouse events
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setVisible(true);
// Inner class extending MouseAdapter
class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked";
repaint();
public void mousePressed(MouseEvent e) {
msg = "Mouse Pressed";
repaint();
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
repaint();
public void mouseEntered(MouseEvent e) {
msg = "Mouse Entered";
repaint();
public void mouseExited(MouseEvent e) {
msg = "Mouse Exited";
repaint();
public void mouseDragged(MouseEvent e) {
msg = "Mouse Dragged";
repaint();
public void mouseMoved(MouseEvent e) {
msg = "Mouse Moved";
repaint();
// Paint message in center of the window
public void paint(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
[Link](msg, 120, 150);
public static void main(String[] args) {
new MouseEventDemo();
🧩 Explanation:
The program uses a MouseAdapter (which implements both
MouseListener and MouseMotionListener).
Every mouse action (click, press, release, drag, move, etc.) updates
the msg string.
The paint() method redraws the message at the center of the
window.
This avoids needing to implement all listener methods separately.
🖥️Output:
A window titled “Mouse Event Demo” appears.
When you click, it shows → “Mouse Clicked”
When you move the mouse, it shows → “Mouse Moved”
When you drag, it shows → “Mouse Dragged”
When you enter or exit the window, it updates accordingly.
Would you like me to make this version graphical (e.g., showing colored
background changes or shapes when events occur)?
You said:
Write a Java program that loads names and phone numbers from a text
file where the data is organized as one line per record and each field in a
record are separated by a tab (\t). It takes a name or phone number as
input and prints the corresponding other value from the hash table (hint:
use hash tables).
ChatGPT said:
Here’s a simple and complete Java program that uses a HashTable to
load data (names and phone numbers) from a text file, and allows you to
look up either by name or phone number 👇
📘 Program: Phone Directory Using HashTable
import [Link].*;
import [Link].*;
public class PhoneDirectory {
public static void main(String[] args) {
// Hash tables for name → phone and phone → name lookups
Hashtable<String, String> nameToPhone = new Hashtable<>();
Hashtable<String, String> phoneToName = new Hashtable<>();
try {
// Reading data from file
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
// Split by tab (\t)
String[] parts = [Link]("\t");
if ([Link] == 2) {
String name = parts[0].trim();
String phone = parts[1].trim();
[Link](name, phone);
[Link](phone, name);
}
[Link]();
[Link]("✅ Phone directory loaded successfully!\n");
catch (IOException e) {
[Link]("❌ Error reading file: " + [Link]());
return;
// User input lookup
Scanner sc = new Scanner([Link]);
while (true) {
[Link]("Search by:");
[Link]("1. Name");
[Link]("2. Phone Number");
[Link]("3. Exit");
[Link]("Enter choice: ");
int choice = [Link]();
[Link](); // consume newline
switch (choice) {
case 1:
[Link]("Enter Name: ");
String name = [Link]().trim();
if ([Link](name))
[Link]("Phone Number: " +
[Link](name));
else
[Link]("Name not found!");
break;
case 2:
[Link]("Enter Phone Number: ");
String phone = [Link]().trim();
if ([Link](phone))
[Link]("Name: " + [Link](phone));
else
[Link]("Phone number not found!");
break;
case 3:
[Link]("👋 Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice! Try again.");
[Link]();
📄 Example Input File — [Link]
Each line contains Name and Phone Number separated by a tab (\t):
Ravi 9876543210
Anita 9123456789
Kumar 9001122334
Meena 9998887776
🖥️Sample Output
✅ Phone directory loaded successfully!
Search by:
1. Name
2. Phone Number
3. Exit
Enter choice: 1
Enter Name: Anita
Phone Number: 9123456789
Search by:
1. Name
2. Phone Number
3. Exit
Enter choice: 2
Enter Phone Number: 9001122334
Name: Kumar
🧩 Explanation
HashTable<String, String> nameToPhone → stores mappings
from name → phone.
HashTable<String, String> phoneToName → stores reverse
mappings.
File is read line by line, split using \t (tab character).
Program allows two-way lookup:
o Enter a name → get phone.
o Enter a phone → get name.
Would you like me to modify it to use HashMap instead (which is faster
and more modern than Hashtable)?
You said:
Implement above program with database instead of text file
ChatGPT said:
Excellent — let’s now upgrade the previous Phone Directory
(Hashtable) program to use a database instead of a text file.
Below is a JDBC-based Java program that connects to a MySQL
database, loads all records into a HashMap, and allows searching by
name or phone number.
🧠 Program: Phone Directory Using Database (JDBC + HashMap)
import [Link].*;
import [Link].*;
public class PhoneDirectoryDB {
public static void main(String[] args) {
// Hash maps for fast lookup
HashMap<String, String> nameToPhone = new HashMap<>();
HashMap<String, String> phoneToName = new HashMap<>();
// Database connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // Your database
name
String user = "root"; // Your DB username
String password = "1234"; // Your DB password
try {
// Load the MySQL driver
[Link]("[Link]");
// Connect to the database
Connection con = [Link](url, user,
password);
[Link]("✅ Connected to Database Successfully!");
// Create table if not exists
Statement st = [Link]();
[Link]("CREATE TABLE IF NOT EXISTS phonebook
(name VARCHAR(50), phone VARCHAR(15))");
// Fetch all records
ResultSet rs = [Link]("SELECT * FROM phonebook");
while ([Link]()) {
String name = [Link]("name").trim();
String phone = [Link]("phone").trim();
[Link](name, phone);
[Link](phone, name);
[Link]("📱 Phone Directory Loaded Successfully!\n");
Scanner sc = new Scanner([Link]);
while (true) {
[Link]("--- MENU ---");
[Link]("1. Add Record");
[Link]("2. Search by Name");
[Link]("3. Search by Phone Number");
[Link]("4. Exit");
[Link]("Enter choice: ");
int choice = [Link]();
[Link](); // consume newline
switch (choice) {
case 1:
// Add new record
[Link]("Enter Name: ");
String newName = [Link]();
[Link]("Enter Phone Number: ");
String newPhone = [Link]();
PreparedStatement ps = [Link]("INSERT
INTO phonebook VALUES (?, ?)");
[Link](1, newName);
[Link](2, newPhone);
[Link]();
[Link](newName, newPhone);
[Link](newPhone, newName);
[Link]("✅ Record added successfully!\n");
break;
case 2:
// Search by name
[Link]("Enter Name: ");
String name = [Link]().trim();
if ([Link](name))
[Link]("Phone Number: " +
[Link](name));
else
[Link]("❌ Name not found!");
[Link]();
break;
case 3:
// Search by phone
[Link]("Enter Phone Number: ");
String phone = [Link]().trim();
if ([Link](phone))
[Link]("Name: " +
[Link](phone));
else
[Link]("❌ Phone number not found!");
[Link]();
break;
case 4:
[Link]("👋 Exiting...");
[Link]();
[Link]();
return;
default:
[Link]("Invalid choice! Try again.\n");
} catch (Exception e) {
[Link]("❌ Error: " + [Link]());
🗄️Database Setup (MySQL)
Before running the program:
1. Create a database (for example testdb):
2. CREATE DATABASE testdb;
3. USE testdb;
4. Create the table (if it doesn’t exist already):
5. CREATE TABLE phonebook (
6. name VARCHAR(50),
7. phone VARCHAR(15)
8. );
9. Optionally insert sample data:
10. INSERT INTO phonebook VALUES
11. ('Ravi', '9876543210'),
12. ('Anita', '9123456789'),
13. ('Kumar', '9001122334');
🖥️Sample Output
✅ Connected to Database Successfully!
📱 Phone Directory Loaded Successfully!
--- MENU ---
1. Add Record
2. Search by Name
3. Search by Phone Number
4. Exit
Enter choice: 2
Enter Name: Anita
Phone Number: 9123456789
--- MENU ---
Enter choice: 3
Enter Phone Number: 9876543210
Name: Ravi
⚙️To Compile and Run
Make sure you have the MySQL JDBC Driver (mysql-connector-j-
[Link]) in your classpath.
javac [Link]
java -cp .;[Link] PhoneDirectoryDB
Would you like me to modify this so that it uses SQLite instead (so you
don’t need a MySQL server)? It would work directly without external setup.
You said:
Write a Java Program that takes tab separated data (one record line) from
a text file and insert them into a database.
ChatGPT said:
Here’s a simple and clear Java JDBC program that reads tab-
separated data from a text file and inserts each record into a
database table 👇
🧠 Program: Insert Tab-Separated Data from File into Database
import [Link].*;
import [Link].*;
public class FileToDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // Your database
name
String user = "root"; // Your MySQL username
String password = "1234"; // Your MySQL password
String fileName = "[Link]"; // Text file with tab-
separated data
try {
// Load MySQL JDBC driver
[Link]("[Link]");
// Establish connection
Connection con = [Link](url, user,
password);
[Link]("✅ Connected to Database!");
// Create table if not exists
Statement st = [Link]();
[Link]("CREATE TABLE IF NOT EXISTS employees (name
VARCHAR(50), age INT, department VARCHAR(50))");
[Link]("📋 Table checked/created.\n");
// Read from file
BufferedReader br = new BufferedReader(new
FileReader(fileName));
String line;
int count = 0;
while ((line = [Link]()) != null) {
// Split tab-separated data
String[] parts = [Link]("\t");
if ([Link] < 3) continue; // Skip invalid lines
String name = parts[0];
int age = [Link](parts[1]);
String dept = parts[2];
// Insert into database
PreparedStatement ps = [Link]("INSERT INTO
employees VALUES (?, ?, ?)");
[Link](1, name);
[Link](2, age);
[Link](3, dept);
[Link]();
count++;
[Link]();
[Link]();
[Link]("✅ " + count + " record(s) inserted
successfully!");
catch (Exception e) {
[Link]("❌ Error: " + [Link]());
📄 Sample Input File ([Link])
Each line contains tab-separated values:
Ravi 25 IT
Anita 30 HR
Kumar 28 Finance
Sneha 35 Marketing
🗄️Database Setup (MySQL)
Before running, make sure:
1. You have created a database (example: testdb)
2. CREATE DATABASE testdb;
3. USE testdb;
4. The program will automatically create the table:
5. CREATE TABLE employees (
6. name VARCHAR(50),
7. age INT,
8. department VARCHAR(50)
9. );
🖥️Expected Output
✅ Connected to Database!
📋 Table checked/created.
✅ 4 record(s) inserted successfully!
⚙️To Compile and Run
Make sure the MySQL Connector JAR (e.g., [Link])
is in your classpath.
javac [Link]
java -cp .;[Link] FileToDatabase
Would you like me to modify this version to use SQLite (so you can run it
locally without MySQL)? It works with no setup and stores data in a
single .db file.
You said:
Write a Java Program that prints the meta data of a given table
ChatGPT said:
Here’s a Java JDBC program that connects to a database and prints the
metadata (structure information) of a given table — such as column
names, data types, and other details 👇
🧠 Program: Display Table Metadata using JDBC
import [Link].*;
public class TableMetaData {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // Database name
String user = "root"; // Your MySQL username
String password = "1234"; // Your MySQL password
String tableName = "employees"; // Table name to check
try {
// Load the MySQL JDBC Driver
[Link]("[Link]");
// Connect to database
Connection con = [Link](url, user,
password);
[Link]("✅ Connected to Database!");
// Query to get metadata
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM " + tableName);
// Get metadata object
ResultSetMetaData meta = [Link]();
int columnCount = [Link]();
[Link]("\n📋 Table Name: " + tableName);
[Link]("------------------------------------");
[Link]("%-20s %-20s %-10s\n", "COLUMN NAME", "DATA
TYPE", "SIZE");
[Link]("------------------------------------");
// Print column details
for (int i = 1; i <= columnCount; i++) {
String colName = [Link](i);
String colType = [Link](i);
int colSize = [Link](i);
[Link]("%-20s %-20s %-10d\n", colName, colType,
colSize);
[Link]();
} catch (Exception e) {
[Link]("❌ Error: " + [Link]());
🗄️Example Database Table
Suppose your database (testdb) contains a table called employees:
CREATE TABLE employees (
name VARCHAR(50),
age INT,
department VARCHAR(50)
);
🖥️Expected Output
✅ Connected to Database!
📋 Table Name: employees
------------------------------------
COLUMN NAME DATA TYPE SIZE
------------------------------------
name VARCHAR 50
age INT 11
department VARCHAR 50
⚙️How to Compile & Run
Make sure you have the MySQL JDBC driver (mysql-connector-j-
[Link]) in your classpath.
javac [Link]
java -cp .;[Link] TableMetaData
✅ What This Program Does
Connects to the given MySQL database.
Executes a SELECT * FROM <table> query.
Retrieves metadata using ResultSetMetaData.
Prints each column’s name, data type, and size.
Would you like me to make a version that lists all tables in the database
along with their metadata automatically (not just one table)?
You said:
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
ChatGPT said:
Here’s a Java Swing program that implements a Simple Calculator
using GridLayout, with buttons for digits and operators +, -, *, %, / — and
includes exception handling (like divide by zero).
🧮 Java Program: Simple Calculator using GridLayout
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleCalculator extends JFrame implements ActionListener {
JTextField display;
double num1 = 0, num2 = 0, result = 0;
char operator;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Display field
display = new JTextField();
[Link](false);
add(display, [Link]);
// Panel for buttons
JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 10, 10));
// Buttons for digits and operators
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "%", "/", "="
};
for (String text : buttons) {
JButton b = new JButton(text);
[Link](this);
[Link](b);
add(panel, [Link]);
// Clear button at the bottom
JButton clearBtn = new JButton("C");
[Link](this);
add(clearBtn, [Link]);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s = [Link]();
try {
if ([Link](0) >= '0' && [Link](0) <= '9') {
[Link]([Link]() + s);
} else if ([Link]("+") || [Link]("-") || [Link]("*") ||
[Link]("/") || [Link]("%")) {
num1 = [Link]([Link]());
operator = [Link](0);
[Link]("");
} else if ([Link]("=")) {
num2 = [Link]([Link]());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;
break;
case '%':
result = num1 % num2;
break;
[Link]([Link](result));
} else if ([Link]("C")) {
[Link]("");
num1 = num2 = result = 0;
} catch (ArithmeticException ex) {
[Link]("Error: " + [Link]());
} catch (Exception ex) {
[Link]("Invalid Input");
public static void main(String[] args) {
new SimpleCalculator();
🧩 Explanation
Layout:
o BorderLayout is used for the main frame.
o A GridLayout(4,4) arranges digit and operator buttons neatly.
Display: A JTextField shows numbers and results.
Buttons: Digits 0–9, operators + - * / %, = for result, and C for
clear.
Error Handling:
o Handles invalid inputs and division by zero gracefully.
🖥️Sample Output
When you run the program, a window appears like this:
+-----------------------------------+
| [Display Area] |
|-----------------------------------|
|7|8|9|+ |
|4|5|6|- |
|1|2|3|* |
|0|%|/|= |
|-----------------------------------|
|[C] |
+-----------------------------------+
Example:
o Enter 8, press /, enter 0, press =
o Output: Error: Division by zero
Would you like me to make the calculator support decimal points and
continuous calculations (like real calculators do)?
ChatGPT can make mistakes. Check important info. See Cookie Preference