0% found this document useful (0 votes)
6 views85 pages

Java Programming Lab Practical Tasks

The document outlines practical assignments for a Java Programming and Dynamic Webpage Design lab course as part of a Bachelor of Computer Application program. It includes various programming tasks such as pattern printing, data manipulation, object-oriented programming, GUI development, and database connectivity, along with objectives and expected outcomes for each task. The document serves as a guideline for students to complete their practical work and understand key programming concepts.

Uploaded by

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

Java Programming Lab Practical Tasks

The document outlines practical assignments for a Java Programming and Dynamic Webpage Design lab course as part of a Bachelor of Computer Application program. It includes various programming tasks such as pattern printing, data manipulation, object-oriented programming, GUI development, and database connectivity, along with objectives and expected outcomes for each task. The document serves as a guideline for students to complete their practical work and understand key programming concepts.

Uploaded by

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

1

PRACTICAL FILE

Practical Work of Java Programming and Dynamic Webpage Design


Lab
(BCA506)

Submitted in partial fulfilment of the requirement for the award of


Bachelor of Computer Application (BCA)
to
ASIAN SCHOOL OF BUSINESS, NOIDA
Affiliated to Ch. Charan Singh University, Meerut

Submitted to: Submitted by:


Prof. Anuradha Awasthi Naman Rai
Assistant Professor Univ. Roll No.: 230398000281

Batch – BCA 2023-26

ASIAN SCHOOL OF BUSINESS


Sector-125, Noida, G.B. Nagar (U.P.)
2

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

WAP to do the following:


a) To output the question “Who is the inventor of C++?”.
b) To accept and answer.
c) To print out “Good” and then stop, if the answer is correct.
6. d) To output message “try again”, if the answer is wrong. 25-26 14.11.25
e) To display the correct answer when the answer is wrong even at the
third attempt and stop.
Objective: Understanding simple user-interaction implementation
through code.
WAP to do alphabetical ordering of strings. Implement using
compareTo() function.
Example: Input – {"Madras”, “Delhi”, “Ahmedabad”, “Calcutta”,
7. 27-28 14.11.25
“Bombay”}
Output – Ahmedabad Bombay Calcutta Delhi Madras
Objective: Understanding string functions and processing.
WAP to read a text and count all the occurrences of a particular word.
8. Objective: Understanding string processing using data structure like 29-30 14.11.25
HashMap.
(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.
9. 31-34 14.11.25
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.
(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:
10. a. Accept deposit from a customer and update the balance. 35-42 14.11.25
b. Display the balance.
c. Compute and deposit interest.
d. Permit withdrawal and update the balance.
e. Check for the minimum balance, impose penalty, if necessary, and
update the balance.
Do not use any constructors. Use methods to initialize the class
members.
(ii) Modify the above program to include constructors for all the three
classes.
Objective: Understanding the concept of inheritance through a simple
application of banking.
(i) WAP a function draw_pyramid(char) that takes a character as
input and prints a pyramid using that character.
11. Example: draw_pyramid(‘*’) 43-45 14.11.25
4

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

Objective: Implementation practice using GUI for using various


features in GUI.
Write a program to load the MySQL JDBC driver and establish a
connection to a MySQL database. (The database class name for
18. MySQL Connector/J is [Link]) 67-68 14.11.25
Objective: Understanding the concept for connecting to JDBC
MYSQL database.
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
19. 69-72 14.11.25
be preferred.
Objective: Understanding the concept for establishing connection of
client to the server using TCP and UDP protocols.
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
20. approach. 73 14.11.25
Objective: Understanding the concept for sending and receiving
messages between client and server over a Java network using TCP
and UDP protocols.
Write a JSP program to generate and display the Fibonacci series on a
webpage. (This program will use a combination of JSP scriptlets and
21. HTML to dynamically calculate and display the Fibonacci sequence.) 74-75 14.11.25
Objective: Implementing JSP program for printing fibonacci series on
a webpage using HTML.
Write a program to connect a JSP with a database in the backend.
Assume the database name is the same as username.
22. 76-77 14.11.25
Objective: Understanding the concept of establishing a database
connection through JSP program.
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.
23. b) Assignment submission details. 78-81 14.11.25
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.
A cloth showroom has announced the following seasonal discounts on
purchase of items:
Discount
Purchase Amount
Mill cloth Handloom items
0-100 – 5.0%
101-200 5.0% 7.5%
24. 82-83 14.11.25
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.
Objective: Practicing processing statistical data by user for
computation.
Write a program that will read the value of x and evaluate the
25. following function: 84-85 14.11.25
{1 for x > 0
6

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.

Objective: To understand the basics of coding principles and pattern printing.

Code:

import [Link]; //importing Scanner class for user input

public class DiamondPattern {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]); //creating Scanner class object
[Link]("Please enter the length of Pattern you want...");
int n = [Link](); //taking user input and assigning it to variable n
Pattern(n); //calling the Pattern method with the input n
[Link]();

static void Pattern(int n) {

//outer for loop for the upper half of the pattern


for (int row = 1; row <= (n / 2) + 1; row++) {
//inner loop for printing/giving the gap or spaces
for (int gap = 0; gap <= (n / 2) - row; gap++) {
[Link](" ");
}

//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

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);
}
}
}
[Link]();

//for the lower half we will just do the opposite of above code

