Java Programming Lab Practical Tasks
Java Programming Lab Practical Tasks
PRACTICAL FILE
Index
Serial Page Faculty
Program Date
No. No. Sign
WAP in Java to print the diamond structure as below by taking input
from user –
Example – Input: 7
Output:
1
212
32123
1. 4321234 7-10 14.11.25
32123
212
1
Also discuss the time complexity of your code. Please include
comments in your program for explaining the code.
Objective: To understand the basics of coding principles and pattern
printing.
WAP in Java to reverse a number. Write it in two ways –
a) Using while loop.
b) Using recursion.
c) Using StringBuilder class of Java.
Example –
i. Input: n = 357 Output: 753
2. ii. Input n = 100 Output: 1 (leading zeros are not considered) 11-13 14.11.25
Note: Leading zeros will not be considered after reversing (i.e. after
reversing 100 will become 001 ≈ 1).
Also discuss the time complexity of your code. Please include
comments in your program for explaining the code.
Objective: To understand basics of coding and integer manipulation
using loops and strings.
(i) Design a class to represent a bank account. Include the following
members:
Data members –
Name of the depositor
Account number
Type of account
Balance amount in the account
Methods –
3. 14-19 14.11.25
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
(ii) Modify the program to incorporate a constructor to provide initial
values.
Objective: To understand basic OOPs concept of classes,
encapsulation and constructors.
WAP to do binary search in Java. Take the input array and item to be
searched from the user. Discuss its time and space complexity.
4. 20-21 14.11.25
Objective: Writing searching code in Java and understanding time and
space complexity.
WAP to do merge sort in Java. Take the input array from the user.
Discuss its time and space complexity.
5. 22-24 14.11.25
Objective: Writing sorting code in Java and understanding time and
space complexity.
3
Output:
*
***
*****
*******
*********
(ii) Extend the above program to create two threads for printing the
pyramids for * and #. Synchronise the output such that it is not
distorted.
*
***
*****
*******
*********
#
###
#####
#######
#########
Objective: Understanding multithreading through creating multiple
threads and synchronizing them.
Define an exception called “NoMatchException” that is thrown when a
string is not equal to “India”. Write a program that uses this exception.
12. 46-47 14.11.25
Objective: Understanding exception handling through practical
implementation of catching an exception for user input.
Develop a GUI program to create a login form using:
(i) AWT
13. (ii) Swing 48-51 14.11.25
Objective: Implementing login form for understanding GUI creation
using AWT and Swing.
Develop a GUI that receives three numeric values as input from user
and display the largest of the 3 on the screen, using:
(i) AWT
(ii) Swing
Add input validation feature in the GUI by ensuring that all the fields
14. 52-57 14.11.25
are filled with valid numbers. Also keep tracking history by display a
list of previous inputs and results in the GUI.
Objective: Implementing processing data given by user through GUI
and some advance feature like input validation and storing history for
the inputs.
Develop Student Management System as per the chapter 15 “Graphics
Programming Using AWT, Swing and Layout Manager” (15.21) from
the book Programming with Java by E Balagurusamy.
15. 58-61 14.11.25
Objective: Implementing a complete Student Management system for
understanding using various features of GUI and creating a database
for processing.
Enter the temperature in Celsius from user using GUI with proper
labels and show the temperature in Fahrenheit. (Use AWT or/and
16. Swing and any layout). 62-63 14.11.25
Objective: Implementation practice using GUI for taking input from
user and process it.
Write a program to enter name, roll number and age from the user in
GUI format and on click of button display whether he is eligible to
17. 64-66 14.11.25
vote or not. (Use AWT or/and Swing and any layout) in your program
with example.
5
Y = {0 for x = 0
{-1 for x < 0
Using:
(a) nested if statements,
(b) else if statements, and
(c) conditional operator?:
Objective: Practicing processing some mathematical formula by user;
also implementing tertiary operator.
7
PRACTICAL -1
Aim: WAP in Java to print the diamond structure as below by taking input from user –
Example – Input: 7
Output:
1
212
32123
4321234
32123
212
1
Also discuss the time complexity of your code. Please include comments in your program for explaining the
code.
Code:
//inner loop for printing the left side pattern of upper half
for (int leftcol = row; leftcol >= 1; leftcol--) {
[Link](leftcol);
//this if block will only be executed if current row is not 1 , and the leftcol becomes 1
8
//for the lower half we will just do the opposite of above code
}
}
//inner loop for printing the left side pattern of upper half
for (int leftcol = row; leftcol >= 1; leftcol--) {
[Link](leftcol);
//this if block will only be executed if current row is not 1 , and the leftcol becomes 1
if (row != 1 && leftcol == 1) {
//this for loop inside inner for loop and if block
//will print the right half of the upper pattern
for (int rightcol = 2; rightcol <= row; rightcol++) {
[Link](rightcol);
9
}
}
}
[Link]();
//for the lower half we will just do the opposite of above code
}
}
}
10
Output:
Time Complexity:
The outer loops (for both upper and lower halves) run approximately n/2 times → O(n).
Inside each outer loop:
o The gap loop runs up to O(n) in the worst case.
o The leftcol + rightcol loops together also run up to O(n).
So, for each row, the total work is O(n), and since there are O(n) rows, the total time complexity
becomes:
𝑂(𝑛) × 𝑂(𝑛) = 𝑂(𝑛2 )
11
PRACTICAL -2
Aim: (i) Design a class to represent a bank account. Include the following members:
Data members –
Name of the depositor
Account number
Type of account
Balance amount in the account
Methods –
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
(ii) Modify the program to incorporate a constructor to provide initial values.
Code:
import [Link];
[Link]();
}
[Link]("reversed using while loop:" + rev);
}
if (n != 0) {
reverseRecursion(n, reverse);
} else {
[Link]("reversed using recursion:" + reverse);
}
}
}
}
13
Output:
Time Complexity:
Reversing using while loop → O(log₁₀ n) Iterates through each digit once using a while
loop.
Reversing using recursion → O(log₁₀ n) Recursively processes each digit, similar to the
while loop.
Reversing using StringBuilder class→ O(d) Where d is the number of digits. String
conversion and reversal both depend on digit count.
14
PRACTICAL -3
Aim: (i) Design a class to represent a bank account. Include the following members:
Data members –
Name of the depositor
Account number
Type of account
Balance amount in the account
Methods –
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
(ii) Modify the program to incorporate a constructor to provide initial values.
Code:
import [Link];
balance -= amount;
[Link]("Amount withdrawn successfully. New balance: " + balance);
} else if (amount > balance) {
[Link]("Insufficient balance.");
} else {
[Link]("Invalid withdrawal amount.");
}
}
}
}
if (choice == 1) {
// Part (i): Without Constructor
BankAccountWithoutConstructor account = new BankAccountWithoutConstructor();
switch (option) {
case 1:
[Link]("Enter amount to deposit: ");
amount = [Link]();
[Link](amount);
break;
case 2:
[Link]("Enter amount to withdraw: ");
amount = [Link]();
[Link](amount);
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice. Please try again.");
}
} while (option != 4);
} else if (choice == 2) {
// Part (ii): With Constructor
[Link]("Enter Depositor Name: ");
name = [Link]();
[Link]("Enter Account Number: ");
accNo = [Link]();
[Link](); // Consume newline
[Link]("Enter Account Type (e.g., Savings/Current): ");
type = [Link]();
[Link]("Enter Initial Balance: ");
initialBal = [Link]();
switch (option) {
case 1:
[Link]("Enter amount to deposit: ");
amount = [Link]();
[Link](amount);
break;
case 2:
[Link]("Enter amount to withdraw: ");
amount = [Link]();
[Link](amount);
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice. Please try again.");
}
} while (option != 4);
} else {
[Link]("Invalid selection.");
}
[Link]();
}
}
Output:
19
20
PRACTICAL -4
Aim: WAP to do binary search in Java. Take the input array and item to be searched from the user. Discuss
its time and space complexity.
Code:
import [Link];
// Display result
if (result == -1)
[Link]("Element not found in the array.");
else
[Link]("Element found at index: " + result);
[Link]();
}
if (arr[mid] == key)
21
Output:
PRACTICAL -5
Aim: WAP to do merge sort in Java. Take the input array from the user. Discuss its time and space
complexity.
Objective: Writing sorting code in Java and understanding time and space complexity.
Code:
import [Link];
[Link]();
}
}
}
Output:
Divide step: Each recursive call splits the array in half → log n levels.
Merge step: Each level merges all elements → O(n) work per level.
So total time = O(n log n) in all cases (best, average, worst).
Temporary arrays L[] and R[] are created during each merge.
In total, extra space proportional to the array size is used.
25
PRACTICAL -6
Code:
import [Link];
String s = [Link]();
return;
}
}
}
}
26
Output:
27
PRACTICAL -7
Code:
import [Link];
import [Link];
import [Link];
// Bubble sort
for (int i = 0; i < [Link]() - 1; i++) {
for (int j = i + 1; j < [Link](); j++) {
if ([Link](i).compareToIgnoreCase([Link](j)) > 0) { // Case-insensitive
String temp = [Link](i);
[Link](i, [Link](j));
[Link](j, temp);
}
}
}
28
[Link]();
}
}
Output:
29
PRACTICAL -8
Aim: WAP to read a text and count all the occurrences of a particular word.
Code:
import [Link];
// Input text
[Link]("Enter a line of text:");
String text = [Link]();
// Count occurrences
int count = 0;
for (String w : words) {
if ([Link](word)) {
count++;
}
}
// Display result
[Link]("The word \"" + word + "\" occurs " + count + " time(s) in the text.");
[Link]();
}
}
30
Output:
31
PRACTICAL -9
Aim: (i) WAP that accepts a shopping list of five items from the command line and stores them in a
vector.
(ii) Modify the program to accomplish the following:
a. To delete an item in the list.
b. To add an item at a specified location in the list.
c. To add an item at the end of the list.
d. To print the contents of the vector.
e. Display the total bill for all the items.
Objective: Understanding vectors in Java; creating, updating, adding and removing an element in vector.
Code:
import [Link];
import [Link];
import [Link];
if ([Link] != 5) {
[Link]("Please enter exactly 5 items as command-line arguments.");
return;
}
switch (choice) {
case 1:
[Link]("Enter the name of the item to delete: ");
String delItem = [Link]();
if ([Link](delItem)) {
[Link](delItem + " deleted from the list.");
} else {
[Link]("Item not found!");
}
break;
case 2:
[Link]("Enter item name to add: ");
String newItem = [Link]();
[Link]("Enter the position (0 to " + [Link]() + "): ");
int pos = [Link]();
[Link](); // clear buffer
if (pos >= 0 && pos <= [Link]()) {
[Link](pos, newItem);
[Link](newItem + " added at position " + pos);
} else {
[Link]("Invalid position!");
}
break;
case 3:
[Link]("Enter item name to add at end: ");
String endItem = [Link]();
[Link](endItem);
[Link](endItem + " added at the end of the list.");
break;
case 4:
[Link]("Current Shopping List: " + items);
break;
case 5:
[Link]("\nEnter the price for each item:");
double total = 0;
for (String item : items) {
[Link](item + " price: ");
double price = [Link]();
total += price;
}
[Link]("Total Bill = Rs." + total);
[Link](); // clear buffer
break;
33
case 6:
[Link]("Exiting... Thank you!");
[Link]();
return;
default:
[Link]("Invalid choice! Try again.");
}
}
}
}
Output:
34
35
PRACTICAL -10
Aim: (i) Assume that a bank maintains two kinds of account for its customers, one called savings account
and the other current account. The savings account provides compound interest and withdrawal facilities but
no cheque book facility. The current account provides cheque book facility but no interest. Current account
holders should also maintain a minimum balance and if the balance falls below this level, a service charge is
imposed.
Create a class Account that stores customer name, account number and type of account. From this derive
the class Curr-acct and Sav-acct to make them more specific to their requirements. Include the necessary
methods in order to achieve the following tasks:
(ii) Modify the above program to include constructors for all the three classes.
Code:
import [Link];
}
}
// b. Display balance
public void displayBalance() {
[Link]("Account Holder: " + name);
[Link]("Account Number: " + accountNumber);
[Link]("Account Type: " + type);
[Link]("Current Balance: " + balance);
}
class AccountWithConstructor {
protected String name;
protected int accountNumber;
protected String type;
protected double balance;
// Constructor
public AccountWithConstructor(String n, int accNo, String t, double bal) {
name = n;
accountNumber = accNo;
type = t;
balance = bal;
[Link]("Account initialized successfully.");
}
// b. Display balance
public void displayBalance() {
[Link]("Account Holder: " + name);
[Link]("Account Number: " + accountNumber);
[Link]("Account Type: " + type);
[Link]("Current Balance: " + balance);
}
String name;
int accNo;
double initialBal, amount;
if (mainChoice == 1) {
// Part (i): Without Constructors
[Link]("\n--- Part (i): Without Constructors ---");
[Link]("Choose account type - 1: Savings, 2: Current: ");
int accType = [Link]();
39
Object account = null; // Use Object for common interface, but handle separately
boolean isSavings = (accType == 1);
if (isSavings) {
Sav_acctWithoutConstructor sav = new Sav_acctWithoutConstructor();
[Link](name, accNo, "Savings", initialBal);
account = sav;
runMenu(sc, sav, true);
} else {
Curr_acctWithoutConstructor curr = new Curr_acctWithoutConstructor();
[Link](name, accNo, "Current", initialBal);
account = curr;
runMenu(sc, curr, false);
}
} else if (mainChoice == 2) {
// Part (ii): With Constructors
[Link]("\n--- Part (ii): With Constructors ---");
[Link]("Choose account type - 1: Savings, 2: Current: ");
int accType = [Link]();
[Link](); // Consume newline
if (isSavings) {
Sav_acctWithConstructor sav = new Sav_acctWithConstructor(name, accNo, initialBal);
runMenu(sc, sav, true);
} else {
Curr_acctWithConstructor curr = new Curr_acctWithConstructor(name, accNo, initialBal);
runMenu(sc, curr, false);
}
} else {
40
[Link]("Invalid selection.");
return;
}
[Link]();
}
switch (option) {
case 1:
[Link]("Enter amount to deposit: ");
double depAmt = [Link]();
[Link](depAmt);
break;
case 2:
[Link]("Enter amount to withdraw: ");
double wdAmt = [Link]();
[Link](wdAmt);
break;
case 3:
[Link]();
break;
case 4:
if (isSavings) {
((Sav_acctWithoutConstructor) account).computeInterest();
} else {
((Curr_acctWithoutConstructor) account).checkMinBalance();
}
break;
case 5:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice.");
}
41
switch (option) {
case 1:
[Link]("Enter amount to deposit: ");
double depAmt = [Link]();
[Link](depAmt);
break;
case 2:
[Link]("Enter amount to withdraw: ");
double wdAmt = [Link]();
[Link](wdAmt);
break;
case 3:
[Link]();
break;
case 4:
if (isSavings) {
((Sav_acctWithConstructor) account).computeInterest();
} else {
((Curr_acctWithConstructor) account).checkMinBalance();
}
break;
case 5:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice.");
}
} while (option != 5);
}}
42
Output:
43
PRACTICAL -11
Aim: (i) WAP a function draw_pyramid(char) that takes a character as input and prints a pyramid using
that character.
Example: draw_pyramid(‘*’)
Output:
*
***
*****
*******
*********
(ii) Extend the above program to create two threads for printing the pyramids for * and #. Synchronize the
output such that it is not distorted.
*
***
*****
*******
*********
#
###
#####
#######
#########
Objective: Understanding multithreading through creating multiple threads and synchronizing them.
Code:
(i)
import [Link];
[Link](ch);
}
[Link]();
}
}
}
Output:
(ii)
}
}
}
}
[Link]();
[Link]();
}
Output:
46
PRACTICAL -12
Aim: Define an exception called “NoMatchException” that is thrown when a string is not equal to “India”.
Write a program that uses this exception.
Code:
import [Link];
// Method that checks the string and throws NoMatchException if not "India"
public static void checkCountry(String country) throws NoMatchException {
if () {
throw new NoMatchException("Error with exception NoMatchException: '" + country + "' is not
equal to 'India'");
} else {
[Link]("Match found: The country is India.");
}
}
try {
checkCountry(input);
} catch (NoMatchException e) {
[Link]([Link]());
} finally {
[Link]();
}
47
}
}
Output:
48
PRACTICAL -13
Objective: Implementing login form for understanding GUI creation using AWT and Swing.
Code:
(i) AWT
import [Link].*;
import [Link].*;
public AWTLogin() {
// Set frame properties
setTitle("AWT Login Page");
setSize(300, 200);
setLayout(new GridLayout(4, 2, 5, 5));
setLocationRelativeTo(null);
// Create components
Label userLabel = new Label("Username:");
Label passLabel = new Label("Password:");
usernameField = new TextField();
passwordField = new TextField();
[Link]('*');
// Add components
add(userLabel);
add(usernameField);
add(passLabel);
add(passwordField);
add(new Label("")); // empty cell
add(loginButton);
add(messageLabel);
// Close window
addWindowListener(new WindowAdapter() {
49
setVisible(true);
}
Output:
50
Code:
(ii) Swing
import [Link].*;
import [Link].*;
import [Link].*;
public SwingLogin() {
// Set frame properties
setTitle("Swing Login Page");
setSize(350, 200);
setLayout(new GridLayout(4, 2, 5, 5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create components
JLabel userLabel = new JLabel("Username:");
JLabel passLabel = new JLabel("Password:");
usernameField = new JTextField();
passwordField = new JPasswordField();
JButton loginButton = new JButton("Login");
messageLabel = new JLabel("");
// Add components
add(userLabel);
add(usernameField);
add(passLabel);
add(passwordField);
add(new JLabel("")); // empty cell
add(loginButton);
add(messageLabel);
setVisible(true);
}
[Link]("Invalid Credentials");
}
}
Output:
52
PRACTICAL -14
Aim: Develop a GUI that receives three numeric values as input from user and display the largest of the 3
on the screen, using:
(i) AWT
(ii) Swing
Add input validation feature in the GUI by ensuring that all the fields are filled with valid numbers. Also
keep tracking history by display a list of previous inputs and results in the GUI.
Objective: Implementing processing data given by user through GUI and some advance feature like input
validation and storing history for the inputs.
Code:
(i) AWT
import [Link].*;
import [Link].*;
import [Link];
public LargestNumberAWT() {
history = new ArrayList<>();
setTitle("Largest Number Finder (AWT)");
setSize(500, 500);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(5, 5, 5, 5);
[Link] = [Link];
// Button
53
// Result Label
lblResult = new Label("Largest: ");
[Link]([Link]);
addComponent(lblResult, 0, 4, 2, 1, gbc);
// History Label
addComponent(new Label("History:"), 0, 5, gbc);
historyList = new List(10);
addComponent(historyList, 0, 6, 2, 1, gbc);
// Action Listener
[Link](e -> findLargest());
// Window Closing
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
setVisible(true);
}
private void addComponent(Component comp, int x, int y, int w, int h, GridBagConstraints gbc) {
[Link] = x;
[Link] = y;
[Link] = w;
[Link] = h;
add(comp, gbc);
}
// Validation
if ([Link]() || [Link]() || [Link]()) {
[Link]("Error: All fields are required!");
return;
}
n1 = [Link](s1);
n2 = [Link](s2);
n3 = [Link](s3);
} catch (NumberFormatException ex) {
[Link]("Error: Enter valid numbers only!");
return;
}
// Add to history
String entry = s1 + ", " + s2 + ", " + s3 + " → " + largest;
[Link](entry);
[Link](entry);
}
Output:
55
Code:
(ii) Swing
import [Link].*;
import [Link].*;
import [Link];
public LargestNumberSwing() {
setTitle("Largest Number Finder (Swing)");
setSize(550, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(8, 8, 8, 8);
[Link] = [Link];
// Input Fields
addRow("Number 1:", tf1 = new JTextField(15), 0, gbc);
addRow("Number 2:", tf2 = new JTextField(15), 1, gbc);
addRow("Number 3:", tf3 = new JTextField(15), 2, gbc);
// Button
JButton btn = new JButton("Find Largest");
[Link] = 2;
[Link] = 0;
[Link] = 3;
add(btn, gbc);
// Result
lblResult = new JLabel("Largest: ");
[Link](true);
[Link](new Color(255, 255, 180));
[Link](new Font("Arial", [Link], 14));
[Link] = 4;
add(lblResult, gbc);
// History
JLabel lblHistory = new JLabel("Calculation History:");
[Link] = 5;
add(lblHistory, gbc);
// Action
[Link](e -> findLargest());
setVisible(true);
}
private void addRow(String label, JComponent field, int row, GridBagConstraints gbc) {
[Link] = 0;
[Link] = row;
[Link] = 1;
add(new JLabel(label), gbc);
[Link] = 1;
add(field, gbc);
}
// Add to history
String entry = [Link]("%.2f, %.2f, %.2f → %.2f", n1, n2, n3, largest);
[Link](entry);
}
57
Output:
58
PRACTICAL -15
Aim: Develop Student Management System as per the chapter 15 “Graphics Programming Using AWT,
Swing and Layout Manager” (15.21) from the book Programming with Java by E Balagurusamy.
Objective: Implementing a complete Student Management system for understanding using various
features of GUI and creating a database for processing.
Code:
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link];
class Student {
String name, roll, course, grade;
Student(String name, String roll, String course, String grade) {
[Link] = name;
[Link] = roll;
[Link] = course;
[Link] = grade;
}
}
StudentManagementSystem() {
// ====== FRAME SETUP ======
setTitle(" Student Management System");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
[Link](nameLabel); [Link](nameField);
[Link](rollLabel); [Link](rollField);
[Link](courseLabel); [Link](courseField);
[Link](gradeLabel); [Link](gradeField);
[Link](addButton); [Link](clearButton);
add(formPanel, [Link]);
[Link](this);
[Link](this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == addButton) {
String name = [Link]().trim();
String roll = [Link]().trim();
String course = [Link]().trim();
String grade = [Link]().trim();
clearFields();
} else if ([Link]() == clearButton) {
clearFields();
[Link]("");
}
}
void clearFields() {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
}
new StudentManagementSystem();
}
}
61
Output:
62
PRACTICAL -16
Aim: Enter the temperature in Celsius from user using GUI with proper labels and show the temperature in
Fahrenheit. (Use AWT or/and Swing and any layout).
Objective: Implementation practice using GUI for taking input from user and process it.
Code:
import [Link].*;
import [Link].*;
import [Link].*;
public CelsiusToFahrenheitSwing() {
// Set up the frame
setTitle("Celsius to Fahrenheit Converter");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center on screen
[Link](lblCelsius);
[Link](txtCelsius);
[Link](btnConvert);
setVisible(true);
}
if ([Link]()) {
[Link]("Please enter a temperature!");
[Link]([Link]);
return;
}
try {
double celsius = [Link](input);
double fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
Output:
64
PRACTICAL -17
Aim: Write a program to enter name, roll number and age from the user in GUI format and on click of
button display whether he is eligible to vote or not. (Use AWT or/and Swing and any layout) in your
program with example.
Objective: Implementation practice using GUI for using various features in GUI.
Code:
import [Link].*;
import [Link].*;
import [Link].*;
public VotingEligibilitySwing() {
// Frame setup
setTitle("Voting Eligibility Checker");
setSize(450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout(15, 15));
[Link](new JLabel("Name:"));
txtName = new JTextField();
[Link](txtName);
[Link](new JLabel("Age:"));
txtAge = new JTextField();
[Link](txtAge);
setVisible(true);
}
// Validation
if ([Link]() || [Link]() || [Link]()) {
showResult("All fields are required!", [Link]);
return;
}
int age;
try {
age = [Link](ageStr);
if (age < 0 || age > 150) {
showResult("Age must be between 0 and 150!", [Link]);
return;
}
} catch (NumberFormatException ex) {
showResult("Age must be a valid number!", [Link]);
return;
}
// Check eligibility
String eligibility = (age >= 18)
? "<html><font color='green'><b>ELIGIBLE to vote!</b></font></html>"
: "<html><font color='red'><b>NOT eligible to vote.</b><br>Must be 18 or
above.</font></html>";
Output:
67
PRACTICAL -18
Aim: Write a program to load the MySQL JDBC driver and establish a connection to a MySQL database.
(The database class name for MySQL Connector/J is [Link])
Code:
import [Link];
import [Link];
import [Link];
try {
// Step 1: Load the MySQL JDBC driver
[Link]("[Link]");
[Link]("MySQL JDBC Driver loaded successfully.");
} catch (ClassNotFoundException e) {
[Link]("MySQL JDBC Driver not found. Ensure MySQL Connector/J is in the
classpath.");
[Link]();
} catch (SQLException e) {
[Link]("Error connecting to the database.");
[Link]();
} finally {
// Step 3: Close the connection
if (connection != null) {
try {
[Link]();
[Link]("Database connection closed.");
68
} catch (SQLException e) {
[Link]("Error closing the connection.");
[Link]();
}
}
}
}
}
Output:
69
PRACTICAL -19
Aim: Write a simple Java code example demonstrating how to establish a basic client-server
communication using TCP Sockets and UDP Datagram Sockets. Discuss the scenarios where each protocol
would be preferred.
Objective: Understanding the concept for establishing connection of client to the server using TCP and
UDP protocols.
Code:
import [Link].*;
import [Link].*;
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
TCP Client
This client connects to the server on port 8080, sends a message, reads the echoed response, and closes.
java
import [Link].*;
import [Link].*;
// Send to server
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Hello from TCP Client!");
Output:
(Server):
(Client):
71
import [Link].*;
import [Link];
while (true) {
[Link](receivePacket);
String message = new String([Link](), 0, [Link]());
[Link]("Received from " + [Link]() + ": " + message);
// Echo back
byte[] sendBuffer = ("Echo: " + message).getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, [Link],
[Link](), [Link]());
[Link](sendPacket);
}
} catch (IOException e) {
[Link]();
}
}
}
UDP Client
This client sends a message to the server on port 8080, receives the echoed response, and exits.
import [Link].*;
import [Link];
// Receive echo
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, [Link]);
72
[Link](receivePacket);
String response = new String([Link](), 0, [Link]());
[Link]("Server echoed: " + response);
} catch (IOException e) {
[Link]();
}
}
}
Output:
(Server):
(Client):
73
PRACTICAL -20
Aim: Write a simple Java code example demonstrating how to send a message using either a Socket (for
TCP) or a Datagram Socket (for UDP). Highlight the key classes and methods involved in each approach.
Objective: Understanding the concept for sending and receiving messages between client and server over
a Java network using TCP and UDP protocols.
Code:
import [Link].*;
import [Link].*;
// Send message
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Hello from TCP Sender!");
[Link]("Message sent via TCP.");
} catch (IOException e) {
[Link]();
}
}
}
Output:
74
PRACTICAL -21
Aim: Write a JSP program to generate and display the Fibonacci series on a webpage. (This program will
use a combination of JSP scriptlets and HTML to dynamically calculate and display the Fibonacci
sequence.)
Objective: Implementing JSP program for printing fibonacci series on a webpage using HTML.
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fibonacci Series</title>
</head>
<body>
<h2>Fibonacci Series Generator</h2>
<form method="post"> Enter the number of terms:
<input type="number" name="terms" min="1" required>
<input type="submit" value="Generate">
</form>
<hr>
<%
// Get the number of terms from the form
String termsStr = [Link]("terms"); if (termsStr != null) {
int n = [Link](termsStr); int first = 0, second = 1;
[Link]("</p>");
}
%>
</body>
</html>
75
Output:
76
Practical-22
Aim: Write a program to connect a JSP with a database in the backend. Assume the database name is the
same as username.
Objective: Understanding the concept of establishing a database connection through JSP program.
Code:
SQL
CREATE DATABASE your_username; USE your_username;
INSERT INTO students (name, age) VALUES ('Riya', 20), ('Amit', 22); JSP File
<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>
<html>
<head>
<title>Database Connection Example</title>
</head>
<body>
<h2>Student List from Database</h2>
<%
String url = "jdbc:mysql://localhost:3306/your_username"; // database name same as username String user =
"your_username"; // MySQL username
String password = "your_password"; // MySQL password
Connection con = null; Statement stmt = null; ResultSet rs = null;
try {
// Load MySQL JDBC Driver [Link]("[Link]");
// Establish connection
con = [Link](url, user, password);
// Create statement
stmt = [Link]();
// Execute query
rs = [Link]("SELECT * FROM students");
while([Link]()) { [Link]("<tr>");
[Link]("<td>" + [Link]("id") + "</td>"); [Link]("<td>" + [Link]("name") + "</td>");
[Link]("<td>" + [Link]("age") + "</td>"); [Link]("</tr>");
}
[Link]("</table>");
} catch(Exception e) {
[Link]("Error: " + [Link]());
} finally {
try { if(rs != null) [Link](); } catch(Exception e) {}
try { if(stmt != null) [Link](); } catch(Exception e) {} try { if(con != null) [Link](); } catch(Exception
e) {}
}
%>
</body>
</html>
Output:
78
Practical-23
Aim: Design a package called "Education” with classes like "Exam", "Assignment", etc. Write another
package called "Admission" with classes like "Student-Details", "Library", etc.
Write a program to demonstrate the following:
a) Display the results of the students.
b) Assignment submission details.
c) Library books taken/return in time.
d) What are the books taken from the library before the exam? Note: Create a menu-based design.
Objective: Understanding packages implementation and accessing data members between packages by
importing them.
Code:
package Education;
import [Link]; import [Link];
public class Exam {
private Map<String, Integer> results; // Student ID to score
public Exam() {
results = new HashMap<>();
}
package Admission;
public Library() {
booksTaken = new HashMap<>(); bookDates = new HashMap<>();
}
Output:
81
82
Practical-24
Aim: A cloth showroom has announced the following seasonal discounts on purchase of items:
Purchase Amount Discount
Mill cloth Handloom items
0-100 – 5.0%
101-200 5.0% 7.5%
201-300 7.5% 10.0%
Above 300 10.0% 15.0%
Write a program using switch and if statements to compute the net amount to be paid by a customer. import
[Link];
Objective:
Code:
public class ShowroomDiscount {
public static void main(String[] args) { Scanner sc = new Scanner([Link]);
// Input purchase details [Link]("Enter purchase amount: "); double amount = [Link]();
default:
[Link]("Invalid choice!"); [Link](0);
}
[Link]("Discount applied: " + discount + "%"); [Link]("Net amount to be paid: Rs. "
+ netAmount);
[Link]();
}
}
Output:
84
Practical-25
Aim: Write a program that will read the value of x and evaluate the following function:
{1 for x > 0 Y = {0 for x = 0
{-1 for x < 0 Using:
(a) nested if statements,
(b) else if statements, and
(c) conditional operator?:
Objective: Practicing processing some mathematical formula by user; also implementing tertiary operator.
Code:
import [Link];
// Input x
[Link]("Enter value of x: "); int x = [Link]();
// Select method
[Link]("Choose method to evaluate Y:"); [Link]("1. Nested if");
[Link]("2. Else if"); [Link]("3. Ternary operator"); [Link]("Enter choice
(1-3): ");
int choice = [Link]();
int y = 0; // variable to store Y switch (choice) {
case 1: // Nested if if (x >= 0) {
if (x == 0) { y = 0;
} else {
y = 1;
}
} else {
y = -1;
}
[Link]("Using nested if: Y = " + y); break;
default:
[Link]("Invalid choice! Please select 1, 2, or 3.");
}
[Link]();
}
}
Output:
Efficient computation of Fahrenheit from Celsius in Java's AWT/Swing GUI framework involves using event listeners to respond to user inputs in real-time. By setting up a JTextField for Celsius input and a JButton for conversion, the GUI captures user input and immediately processes it when the button is pressed. This process employs the formula Fahrenheit = (Celsius * 9/5) + 32. The converted temperature is displayed using a JLabel, offering instant feedback. Proper input validation ensures that users enter numeric values, preventing runtime errors. Thus, the user interface is responsive and error-resistant .
AWT and Swing are comprehensive libraries that facilitate GUI development in Java. AWT provides a basic set of components that are suitable for simple applications, while Swing components are more versatile and rich, offering greater customization options and a consistent look across platforms. For input validation, GUI applications can use event listeners to intercept user inputs and validate them before processing, providing immediate feedback to users. History tracking can be implemented using data structures that store previous inputs and results, which can then be displayed on the GUI, offering users a record of their interactions. This approach not only enhances user experience but also adds significant utility to GUI-based applications, making them more robust and user-friendly .
Constructors in Java provide a structured way to initialize object fields right at the time of creation, ensuring that objects are always in a valid state without needing a separate initialization method call. Unlike methods for assigning initial values, constructors enforce that initialization logic is executed as part of the object creation process, reducing errors and enhancing code maintainability. Methods can be called multiple times and do not inherently associate with object creation, which may lead to incomplete initialization. Constructors also allow for overloading, providing flexibility in how objects are instantiated with different initial states .
Conditional operators in Java, such as the ternary operator, are preferable in scenarios where simple, compact conditional assignments are needed. They are particularly useful for succinctly assigning values based on a condition within a single line, improving readability for straightforward conditions. However, nested if statements are more suitable for complex conditions with multiple branches and actions because they provide a clearer structure for such logic. While conditional operators reduce code length, overuse in complex scenarios can harm readability. Thus, selecting between them involves balancing concise logic expression with maintainability .
Java GUI applications can implement several strategies for effective input validation and feedback. Input validation can be accomplished using event listeners that check the input data type and range in real-time. For instance, JTextField input can be scrutinized using a DocumentFilter or InputVerifier to ensure proper data entry. Feedback mechanisms, such as changing the color of JLabel messages or using JOptionPane for alert dialogs, promptly inform users of incorrect inputs or successful validation. Additionally, disabling certain components until valid input is provided helps prevent processing errors, ensuring robust application flow and user satisfaction .
A menu-based design in a Java package offers a structured user interface that simplifies navigation through different functionalities. This design helps encapsulate various features under intuitive categories or options, improving user accessibility and reducing complexity. Additionally, a menu-based design can be easily adapted or extended with new options, making it flexible for future enhancements. It allows users to interact with the software in an organized manner, enhancing the overall user experience by minimizing decision fatigue and providing clear guidance on available actions .
When implementing client-server communication using TCP and UDP in Java, the choice of protocol depends on the application's requirements for reliability and performance. TCP provides a reliable connection-oriented service, ensuring that data is transmitted accurately in the correct order. It is suitable for applications like file transfers, email, and secure communications. On the other hand, UDP is a connectionless protocol that offers faster, non-guaranteed data transmission effective for applications where speed is crucial and occasional data loss is acceptable, such as live video streaming or online gaming. Java provides classes such as Socket for TCP and DatagramSocket for UDP, each with methods designed to facilitate their respective communication processes .
In Java applications, packages like "Education" and "Admission" categorize classes into coherent units, facilitating modular design and code reusability. The "Education" package can include classes such as "Exam" and "Assignment", which would handle student assessment data, while the "Admission" package might contain "StudentDetails" and "Library" classes to manage student records and library operations. Implementing these packages involves creating directories aligned with the package names and using the 'package' keyword at the beginning of each class file. This structured approach simplifies data management across applications, supports information encapsulation, and promotes maintainable and extensible code architecture .
Implementing a Student Management System using AWT, Swing, and Layout Manager involves several principles of graphics programming in Java. AWT and Swing components form the GUI's backbone, providing the necessary interactive elements. AWT offers essential components and lightweight interface design, while Swing extends functionality with rich, flexible options. Layout Managers enable the structured organization of components, adapting to various screen sizes and resolutions. A coherent Student Management System uses these tools to create a comprehensive interface that provides seamless navigation, data input, and results visualization, facilitating operations such as student record management and examination tracking. Employing MVC design patterns can further enhance maintainability by separating business logic from user interface design, ensuring scalability and ease of updates .
Exception handling in Java involves creating a robust structure to manage runtime errors. Custom exceptions, such as "NoMatchException", allow developers to define specific error conditions, improving error granularity and application robustness. When a user input does not match a predetermined condition, for instance, 'India' in this case, an instance of NoMatchException can be thrown, which can then be caught in a try-catch block. This approach isolates error handling logic and provides a way to gracefully inform users of input errors, avoiding application crashes and enhancing user experience .