for (int row = (n / 2); row >= 1; row--) {


for (int gap = (n / 2) - row; gap >= 0; gap--) {
[Link](" ");
}
for (int leftcol = row; leftcol >= 1; leftcol--) {
[Link](leftcol);
if (leftcol == 1) {
for (int rightcol = 2; rightcol <= row; rightcol++) {
[Link](rightcol);
}
}
}
[Link]();

}
}

static void Pattern2(int n) {

//outer for loop for the upper half of the pattern


for (int row = 1; row < (n / 2) + 1; row++) {
//inner loop for printing/giving the gap or spaces
for (int gap = 0; gap <= (n / 2) - row; gap++) {
[Link](" ");
}

//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

for (int row = (n / 2); row >= 1; row--) {


for (int gap = (n / 2) - row; gap >= 0; gap--) {
[Link](" ");
}
for (int leftcol = row; leftcol >= 1; leftcol--) {
[Link](leftcol);
if (leftcol == 1) {
for (int rightcol = 2; rightcol <= row; rightcol++) {
[Link](rightcol);
}
}
}
[Link]();

}
}
}
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.

Objective: To understand basic OOPs concept of classes, encapsulation and constructors.

Code:

import [Link];

public class Reverse {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


[Link]("Enter the number to reverse:");//taking input from user
int n = [Link]();

//[Link] the method which uses while loop to reverse


reverseWhile(n);

//this variable I have only used for reversing using recursion(2)


int reverse = 0;
//[Link] the method which uses recursion to reverse
reverseRecursion(n, reverse);

//[Link] StringBuilder class


reverseStringBuilder(n);

[Link]();

static void reverseWhile(int n) {


int rev = 0;
while (n != 0) {
12

rev = (rev * 10) + (n % 10);


n = n / 10;

}
[Link]("reversed using while loop:" + rev);
}

static void reverseRecursion(int n, int reverse) {

reverse = (reverse * 10) + (n % 10);


n = n / 10;

if (n != 0) {
reverseRecursion(n, reverse);
} else {
[Link]("reversed using recursion:" + reverse);

}
}

static void reverseStringBuilder(int n) {

//converting the number to a String


String numberAsString = [Link](n);

//creating a StringBuilder object and passing the String as constructor argument


StringBuilder sb = new StringBuilder(numberAsString);

//reversing the StringBuilder


[Link]();

//converting back to an integer


int rev = [Link]([Link]());

[Link]("reversed using StringBuilder:" + rev);

}
}
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.

Objective: To understand basic OOPs concept of classes, encapsulation and constructors.

Code:

import [Link];

// Part (i): Class without constructor, using assign method


class BankAccountWithoutConstructor {
private String name;
private int accountNumber;
private String accountType;
private double balance;

// Method to assign initial values


public void assign(String n, int accNo, String type, double bal) {
name = n;
accountNumber = accNo;
accountType = type;
balance = bal;
}

// Method to deposit an amount


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Amount deposited successfully. New balance: " + balance);
} else {
[Link]("Invalid deposit amount.");
}
}

// Method to withdraw an amount after checking balance


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
15

balance -= amount;
[Link]("Amount withdrawn successfully. New balance: " + balance);
} else if (amount > balance) {
[Link]("Insufficient balance.");
} else {
[Link]("Invalid withdrawal amount.");
}
}

// Method to display name and balance


public void display() {
[Link]("Depositor Name: " + name);
[Link]("Balance: " + balance);
[Link]("Account Type: " + accountType);
}
}

// Part (ii): Modified class with constructor


class BankAccountWithConstructor {
private String name;
private int accountNumber;
private String accountType;
private double balance;

// Constructor to provide initial values


public BankAccountWithConstructor(String n, int accNo, String type, double bal) {
name = n;
accountNumber = accNo;
accountType = type;
balance = bal;
}

// Method to deposit an amount


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Amount deposited successfully. New balance: " + balance);
} else {
[Link]("Invalid deposit amount.");
}
}

// Method to withdraw an amount after checking balance


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Amount withdrawn successfully. New balance: " + balance);
} else if (amount > balance) {
[Link]("Insufficient balance.");
} else {
[Link]("Invalid withdrawal amount.");
16

}
}

// Method to display name and balance


public void display() {
[Link]("hello");
[Link]("Depositor Name: " + name);
[Link]("Balance: " + balance);
[Link]("Account Type: " + accountType);
}
}

public class BankAccountDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int choice;

[Link]("Choose which version to run:");


[Link]("1. Part (i) - Without Constructor");
[Link]("2. Part (ii) - With Constructor");
choice = [Link]();
[Link](); // Consume newline

String name, type;


int accNo;
double initialBal, amount;

if (choice == 1) {
// Part (i): Without Constructor
BankAccountWithoutConstructor account = new BankAccountWithoutConstructor();

// Take user input for initial values


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

// Assign initial values


[Link](name, accNo, type, initialBal);

// Interactive menu using switch


int option;
do {
[Link]("\nMenu:");
[Link]("1. Deposit Amount");
[Link]("2. Withdraw Amount");
17

[Link]("3. Display Name , Balance and Account Type");


[Link]("4. Exit");
[Link]("Enter your choice: ");
option = [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 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]();

// Create object using constructor


BankAccountWithConstructor account = new BankAccountWithConstructor(name, accNo, type,
initialBal);

// Interactive menu using switch


int option;
do {
[Link]("\nMenu:");
[Link]("1. Deposit Amount");
[Link]("2. Withdraw Amount");
[Link]("3. Display Name , Balance and Account Type");
[Link]("4. Exit");
18

[Link]("Enter your choice: ");


option = [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.

Objective: To understand basic OOPs concept of classes, encapsulation and constructors.

Code:

import [Link];

public class BinarySearch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input array size


[Link]("Enter the number of elements: ");
int n = [Link]();
int[] arr = new int[n];

// Input sorted array


[Link]("Enter " + n + " sorted elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Input element to search


[Link]("Enter the element to search: ");
int key = [Link]();

// Perform binary search


int result = binarySearch(arr, key);

// Display result
if (result == -1)
[Link]("Element not found in the array.");
else
[Link]("Element found at index: " + result);

[Link]();
}

// Binary search method


static int binarySearch(int[] arr, int key) {
int low = 0, high = [Link] - 1;

while (low <= high) {


int mid = low + (high - low) / 2; // prevents overflow

if (arr[mid] == key)
21

return mid; // element found


else if (arr[mid] < key)
low = mid + 1; // search in right half
else
high = mid - 1; // search in left half
}
return -1; // element not found
}
}

Output:

Time Complexity: O(log n)

 Binary search divides the array in half each iteration.


 In the worst case, it performs about log₂(n) comparisons.
 Efficient for sorted arrays.

Space Complexity: O(1)

 Uses a constant amount of extra space:


 Variables like low, high, mid, and key.
 No recursion or additional data structures.
22

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];

public class MergeSort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input array size


[Link]("Enter the number of elements: ");
int n = [Link]();
int[] arr = new int[n];

// Input array elements


[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Perform merge sort


mergeSort(arr, 0, n - 1);

// Display sorted array


[Link]("Sorted array:");
for (int num : arr) {
[Link](num + " ");
}

[Link]();
}

// Merge sort function


static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;

// Divide the array into two halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
23

}
}

// Merge two sorted subarrays


static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

// Create temporary arrays


int[] L = new int[n1];
int[] R = new int[n2];

// Copy data to temp arrays


for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// Merge the temp arrays


int i = 0, j = 0, k = left;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy remaining elements (if any)


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}
24

Output:

Time Complexity: O(n log n)

 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).

Space Complexity: O(n)

 Temporary arrays L[] and R[] are created during each merge.
 In total, extra space proportional to the array size is used.
25

PRACTICAL -6

Aim: WAP to do the following:


a) To output the question “Who is the inventor of C++?”.
b) To accept and answer.
c) To print out “Good” and then stop, if the answer is correct.
d) To output message “try again”, if the answer is wrong.
e) To display the correct answer when the answer is wrong even at the third attempt and stop.

Objective: Understanding simple user-interaction implementation through code.

Code:
import [Link];

public class QuestionAnswer {


public static void main(String[] args) {
String answer = "Bjarne Stroustrup";
[Link]("Who is the inventor of C++ ??");

Scanner sc = new Scanner([Link]);

for (int attempt = 1; attempt <= 3; attempt++) {

String s = [Link]();

if (attempt <= 3 && [Link](answer)) {


[Link]("Good!");
return;
} else if (attempt <= 2 && [Link](answer) == false) {
[Link]("try again");
continue;
} else if (attempt == 3 && [Link](answer) == false) {
[Link]("Sorry!! correct answer is:" + answer);

return;
}

}
}
}
26

Output:
27

PRACTICAL -7

Aim: WAP to do alphabetical ordering of strings. Implement using compareTo() function.

Example: Input – {"Madras”, “Delhi”, “Ahmedabad”, “Calcutta”, “Bombay”}


Output – Ahmedabad Bombay Calcutta Delhi Madras

Objective: Understanding String functions and processing

Code:
import [Link];
import [Link];
import [Link];

public class AlphabeticalSorting {


public static void main(String[] args) {

ArrayList<String> city = new ArrayList<>();


Scanner sc = new Scanner([Link]);

[Link]("Enter the number of cities you want to sort: ");


int count = [Link]();

// Consume the leftover newline after nextInt()


[Link]();

[Link]("Enter the names of " + count + " cities:");


for(int i = 0; i < count; i++) {
String name = [Link]().trim(); // trim() removes extra spaces
if (![Link]()) { // optional: prevent empty entries
[Link](name);
} else {
[Link]("Empty input! Please re-enter:");
i--; // repeat this iteration
}
}

[Link]("\nBefore sorting: " + city);

// 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]("After sorting: " + city);

[Link]();
}
}

Output:
29

PRACTICAL -8

Aim: WAP to read a text and count all the occurrences of a particular word.

Objective: Understanding string processing using data structure like HashMap.

Code:

import [Link];

public class WordCount {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input text
[Link]("Enter a line of text:");
String text = [Link]();

// Input word to search


[Link]("Enter the word to count: ");
String word = [Link]();

// Convert both to lowercase for case-insensitive comparison


text = [Link]();
word = [Link]();

// Split text into words


String[] words = [Link]("\\W+"); // Split by non-word characters (punctuation, spaces)

// 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];

public class ShoppingList {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// (i) Accept a shopping list of 5 items from the command line


Vector<String> items = new Vector<>();

if ([Link] != 5) {
[Link]("Please enter exactly 5 items as command-line arguments.");

return;
}

// Add the 5 items from command line to the vector


for (String item : args) {
[Link](item);
}

[Link]("Initial Shopping List: " + items);

// (ii) Modify the program to perform operations


while (true) {
[Link]("\n--- MENU ---");
[Link]("1. Delete an item");
[Link]("2. Add an item at a specific location");
[Link]("3. Add an item at the end");
[Link]("4. Print the shopping list");
[Link]("5. Display total bill");
[Link]("6. Exit");
32

[Link]("Enter your choice: ");


int choice = [Link]();
[Link](); // clear buffer

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:

a. Accept deposit from a customer and update the balance.


b. Display the balance.
c. Compute and deposit interest.
d. Permit withdrawal and update the balance.
e. Check for the minimum balance, impose penalty, if necessary, and update the balance.
Do not use any constructors. Use methods to initialize the class members.

(ii) Modify the above program to include constructors for all the three classes.

Objective: Understanding the concept of inheritance through a simple application of banking.

Code:
import [Link];

// Part (i): Without Constructors - Use init() methods


class AccountWithoutConstructor {
protected String name;
protected int accountNumber;
protected String type;
protected double balance;

// Method to initialize (no constructor)


public void init(String n, int accNo, String t, double bal) {
name = n;
accountNumber = accNo;
type = t;
balance = bal;
[Link]("Account initialized successfully.");
}

// a. Accept deposit and update balance


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount + ". New balance: " + balance);
} else {
[Link]("Invalid deposit amount.");
36

}
}

// b. Display balance
public void displayBalance() {
[Link]("Account Holder: " + name);
[Link]("Account Number: " + accountNumber);
[Link]("Account Type: " + type);
[Link]("Current Balance: " + balance);
}

// d. Permit withdrawal and update balance


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount + ". New balance: " + balance);
} else {
[Link]("Invalid withdrawal amount or insufficient balance.");
}
}
}

class Sav_acctWithoutConstructor extends AccountWithoutConstructor {


private double interestRate = 0.05; // 5% annual interest (assumed)

// c. Compute and deposit interest


public void computeInterest() {
double interest = balance * interestRate;
deposit(interest);
[Link]("Interest computed and added: " + interest);
}
}

class Curr_acctWithoutConstructor extends AccountWithoutConstructor {


private double minBalance = 1000.0;
private double serviceCharge = 50.0;

// e. Check minimum balance, impose penalty if necessary, update balance


public void checkMinBalance() {
if (balance < minBalance) {
balance -= serviceCharge;
[Link]("Balance below minimum (" + minBalance + "). Service charge imposed: " +
serviceCharge);
[Link]("Updated balance: " + balance);
} else {
[Link]("Balance is above minimum. No charge.");
}
}
}

// Part (ii): With Constructors


37

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.");
}

// a. Accept deposit and update balance


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount + ". New balance: " + balance);
} else {
[Link]("Invalid deposit amount.");
}
}

// b. Display balance
public void displayBalance() {
[Link]("Account Holder: " + name);
[Link]("Account Number: " + accountNumber);
[Link]("Account Type: " + type);
[Link]("Current Balance: " + balance);
}

// d. Permit withdrawal and update balance


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount + ". New balance: " + balance);
} else {
[Link]("Invalid withdrawal amount or insufficient balance.");
}
}
}

class Sav_acctWithConstructor extends AccountWithConstructor {


private double interestRate = 0.05; // 5% annual interest (assumed)

// Constructor calls super


public Sav_acctWithConstructor(String n, int accNo, double bal) {
super(n, accNo, "Savings", bal);
}
38

// c. Compute and deposit interest


public void computeInterest() {
double interest = balance * interestRate;
deposit(interest);
[Link]("Interest computed and added: " + interest);
}
}

class Curr_acctWithConstructor extends AccountWithConstructor {


private double minBalance = 1000.0;
private double serviceCharge = 50.0;

// Constructor calls super


public Curr_acctWithConstructor(String n, int accNo, double bal) {
super(n, accNo, "Current", bal);
}

// e. Check minimum balance, impose penalty if necessary, update balance


public void checkMinBalance() {
if (balance < minBalance) {
balance -= serviceCharge;
[Link]("Balance below minimum (" + minBalance + "). Service charge imposed: " +
serviceCharge);
[Link]("Updated balance: " + balance);
} else {
[Link]("Balance is above minimum. No charge.");
}
}
}

public class BankAccountSystem {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int mainChoice;

[Link]("Choose which version to run:");


[Link]("1. Part (i) - Without Constructors (use init() method)");
[Link]("2. Part (ii) - With Constructors");
mainChoice = [Link]();
[Link](); // Consume newline

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

[Link](); // Consume newline

[Link]("Enter Account Holder Name: ");


name = [Link]();
[Link]("Enter Account Number: ");
accNo = [Link]();
[Link](); // Consume newline
[Link]("Enter Initial Balance: ");
initialBal = [Link]();

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

[Link]("Enter Account Holder Name: ");


name = [Link]();
[Link]("Enter Account Number: ");
accNo = [Link]();
[Link](); // Consume newline
[Link]("Enter Initial Balance: ");
initialBal = [Link]();

boolean isSavings = (accType == 1);

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

// Common menu method (overloaded for different classes)


public static void runMenu(Scanner sc, AccountWithoutConstructor account, boolean isSavings) {
int option;
do {
[Link]("\n--- Menu ---");
[Link]("1. Deposit Amount");
[Link]("2. Withdraw Amount");
[Link]("3. Display Account Details");
if (isSavings) {
[Link]("4. Compute and Deposit Interest");
} else {
[Link]("4. Check Minimum Balance & Impose Penalty");
}
[Link]("5. Exit");
[Link]("Enter choice: ");
option = [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

} while (option != 5);


}

// Overload for Part (ii)


public static void runMenu(Scanner sc, AccountWithConstructor account, boolean isSavings) {
int option;
do {
[Link]("\n--- Menu ---");
[Link]("1. Deposit Amount");
[Link]("2. Withdraw Amount");
[Link]("3. Display Account Details");
if (isSavings) {
[Link]("4. Compute and Deposit Interest");
} else {
[Link]("4. Check Minimum Balance & Impose Penalty");
}
[Link]("5. Exit");
[Link]("Enter choice: ");
option = [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_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];

public class PyramidPattern {

public static void main(String[] args) {


[Link]("enter the character which you want as the pattern:");
Scanner sc = new Scanner([Link]);
char ch = [Link]().charAt(0);
draw_pyramid(ch);
}

static synchronized void draw_pyramid(char ch) {


for (int row = 1; row <= 5; row++) {
for (int gap = 0; gap <= 5 - row; gap++) {
[Link](" ");
}
for (int col = 1; col <= 2 * row - 1; col++) {
44

[Link](ch);
}
[Link]();
}
}
}

Output:

(ii)

class MyThread1 extends Thread {


@Override
public void run() {

char ch1 = '*';


PyramidPattern.draw_pyramid(ch1);

}
}

class MyThread2 extends Thread {


@Override
public void run() {

char ch2 = '#';


PyramidPattern.draw_pyramid(ch2);

}
}

public class SynchronizedPattern {


45

public static void main(String[] args) {

MyThread1 t1 = new MyThread1();


MyThread2 t2 = new MyThread2();

//setting priority so that our pattern gets always always executed


//such that * patterns are printed before #
[Link](10);

[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.

Objective: Understanding exception handling through practical implementation of catching an exception


for user input.

Code:
import [Link];

// Step 1: Define the custom exception class


class NoMatchException extends Exception {
// Default constructor
public NoMatchException() {
super("NoMatchException: String is not equal to 'India'");
}

// Parameterized constructor with custom message


public NoMatchException(String message) {
super(message);
}
}

public class NoMatchExceptionDemo {

// Method that checks the string and throws NoMatchException if not "India"
public static void checkCountry(String country) throws NoMatchException {
if (![Link]("India")) {
throw new NoMatchException("Error with exception NoMatchException: '" + country + "' is not
equal to 'India'");
} else {
[Link]("Match found: The country is India.");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter a country name: ");


String input = [Link]();

try {
checkCountry(input);
} catch (NoMatchException e) {
[Link]([Link]());
} finally {
[Link]();
}
47

}
}

Output:
48

PRACTICAL -13

Aim: Develop a GUI program to create a login form using:


(i) AWT
(ii) Swing

Objective: Implementing login form for understanding GUI creation using AWT and Swing.

Code:

(i) AWT

import [Link].*;
import [Link].*;

public class AWTLogin extends Frame implements ActionListener {


TextField usernameField, passwordField;
Label messageLabel;

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

Button loginButton = new Button("Login");


messageLabel = new Label("");

// Add components
add(userLabel);
add(usernameField);
add(passLabel);
add(passwordField);
add(new Label("")); // empty cell
add(loginButton);
add(messageLabel);

// Register action listener


[Link](this);

// Close window
addWindowListener(new WindowAdapter() {
49

public void windowClosing(WindowEvent e) {


dispose();
}
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String username = [Link]();
String password = [Link]();

if ([Link]("admin") && [Link]("1234")) {


[Link]("Login Successful!");
} else {
[Link]("Invalid Credentials");
}
}

public static void main(String[] args) {


new AWTLogin();
}
}

Output:
50

Code:

(ii) Swing

import [Link].*;
import [Link].*;
import [Link].*;

public class SwingLogin extends JFrame implements ActionListener {


JTextField usernameField;
JPasswordField passwordField;
JLabel messageLabel;

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);

// Register action listener


[Link](this);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String username = [Link]();
String password = new String([Link]());

if ([Link]("admin") && [Link]("1234")) {


[Link]("Login Successful!");
} else {
51

[Link]("Invalid Credentials");
}
}

public static void main(String[] args) {


new SwingLogin();
}
}

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 class LargestNumberAWT extends Frame {


private TextField tf1, tf2, tf3;
private Label lblResult;
private List historyList;
private ArrayList<String> history;

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];

// Labels and TextFields


addComponent(new Label("Number 1:"), 0, 0, gbc);
tf1 = new TextField(15);
addComponent(tf1, 1, 0, gbc);

addComponent(new Label("Number 2:"), 0, 1, gbc);


tf2 = new TextField(15);
addComponent(tf2, 1, 1, gbc);

addComponent(new Label("Number 3:"), 0, 2, gbc);


tf3 = new TextField(15);
addComponent(tf3, 1, 2, gbc);

// Button
53

Button btn = new Button("Find Largest");


addComponent(btn, 0, 3, 2, 1, gbc);

// 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, GridBagConstraints gbc) {


addComponent(comp, x, y, 1, 1, gbc);
}

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

private void findLargest() {


String s1 = [Link]().trim();
String s2 = [Link]().trim();
String s3 = [Link]().trim();

// Validation
if ([Link]() || [Link]() || [Link]()) {
[Link]("Error: All fields are required!");
return;
}

double n1, n2, n3;


try {
54

n1 = [Link](s1);
n2 = [Link](s2);
n3 = [Link](s3);
} catch (NumberFormatException ex) {
[Link]("Error: Enter valid numbers only!");
return;
}

double largest = [Link]([Link](n1, n2), n3);


[Link]("Largest: " + largest);

// Add to history
String entry = s1 + ", " + s2 + ", " + s3 + " → " + largest;
[Link](entry);
[Link](entry);
}

public static void main(String[] args) {


new LargestNumberAWT();
}
}

Output:
55

Code:

(ii) Swing

import [Link].*;
import [Link].*;
import [Link];

public class LargestNumberSwing extends JFrame {


private JTextField tf1, tf2, tf3;
private JLabel lblResult;
private DefaultListModel<String> historyModel;
private JList<String> historyList;

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);

historyModel = new DefaultListModel<>();


historyList = new JList<>(historyModel);
JScrollPane scrollPane = new JScrollPane(historyList);
56

[Link](new Dimension(400, 150));


[Link] = 6;
add(scrollPane, 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);
}

private void findLargest() {


String s1 = [Link]().trim();
String s2 = [Link]().trim();
String s3 = [Link]().trim();

if ([Link]() || [Link]() || [Link]()) {


[Link]("Error: All fields required!");
[Link]([Link]);
return;
}

double n1, n2, n3;


try {
n1 = [Link](s1);
n2 = [Link](s2);
n3 = [Link](s3);
} catch (NumberFormatException ex) {
[Link]("Error: Invalid number format!");
[Link]([Link]);
return;
}

double largest = [Link]([Link](n1, n2), n3);


[Link]("Largest: " + largest);
[Link]([Link]);

// Add to history
String entry = [Link]("%.2f, %.2f, %.2f → %.2f", n1, n2, n3, largest);
[Link](entry);
}
57

public static void main(String[] args) {


[Link](LargestNumberSwing::new);
}
}

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;
}
}

public class StudentManagementSystem extends JFrame implements ActionListener {


// UI Components
JLabel title, nameLabel, rollLabel, courseLabel, gradeLabel, msgLabel;
JTextField nameField, rollField, courseField, gradeField;
JButton addButton, clearButton;
JTable table;
DefaultTableModel model;

ArrayList<Student> students = new ArrayList<>();

StudentManagementSystem() {
// ====== FRAME SETUP ======
setTitle(" Student Management System");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));

// ====== TITLE ======


title = new JLabel("Student Management System", [Link]);
[Link](new Font("Poppins", [Link], 22));
[Link](new Color(0, 102, 204));
add(title, [Link]);
59

// ====== FORM PANEL ======


JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));
[Link]([Link]("Enter Student Details"));
[Link](new Color(240, 248, 255));

nameLabel = new JLabel("Name:");


rollLabel = new JLabel("Roll No:");
courseLabel = new JLabel("Course:");
gradeLabel = new JLabel("Grade:");

nameField = new JTextField();


rollField = new JTextField();
courseField = new JTextField();
gradeField = new JTextField();

addButton = new JButton(" Add Student");


clearButton = new JButton("Clear");
msgLabel = new JLabel("");

[Link](new Color(51, 153, 255));


[Link]([Link]);
[Link](new Color(255, 102, 102));
[Link]([Link]);

[Link](nameLabel); [Link](nameField);
[Link](rollLabel); [Link](rollField);
[Link](courseLabel); [Link](courseField);
[Link](gradeLabel); [Link](gradeField);
[Link](addButton); [Link](clearButton);

add(formPanel, [Link]);

// ====== TABLE SECTION ======


String[] columns = {"Name", "Roll No", "Course", "Grade"};
model = new DefaultTableModel(columns, 0);
table = new JTable(model);
[Link](true);
[Link](new Font("SansSerif", [Link], 14));
[Link](25);
[Link](new Color(200, 230, 255));

JScrollPane scrollPane = new JScrollPane(table);


[Link]([Link]("Student Records"));
add(scrollPane, [Link]);

// ====== MESSAGE BAR ======


JPanel msgPanel = new JPanel();
[Link](msgLabel);
add(msgPanel, [Link]);

// ====== EVENT HANDLING ======


60

[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();

if ([Link]() || [Link]() || [Link]() || [Link]()) {


[Link]([Link]);
[Link](" Please fill all fields!");
return;
}

Student s = new Student(name, roll, course, grade);


[Link](s);

[Link](new Object[]{name, roll, course, grade});


[Link](new Color(0, 153, 0));
[Link](" Student added successfully!");

clearFields();
} else if ([Link]() == clearButton) {
clearFields();
[Link]("");
}
}

void clearFields() {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
}

public static void main(String[] args) {


// Use a nicer theme
try { [Link]("[Link]"); }
catch (Exception ignored) {}

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 class CelsiusToFahrenheitSwing extends JFrame {


private JTextField txtCelsius;
private JLabel lblResult;
private JButton btnConvert;

public CelsiusToFahrenheitSwing() {
// Set up the frame
setTitle("Celsius to Fahrenheit Converter");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center on screen

// Use BorderLayout for main structure


setLayout(new BorderLayout(10, 10));

// === Top Panel: Input ===


JPanel inputPanel = new JPanel(new FlowLayout());
[Link]([Link](20, 20, 10, 20));

JLabel lblCelsius = new JLabel("Temperature in Celsius:");


txtCelsius = new JTextField(10);
btnConvert = new JButton("Convert");

[Link](lblCelsius);
[Link](txtCelsius);
[Link](btnConvert);

// === Center: Result ===


lblResult = new JLabel("Fahrenheit: ", [Link]);
[Link](new Font("Arial", [Link], 16));
[Link](new Color(0, 100, 200));

// === Add panels to frame ===


add(inputPanel, [Link]);
add(lblResult, [Link]);

// === Event Handling using Lambda ===


63

[Link](e -> convertTemperature());

// Optional: Press Enter in text field


[Link](e -> convertTemperature());

setVisible(true);
}

private void convertTemperature() {


String input = [Link]().trim();

if ([Link]()) {
[Link]("Please enter a temperature!");
[Link]([Link]);
return;
}

try {
double celsius = [Link](input);
double fahrenheit = (celsius * 9.0 / 5.0) + 32.0;

[Link]([Link]("Fahrenheit: %.2f °F", fahrenheit));


[Link](new Color(0, 120, 0)); // Green for success
} catch (NumberFormatException ex) {
[Link]("Invalid number! Enter digits only.");
[Link]([Link]);
}
}

public static void main(String[] args) {


// Run on Event Dispatch Thread
[Link](CelsiusToFahrenheitSwing::new);
}
}

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 class VotingEligibilitySwing extends JFrame {


private JTextField txtName, txtRollNo, txtAge;
private JLabel lblResult;
private JButton btnCheck;

public VotingEligibilitySwing() {
// Frame setup
setTitle("Voting Eligibility Checker");
setSize(450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout(15, 15));

// === Input Panel (Top) ===


JPanel inputPanel = new JPanel();
[Link](new GridLayout(3, 2, 10, 10));
[Link]([Link](20, 30, 10, 30));

[Link](new JLabel("Name:"));
txtName = new JTextField();
[Link](txtName);

[Link](new JLabel("Roll Number:"));


txtRollNo = new JTextField();
[Link](txtRollNo);

[Link](new JLabel("Age:"));
txtAge = new JTextField();
[Link](txtAge);

// === Button Panel ===


JPanel buttonPanel = new JPanel(new FlowLayout());
btnCheck = new JButton("Check Eligibility");
[Link](new Font("Arial", [Link], 14));
[Link](btnCheck);
65

// === Result Label (Center) ===


lblResult = new JLabel("Fill details and click Check", [Link]);
[Link](new Font("Arial", [Link], 16));
[Link]([Link](10, 20, 20, 20));

// === Add panels to frame ===


add(inputPanel, [Link]);
add(buttonPanel, [Link]);
add(lblResult, [Link]);

// === Event Handling ===


[Link](e -> checkVotingEligibility());

// Allow Enter key in Age field


[Link](e -> checkVotingEligibility());

setVisible(true);
}

private void checkVotingEligibility() {


String name = [Link]().trim();
String rollNo = [Link]().trim();
String ageStr = [Link]().trim();

// 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>";

[Link]("<html><center><b>" + name + "</b> (Roll No: " + rollNo + ")<br>" + eligibility +


"</center></html>");
}
66

private void showResult(String message, Color color) {


[Link]("<html><center><font color='" + toHex(color) + "'>" + message +
"</font></center></html>");
}

// Helper to convert Color to hex


private String toHex(Color color) {
return [Link]("#%02x%02x%02x", [Link](), [Link](), [Link]());
}

public static void main(String[] args) {


[Link](VotingEligibilitySwing::new);
}
}

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])

Objective: Understanding the concept for connecting to JDBC MYSQL database.

Code:
import [Link];
import [Link];
import [Link];

public class MySQLConnectionDemo {


// Database credentials - Replace with your actual values
private static final String URL = "jdbc:mysql://localhost:3306/giraffe";
private static final String USERNAME = "root";
private static final String PASSWORD = "root123";

public static void main(String[] args) {


Connection connection = null;

try {
// Step 1: Load the MySQL JDBC driver
[Link]("[Link]");
[Link]("MySQL JDBC Driver loaded successfully.");

// Step 2: Establish the connection


connection = [Link](URL, USERNAME, PASSWORD);
[Link]("Connection to MySQL database established successfully.");

// Optional: Perform a simple query or just confirm connection


if (connection != null && ![Link]()) {
[Link]("Database connection is active.");
}

} 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:

TCP Server (Echo Server)


This server listens on port 8080, accepts a client connection, reads a message from the client, echoes it back,
and closes the connection.

import [Link].*;
import [Link].*;

public class TCPServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
[Link]("TCP Server listening on port 8080...");
Socket clientSocket = [Link]();
[Link]("Client connected: " + [Link]());

// Read from client


BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
String message = [Link]();
[Link]("Received: " + message);

// Echo back to client


PrintWriter out = new PrintWriter([Link](), true);
[Link]("Echo: " + message);

[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].*;

public class TCPClient {


public static void main(String[] args) {
70

try (Socket socket = new Socket("localhost", 8080)) {


[Link]("Connected to server.");

// Send to server
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Hello from TCP Client!");

// Read from server


BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
String response = [Link]();
[Link]("Server echoed: " + response);
} catch (IOException e) {
[Link]();
}
}
}

Output:
(Server):

(Client):
71

UDP Server (Echo Server)


This server listens on port 8080, receives a datagram, echoes it back to the sender, and continues listening.

import [Link].*;
import [Link];

public class UDPServer {


public static void main(String[] args) {
try (DatagramSocket serverSocket = new DatagramSocket(8080)) {
[Link]("UDP Server listening on port 8080...");
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, [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];

public class UDPClient {


public static void main(String[] args) {
try (DatagramSocket clientSocket = new DatagramSocket()) {
String message = "Hello from UDP Client!";
byte[] sendBuffer = [Link]();
InetAddress serverAddress = [Link]("localhost");
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, [Link],
serverAddress, 8080);
[Link](sendPacket);
[Link]("Sent: " + message);

// 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].*;

public class TCPSender {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080)) {
[Link]("Connected to TCP server.");

// 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]("<h3>First " + n + " terms of Fibonacci series:</h3>"); [Link]("<p>");

for (int i = 1; i <= n; i++) { [Link](first + " ");

int next = first + second; first = second;


second = next;
}

[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;

CREATE TABLE students (


id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50),
age INT
);

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");

[Link]("<table border='1'>"); [Link]("<tr><th>ID</th><th>Name</th><th>Age</th></tr>");


77

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

public void addResult(String studentId, int score) { [Link](studentId, score);


}

public void displayResults() { [Link]("Exam Results:");


for ([Link]<String, Integer> entry : [Link]()) { [Link]("Student ID: " +
[Link]() + ", Score: " + [Link]());
}
@Override
public String toString() { return "StudentDetails{" +
"studentId='" + studentId + '\'' + ", name='" + name + '\'' +
'}';
}
}

package Admission;

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


import [Link];

public class Library {


private Map<String, List<String>> booksTaken; // Student ID to list of books
79

private Map<String, LocalDate> bookDates; // Book to date taken

public Library() {
booksTaken = new HashMap<>(); bookDates = new HashMap<>();
}

public void addBook(String studentId, String book, LocalDate date) {


[Link](studentId, k -> new ArrayList<>()).add(book); [Link](book, date);
}

public void displayBooksTaken() { [Link]("Library Books Taken:");


for ([Link]<String, List<String>> entry : [Link]()) { [Link]("Student ID: " +
[Link]() + ", Books: " +
[Link]());
}
}

public void displayBooksReturnedInTime() {


// Assuming all are returned in time for simplicity [Link]("All books returned in time.");
}

public void displayBooksBeforeExam(LocalDate examDate) { [Link]("Books taken before


exam (" + examDate + "):"); for ([Link]<String, LocalDate> entry : [Link]()) {
if ([Link]().isBefore(examDate)) {
[Link]("Book: " + [Link]() + ", Date: " + [Link]());
}
}
}
}

import [Link]; import [Link];


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

public class Main {


public static void main(String[] args) {
// Sample data
Exam exam = new Exam(); [Link]("S001", 85);
[Link]("S002", 92);

Assignment assignment = new Assignment(); [Link]("S001", "Submitted");


[Link]("S002", "Pending");
80

Library library = new Library();


[Link]("S001", "Java Programming", [Link](2023, 10, 1));
[Link]("S002", "Data Structures", [Link](2023, 10, 5));

Scanner scanner = new Scanner([Link]); while (true) {


[Link]("\nMenu:");
[Link]("a) Display the results of the students."); [Link]("b) Assignment submission
details."); [Link]("c) Library books taken/return in time.");
[Link]("d) What are the books taken from the library before the exam?");
[Link]("e) Exit"); [Link]("Choose an option: "); String choice = [Link]();

switch (choice) { case "a":


[Link](); break;
case "b": [Link](); break;
case "c": [Link]();
[Link](); break;
case "d":
LocalDate examDate = [Link](2023, 10, 10); // Sample exam date
[Link](examDate);
break; case "e":
[Link]("Exiting..."); [Link]();
return; default:
[Link]("Invalid option.");
}
}
}
}

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

[Link]("Select item type:"); [Link]("1. Mill cloth"); [Link]("2.


Handloom items"); [Link]("Enter choice (1 or 2): "); int choice = [Link]();

double discount = 0.0;

// Determine discount based on item type and amount switch (choice) {


case 1: // Mill cloth
if (amount >= 0 && amount <= 100) { discount = 0.0;
} else if (amount >= 101 && amount <= 200) { discount = 5.0;
} else if (amount >= 201 && amount <= 300) { discount = 7.5;
} else if (amount > 300) { discount = 10.0;
}
break;

case 2: // Handloom items


if (amount >= 0 && amount <= 100) { discount = 5.0;
} else if (amount >= 101 && amount <= 200) { discount = 7.5;
} else if (amount >= 201 && amount <= 300) { discount = 10.0;
83

} else if (amount > 300) { discount = 15.0;


}
break;

default:
[Link]("Invalid choice!"); [Link](0);
}

// Calculate net amount


double netAmount = amount - (amount * discount / 100);

[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];

public class EvaluateFunction {


public static void main(String[] args) { Scanner sc = new Scanner([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;

case 2: // Else if if (x > 0) {


y = 1;
} else if (x == 0) { y = 0;
} else {
y = -1;
}
[Link]("Using else if: Y = " + y); break;

case 3: // Ternary operator


y = (x > 0) ? 1 : (x == 0 ? 0 : -1);
85

[Link]("Using ternary operator: Y = " + y); break;

default:
[Link]("Invalid choice! Please select 1, 2, or 3.");
}

[Link]();
}
}

Output:

Common questions

Powered by AI

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 .

You might also like