0% found this document useful (0 votes)
21 views

Java Lab Record

Uploaded by

bharatjparzival
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Lab Record

Uploaded by

bharatjparzival
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

DC SCHOOL OF MANAGEMENT AND

TECHNOLOGY
PULLIKKANAM, VAGAMON
(Affiliated to Mahatma Gandhi University, Kottayam)

DEPARTMENT OF COMPUTER APPLICATIONS

BCA 2021 ADMISSION

SEMESTER-IV
RECORD FOR PRACTICAL WORK ON JAVA PROGRAMMING
USING LINUX

NAME : …………………………………………………………………………………………
REG.NO :…………………………………………………………………………………………

YEAR :…………………………………………………………………………………………
DC SCHOOL OF MANAGEMENT AND
TECHNOLOGY
PULLIKKANAM, VAGAMON
(Affiliated to Mahatma Gandhi University, Kottayam)

Certificate

Certified that this is a bonafide record of practical work done by the


Candidate ……………………………………….….Reg.No ………………………………

Head of The Department Lecturer in charge

Submitted for the practical examination conducted on


………………………………….
at DC School of management and Technology, Pullikkanam, Vagamon.

External Examiner
INDEX
Sl.no. Program Page no

1 Fibonacci of a given number of elements 5

2 Check whether the given number is prime or not 7

3 Check whether the given number is Divisible by 11 9

4 The smallest number among 3 numbers 11

5 Print factorial of a given number 13

6 Sum of digit of a number 15

7 Floyd’s triangle 17

8 Check whether the given number is palindrome or not 19

9 Program to create a Matrix mul plica on 21

10 Program for execu ng Quadra c equa on 24

11 Print armstrong numbers within a limit 26

Mul threaded Program to print odd numbers and even


12
numbers from two different threads with suitable delay
28

Print sum of digits of a given number. If the number is less


13 than 100 or greater than 999 then throw a user defined 31
excep on

Program to Create a class called Matrix which contains a


14
2d integer array.
33

1
Mul threaded Program to print lowercase le ers and
15 uppercase le ers from two different threads with suitable 37
delay

16
Program to calculate the Result
39

17
Program to print the salary of an Employee.
43

18 Program to compute the volume of the cylinder 48

Design a Program with three classes – Student, Exam and


19
Result to model this rela onship
51

Program to create a class Factorial for compu ng factorial


20
of number under a user defined package fact
54

Create a Java Program with a base class Account having


a ributes for customer details and account type, and
derived classes Curr_acct and Sav_acct implemen ng
21 methods for deposit, balance display, interest 56
computa on, and withdrawal, with considera ons for
compound interest and minimum balance penal es for
Current Account holders.
Design a Java Program with an interface Department, a
class Hostel, and a class Student implemen ng the
22 interface and extending Hostel, modeling a ributes and 60
methods for departmental informa on, hostel details,
and student details
Program to Define the two excep on classes.
23 64

Program to find area of Rectangle and square using


24
method overloading
67

25 Applet Program to print Na onal Flag 69

26 Applet Program to draw polygon 71

2
27 Applet Program to draw Traffic Signal 73

28 Applet to draw the following shape 75

Applet Program to show how to pass a parameter from an


29
applet code
77

30 Applet Program to draw a house 79

Program to To perform several shapes using


31 81
bu on.

Program to count the number of words and number of


32
characters in a given text area.
83

33 Program to To perform several shapes using bu on 86

34 Program to perform Swings 89

swing Program to accept a value in a textbox then find the


35 area of a circle and display the result in the second 92
textbox
GUI Program to find area of a circle(Area= 𝜋 ∗ 𝑟𝑎𝑑𝑖𝑢𝑠 ∗
36
𝑟𝑎𝑑𝑖𝑢𝑠)
95

GUI using TextArea, TextField and Bu on. Delete all


37 occurrences of the TextField text in the TextArea using 98
Bu on click.
Swing Program to accept a value in a textbox then find
38 the factorial of that number and display the result in the 101
second textbox
Program using swing to accept values in two textboxes
39 and display the results of mathema cal opera ons in 104
third text box.

3
Program to accept a number then check whether a given
40 number is posi ve or nega ve and display the result in 108
the second textbox

41 Program for Card Layout 112

42 Program for Border layout 115

4
Program No:1
Aim: Program to find fibonacci of a given number of elements.

Algorithm:-

1. Start
2. Create a Scanner object to read input from the user.
3. Prompt the user to enter the number of elements in the Fibonacci series.
4. Read the user's input and store it in the variable `n`.
5. Create three integer variables: `first` and `second`, both initialized to 0, and `next`.
6. Print the initial values of `first` and `second` as the first two elements of the Fibonacci series.
7. Start a loop from `i = 2` until `i < n`.
8. Inside the loop, calculate the value of `next` as the sum of `first` and `second`.
9. Print the value of `next` as the next element of the Fibonacci series.
10. Update the values of `first` and `second` by assigning the value of `second` to `first` and the
value of `next` to `second`.
11. Repeat steps 8-10 until the desired number of elements is printed.
12. Close Scanner object.
13. End

Source Code:
import java.util.Scanner;
class fib
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter number of terms");
int n=sc.nextInt();
int i=0,j=1,nextTerm;
System.out.println("Fibonacci series is ");
for(int c=0;c<n;c++)
{
if(c<=1)
nextTerm=c;
else
{
nextTerm=i+j;

5
i=j;
j=nextTerm;
}
System.out.println(nextTerm);
}
}
}

Output:

6
Program No:2
Aim : - Program to check whether the given number is prime or not.

Algorithm:-

1. Take an integer `num` as input.


2. If `num` is less than 2, return `false` (numbers less than 2 are not prime).
3. Iterate from 2 to the square root of `num` (inclusive):
- If `num` is divisible by any number in this range, return `false` (it's not prime).
4. If the loop completes without finding a divisor, return `true` (it's prime).

SourceCode:

import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}

for (int i = 2; i <= Math.sqrt(num); i++) {


if (num % i == 0) {
return false;
}
}

7
return true;
}
}

Output:

8
Program No:3
Aim : - Write a Program to check the given number is Divisible by 11.

Algorithm:-
Step 1: Declare a variable to store the input number from the user.

Step 2: Declare two variables to store the sum of the digits at odd and even

positions respectively.

Step 3: Initialize a scanner object to read the input from the user.

Step 4: Prompt the user to enter a number and store it in the input variable.

Step 5: Use a loop to iterate over each digit of the input number from right to

left.

Step 6: In each iteration, check if the current position is odd or even and add

the digit to the corresponding sum variable.

Step 7: After the loop, calculate the difference between the two sum variables

and store it in another variable.

Step 8: Check if the difference is divisible by 11 or not using the modulo

operator (%).

Step 9: If yes, print a message that the input number is divisible by 11.

Step 10: If no, print a message that the input number is not divisible by 11.

Source Code:

import java.util.Scanner;

public class divi11 {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");

9
String num = sc.nextLine();
int digitSumEve = 0;
int digitSumOdd = 0;

for(int i = 0; i<num.length(); i++) {


if(i%2 == 0) {
digitSumEve = digitSumEve + num.charAt(i)-'0';
} else {
digitSumOdd = digitSumOdd + num.charAt(i)-'0';
}
}
int res = digitSumOdd-digitSumEve;
if(res % 11 == 0) {
System.out.println("Given number is divisible by 11");
} else {
System.out.println("Given number is not divisible by 11");
}
}
}

Output:

10
Program No:4
Aim : - Write a Program to find the smallest number among 3 numbers.

Algorithm:-

1. Start the Program.


2. Create a Scanner object to read input from the user.
3. Display a message to the user: "Enter three numbers:"
4. Read the first number from the user and store it in the variable `num1`.
5. Read the second number from the user and store it in the variable `num2`.
6. Read the third number from the user and store it in the variable `num3`.
7. Close the Scanner object to free up resources.
8. Calculate the product of the three numbers using the formula: `product = num1 * num2 *
num3`.
9. Display the result to the user, e.g., "The product of the three numbers is: product."
10. End the Program.

Source Code:
import java.util.Scanner;

public class SmallestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter three numbers: ");

double num1 = scanner.nextDouble();


double num2 = scanner.nextDouble();
double num3 = scanner.nextDouble();

scanner.close();

11
double smallest = findSmallest(num1, num2, num3);

System.out.println("The smallest number is: " + smallest);


}

public static double findSmallest(double num1, double num2, double num3) {


if (num1 <= num2 && num1 <= num3) {
return num1;
} else if (num2 <= num1 && num2 <= num3) {
return num2;
} else {
return num3;
}
}
}

Output:

12
Program No:5
Aim : - Write a java Program to print factorial of a given number.If the number is
negative then throw a user defined exception.

Algorithm:-
1. Start
2. Initialize a variable 'num' to store the user input for the number.
3. Prompt the user to enter a number and store it in 'num'.
4. If 'num' is less than 0, throw a user-defined exception "NegativeNumberException."
5. Initialize a variable 'factorial' to 1 to store the factorial of 'num.'
6. For 'i' from 1 to 'num' do the following:
a. Multiply 'factorial' by 'i' and update 'factorial.'
7. Print "The factorial of" 'num' "is" 'factorial.'
8. End

Source Code:
import java.util.Scanner;
public class fact {
public static int calculateFactorial(int n)
{
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a non-negative integer: ");


int num = scanner.nextInt();
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
int result = calculateFactorial(num);
System.out.println("The factorial of " + num + " is: " + result);

13
}
}
}

Output:

14
Program No:6
Aim : - Write a Program to find Sum of digit of a number

Algorithm:-

1. Start
2. Read the number from the user
3. Initialize a variable `sum` to 0
4. Repeat the following steps until the number becomes 0:
5. Get the last digit of the number by using the modulo operator `%` with 10
6. Add the last digit to the `sum`
7. Divide the number by 10 to remove the last digit
8. Print the value of `sum` as the sum of digits
9. End

Source Code:
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int sum = calculateSumOfDigits(number);
System.out.println("Sum of digits of " + number + " is " + sum);
}
public static int calculateSumOfDigits(int num) {
int sum = 0;

while (num != 0) {
int digit = num % 10;
sum += digit;
num /= 10;
}
return sum;
}
}

15
Output:

16
Program No:7
Aim : - Write a Program to create Floyd’s triangle.

Algorithm:-

1. Start

2. Declare variables:
- rows, columns, number, counter as integers

3. Create a Scanner object named "input" to read input from the user

4. Output "Enter number of rows:"

5. Read the value of "rows" from the user

6. Output "Floyd's triangle"

7. Output "******************"

8. Loop (counter from 1 to rows):


a. Loop (columns from 1 to counter):
i. Output the value of "number" followed by a space
ii. Increment the value of "number" by 1
b. Move to the next line

9. End

Source Code:

import java.util.Scanner;
public class flo
{
public static void main(String[]args)
{
int rows,columns,number=1,counter;

17
Scanner input=new Scanner(System.in);

System.out.println("Enter number of rows:");

rows=input.nextInt();

System.out.println("Floyd's triangle");

System.out.println("******************");

for(counter=1 ; counter<=rows ; counter++)


{

for(columns=1 ; columns<=counter ; columns++)


{
System.out.print(number+" ");
number++;
}
System.out.println();

}
}
}

Output:

18
Program No:8
Aim : - Write a Program to check whether the given number is palindrome or not.

Algorithm:-
1.Input the number from the user.
2.Then Reverse it.
3.Compare the number with the number entered by the user.
4.If both the no.’s are the same, then print the number as a palindrome
5.Else print, not a palindrome.

Source Code:
import java.util.Scanner;
class palindrome{
public static void main(String args[]){
int n,r,sum=0,temp;
System.out.println("Enter the number to find if its palindrome or not");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("Number is a palindrome");
else
System.out.println("Number is not a palindrome");
}
}

19
Output:

20
Program No: 9
Aim :- write a Program to create a Matrix multiplication.

Algorithm:-
1.Import the Scanner class.
2.Define a class named matrix.
3.Inside the main method:
Declare integer variables m, n, p, q, sum, c, d, and k.
Create a new Scanner object named in for input.
4.Prompt the user to enter the number of rows and columns for the first matrix.
Read and store m and n from user input.
5.Create a 2D integer array first with dimensions m x n to represent the first matrix.
6.Prompt the user to enter elements for the first matrix using nested loops.
Use loops to iterate over rows (c) and columns (d) and read and store each element in the
first array.
7.Prompt the user to enter the number of rows and columns for the second matrix.
Read and store p and q from user input.
8.Check if the number of columns in the first matrix (n) is equal to the number of rows in the
second matrix (p) to determine if multiplication is possible. If not, display an error message and
exit.
9.If matrix multiplication is possible:
Create a 2D integer array second with dimensions p x q to represent the second matrix.
Create a 2D integer array multiply with dimensions m x q to store the result of matrix
multiplication.
10.Prompt the user to enter elements for the second matrix using nested loops, similar to the
first matrix.
11.Perform matrix multiplication using nested loops:
Use nested loops to iterate over rows (c) and columns (d) for the resulting matrix and initialize
sum to 0 for each element.
Use another loop to iterate over the shared dimension (k), and calculate the sum of products
of corresponding elements from the first and second matrices.
Store the calculated sum in the multiply array for the corresponding position (c, d).
12.Display the result by printing "Product of the matrices:" and using nested loops to iterate over
rows (c) and columns (d) of the multiply array to print each element followed by a tab character.
13.Print a newline character after each row to format the Output.

21
Source Code:
import java.util.Scanner;
class matrix
{
public static void main(String [] args)
{
int m,n,p,q,sum=0,c,d,k;
Scanner in = new Scanner (System.in);
System.out.println("Enter the number of rows and columns of first
matrix");
m = in.nextInt();
n = in.nextInt();
int first[ ][ ] = new int[m] [n];
System.out.println("enter elements of first matrix");
for ( c = 0 ; c < m ; c++)
for ( d = 0 ; d < n ; d++)
first [c] [d]= in.nextInt();
System.out.println("Enter the number of rows and columns of second
matrix");
p = in.nextInt();
q = in.nextInt();
if (n!=p)
System.out.println("The matrices can't be multiplied with each other.");
else
{
int second [ ] [ ] = new int [p] [q];
int multiply [ ] [ ] = new int [m] [q];
System.out.println("Enter elements of second matrix");
for ( c = 0 ; c < p ; c++)
for ( d = 0 ; d < q ; d++)
second [c] [d]= in.nextInt();
for (c = 0 ; c < m ; c++)
{
for ( d = 0 ; d < q ; d++)
{
for( k = 0 ; k < p ; k++)
{
sum = sum + first [c] [k] * second [k] [d];

22
}
multiply [c] [d] = sum;
sum = 0;
}
}
System.out.println("Product of the matrices :");
for ( c = 0 ; c < m ; c++)
{
for( d = 0 ; d < q ; d++)
System.out.println(multiply [c] [d] +"\t");
System.out.print("\n");
}
}
}
}

Output:

23
Program No:10
Aim : - Write a Program for executing Quadratic equation.

Algorithm:-
1. Start
2.Initialize firstroot and secondroot to 0.
3.Read the values of a, b, and c from the user.
4.Calculate the determinant using the formula: determinant = (b * b) - (4 * a * c).
5.Calculate the square root of the determinant.
6.If determinant is greater than 0:
● Calculate firstroot and secondroot using the quadratic formula.
● Display both roots to the user.
7.If determinant is equal to 0:
● Calculate and display a single root.
8.End

Source Code:

import java.util.Scanner;
public class scanner{
public static void main(String args[]){
double secondroot = 0, firstroot = 0;
Scanner sc = new Scanner(System.in);
System.out.println("enter the value of a: ");
double a = sc.nextDouble();
System.out.println("enter the value of b: ");
double b = sc.nextDouble();
System.out.println("enter the values of c: ");
double c =sc.nextDouble();
double determinant = (b*b) - (4*a*c);
double sqrt = Math.sqrt(determinant);
if(determinant>0) {
firstroot = (-b + sqrt)/(2*a);
secondroot = (-b - sqrt)/(2*a);
System.out.println("root are "+ firstroot +" and "+secoundroot);
}
else if(determinant ==0){

24
System.out.println("root is "+(-b + sqrt)/(2*a));
}
}
}

Output:

25
Program No:11
Aim : - Write a Program to print armstrong numbers within a limit.

Algorithm:-
● Prompt the user to enter the limit and store it in the variable.
● Print a message saying that Armstrong numbers up to the limit are:
● Use a for loop to iterate from 0 to the limit.
● For each iteration, call the isArmstrong method with the current value of i as an argument.
If it returns true, then print i followed by a comma.

Source Code:

import java.util.Scanner;
import java.lang.Math;
public class amstornot
{
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;
temp=n;
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
last = temp % 10;
sum += (Math.pow(last, digits));
temp = temp/10;
}
if(n==sum)
return true;
else return false;
}
public static void main(String args[])
{

26
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");
for(int i=0; i<=num; i++)
if(isArmstrong(i))
System.out.print(i+ ", ");
}
}

Output:

27
Program No:12
Aim : - Write a multithreaded Program to print odd numbers and even numbers
from two different threads with suitable delay.

Algorithm:-
1. Create a multi class to contain the main method.
2. Define a shared lock object, lock, to synchronize access to shared resources (console Output).
3. Create two threads, oddThread and evenThread, and start them.
4. Define an OddNumberPrinter inner class that implements the Runnable interface. Override
the run method.
5. In the OddNumberPrinter class:
a. Synchronize on the lock object to ensure exclusive access.
b. Use a loop to iterate from 1 to 20 in steps of 2 (for odd numbers).
c. Print the current odd number with a message.
d. Sleep for 1 second to introduce a delay.
6. Define an EvenNumberPrinter inner class that implements the Runnable interface. Override
the run method.
7. In the EvenNumberPrinter class:
a. Synchronize on the lock object to ensure exclusive access
b. Use a loop to iterate from 2 to 20 in steps of 2 (for even numbers).
c. Print the current even number with a message.
d. Sleep for 2 seconds to introduce a delay.
8. The synchronized blocks in both classes ensure that only one thread at a time can access the
shared resource (console Output), maintaining the order of odd and even number printing.
9. The Program demonstrates multithreading by having two threads print odd and even numbers
with specified delays.

Source Code:

public class multi


{
private static final Object lock= new Object();
public static void main(String[] args)
{
Thread oddThread= new Thread(new OddNumberPrinter());
Thread evenThread= new Thread(new EvenNumberPrinter());

28
oddThread.start();
evenThread.start();
}
private static class OddNumberPrinter implements Runnable
{
@Override
public void run()
{
synchronized (lock)
{
for (int i=1; i<=20; i+=2)
{
System.out.println("Odd Number: " +i);
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
private static class EvenNumberPrinter implements Runnable
{
@Override
public void run()
{
synchronized (lock)
{
for (int i=2; i<=20; i+=2)
{
System.out.println("Even Number: " +i);
try {
Thread.sleep(2000);
}
catch (InterruptedException e)

29
{
e.printStackTrace();
}
}
}
}
}
}

Output:

30
Program No:13
Aim : - Write a Java Program to print sum of digits of a given number. If the
number is less than 100 or greater than 999 then throw a user defined exception.

Algorithm:-
1. Start
2. Initialize a variable 'num' to store the user input for the number.
3. Prompt the user to enter a number and store it in 'num'.
4. If 'num' is less than 100 or greater than 999, throw a user-defined exception
"NumberOutOfRangeException."
5. Initialize a variable 'sum' to 0 to store the sum of the digits.
6. Extract the units, tens, and hundreds digits from 'num' using modulo and integer division.
7. Calculate the sum of the digits and update 'sum.'
8. Print "The sum of the digits in" 'num' "is" 'sum.'
9. End

Source Code:

class InvalidNumberException extends Exception


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

public class invalidnumber


{
public static void main(String[] args)
{
try
{
int number = 123;
if (number < 100 || number > 999)
{
throw new InvalidNumberException("Number must be between 100 and 999");
}

31
int sum = 0;
int originalNumber = number;

while (number != 0)
{
int digit = number % 10;
sum += digit;
number /= 10;
}

System.out.println("The sum of digits of " + originalNumber + " is: " + sum);


}
catch (InvalidNumberException e)
{
System.err.println(e.getMessage());
}
}
}

Output:

32
Program No:14
Aim : - Create a class called Matrix which contains a 2d integer array. Include the
following member functions a. To read the matrix, b. To display the matrix , c.
check whether the given matrix is symmetric or not.

Algorithm:-

1.Create a class named Matrix with private instance variables m and n representing the number
of rows and columns respectively.
Create a 2D array matrix of size m x n to store the matrix elements.
2.Create a 2D array matrix of size m x n to store the matrix elements.
3.Implement a method readMatrix() to read values for the matrix from the user using a Scanner
object.
4.Implement a method displayMatrix() to print the matrix elements row by row.
5.Implement a method transposeMatrix() to calculate the transpose of the matrix and Create a
new 2D array transpose of size n x m.
Copy elements from the original matrix to the transposed matrix with rows and columns
swapped.
6.Check if the original matrix is symmetric by comparing elements of the original and transposed
matrices.
If the matrix is symmetric, set the flag variable to 1; otherwise, set it to 0.
Print whether the matrix is symmetric or not based on the value of flag
7.In the main() function, create a Scanner object to read input from the user.
Prompt the user to enter the number of rows and columns for the matrix.
8.Create an object of the Matrix class called MyMatrix.
9.Call readMatrix() to input matrix values from the user.
10.Print the original matrix using displayMatrix().
11.Call transposeMatrix() to find the transpose of the matrix and check if it is symmetric.
12.Print the transpose matrix using displayMatrix().

33
Source Code:
import java.util.Scanner;
class Matrix{
int flag=1;
private int m;
private int n;
private int[][] matrix;

public Matrix(int m, int n) {


this.m = m;
this.n = n;
this.matrix = new int[m][n];
}

public void readMatrix() {


Scanner sc = new Scanner(System.in);
System.out.println("Enter " + m + "x" + n + " matrix:");
for (int i = 0; i < m; i++) {
System.out.println("Enter values for row " + (i + 1) + " separated by spaces:");
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
}

public void displayMatrix() {


System.out.println("Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

public void transposeMatrix() {


int[][] transposed = new int[n][m];
for (int i = 0; i < n; i++) {

34
for (int j = 0; j < m; j++) {
transposed[i][j] = matrix[j][i];
}
}
matrix = transposed;
int temp = m;
m = n;
n = temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(matrix[i][j]!=transposed[j][i])
{
flag=0;
break;
}
}
}
if (flag==1)
{ System.out.println("Matrix is symmetric"); }
if (flag==0)
{ System.out.println("Matrix is Not symmetric"); }
}

public static void main(String[]args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows:");
int m = sc.nextInt();
System.out.println("Enter number of columns:");
int n = sc.nextInt();

Matrix myMatrix = new Matrix(m, n);


myMatrix.readMatrix();

System.out.println("\nOriginal Matrix:");
myMatrix.displayMatrix();

myMatrix.transposeMatrix();

35
System.out.println("\nTransposed Matrix:");
myMatrix.displayMatrix();

}
}

Output:

36
Program No:15
Aim : - Write multithreaded Program to print lowercase letters and uppercase
letters from two different threads with suitable delay.

Algorithm:-

1. Create a Java class named `LetterPrinter`.


2. Inside the `LetterPrinter` class:
- Define a `main` method as the Program entry point.
- Create two threads: `lowerCaseThread` and `upperCaseThread`.
- Associate each thread with a corresponding `Runnable` object, `LowerCasePrinter` and
`UpperCasePrinter`.
- Start both threads.
3. Define the `LowerCasePrinter` and `UpperCasePrinter` inner classes, both implementing the
`Runnable` interface:
- In the `run` method of `LowerCasePrinter`:
- Print lowercase letters from &#39;a&#39; to &#39;z&#39;.
- Add a 500-millisecond delay between each character.
- Handle potential `InterruptedException`.
- In the `run` method of `UpperCasePrinter`:
- Print uppercase letters from &#39;A&#39; to &#39;Z&#39;.
- Add a 500-millisecond delay between each character.
- Handle potential `InterruptedException`.
4. When you run the Program, the lowercase and uppercase letters are printed simultaneously
in two
threads with a 500-millisecond delay between each character.

Source Code:
public class LetterPrinter {
public static void main(String[] args) {
Thread lowerCaseThread = new Thread(new LowerCasePrinter());
Thread upperCaseThread = new Thread(new UpperCasePrinter());

lowerCaseThread.start();
upperCaseThread.start();
}

static class LowerCasePrinter implements Runnable {

37
public void run() {
for (char ch = 'a'; ch <= 'z'; ch++) {
System.out.print(ch + " ");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

static class UpperCasePrinter implements Runnable {


public void run() {
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}

Output:

38
Program No:16
Aim : -Write a Java Program to calculate the Result. Result should consist of name,
seat_no, date, center number and marks of semester three exam. Create a User
Defined Exception class MarksOutOfBoundsException, If Entered marks of any
subject is greater than 100 or less than 0, and then Program should create a user
defined Exception of type.

Algorithm:-

1. Start
2. Initialize variables:
- name (String)
- seat_no (String)
- date (String)
- center_number (String)
- marks (array of integers) with a length of the number of subjects
3. Create a class called MarksOutOfBoundsException, a user-defined exception class.
- The class should extend Exception and provide a constructor for this exception.
4. Create a function `inputMarks` to input marks for each subject:
a. Iterate over the number of subjects:
i. Display a message asking for the marks of subject i+1.
ii. Read and store the marks for the subject.
iii. Check if the entered marks are outside the valid range (0-100).
iv. If the marks are outside the range, throw the `MarksOutOfBoundsException`.
b. If all marks are within the valid range, return the marks array.
5. In the main Program:
a. Read and store the student's name, seat number, date, and center number.
b. Call the `inputMarks` function to input marks for all subjects.
- Handle the `MarksOutOfBoundsException` exception if thrown.
c. Calculate the total marks and the percentage.
d. Display the result with the following information:
- Name
- Seat Number
- Date
- Center Number
- Marks for each subject
- Total Marks

39
- Percentage
6. End

Source Code:
import java.util.Scanner;

class MarksOutOfBoundsException extends Exception {


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

class Result {
private String name;
private int seatNo;
private String date;
private int centerNo;
private int[] marks;

public Result(String name, int seatNo, String date, int centerNo, int[] marks) {
this.name = name;
this.seatNo = seatNo;
this.date = date;
this.centerNo = centerNo;
this.marks = marks;
}

public void calculateResult() throws MarksOutOfBoundsException {


for (int i = 0; i < marks.length; i++) {
if (marks[i] < 0 || marks[i] > 100) {
throw new MarksOutOfBoundsException("Marks for subject " + (i + 1) + " are out of
bounds (0-100).");
}
}

int totalMarks = 0;
for (int mark : marks) {
totalMarks += mark;

40
}

double average = (double) totalMarks / marks.length;

System.out.println("Result:");
System.out.println("Name: " + name);
System.out.println("Seat Number: " + seatNo);
System.out.println("Date: " + date);
System.out.println("Center Number: " + centerNo);
System.out.println("Total Marks: " + totalMarks);
System.out.println("Average Marks: " + average);
}
}

public class Marks {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your seat number: ");


int seatNo = scanner.nextInt();

scanner.nextLine();

System.out.print("Enter the date: ");


String date = scanner.nextLine();

System.out.print("Enter the center number: ");


int centerNo = scanner.nextInt();

System.out.print("Enter the number of subjects: ");


int numSubjects = scanner.nextInt();

int[] marks = new int[numSubjects];


for (int i = 0; i < numSubjects; i++) {
System.out.print("Enter marks for subject " + (i + 1) + ": ");

41
marks[i] = scanner.nextInt();
}

try {
Result result = new Result(name, seatNo, date, centerNo, marks);
result.calculateResult();
} catch (MarksOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}

Output:

42
Program No:17
Aim : - Write a Java Program which creates a class named 'Employee' having the
following members: Name, Age, Phone number, Address, Salary. It also has a
method named 'printSalary( )' which prints the salary of the Employee. Two
classes 'Officer' and 'Manager' inherits the 'Employee' class. The 'Officer' and
'Manager' classes have data members 'specialization' and 'department'
respectively. Now, assign name, age, phone number, address and salary to an
officer and a manager by making an object of both of these classes and print the
same.

Algorithm:-.

1. Define Employee Class:


2. Create a class Employee with the following attributes:
name (string)
age (integer)
phoneNumber (string)
address (string)
salary (double)
3. Create Employee Constructor:
4. Create a constructor for the Employee class that takes parameters to initialize the
attributes:
Name
Age
phoneNumber
Address
salary
5. Create printSalary Method in Employee Class:
6. Create a method within the Employee class called printSalary that:
Prints "Salary: $" followed by the salary attribute.
7. Define Officer Class:
8. Create a class Officer that extends the Employee class.
Add an additional attribute:
specialization (string)
9. Create Officer Constructor:
10. Create a constructor for the Officer class that takes parameters to initialize the attributes:
● name

43
● Age
● phoneNumber
● Address
● Salary
● Specialization
11. Create printDetails Method in Officer Class:
12. Create a method within the Officer class called printDetails that:
● Prints "Name: " followed by the name attribute.
● Prints "Age: " followed by the age attribute.
● Prints "Phone Number: " followed by the phoneNumber attribute.
● Prints "Address: " followed by the address attribute.
● Prints "Specialization: " followed by the specialization attribute.
Calls the printSalary method inherited from the Employee class.
13. Define Manager Class:
14. Create a class Manager that also extends the Employee class.
Add an additional attribute:
department (string)
15. Create Manager Constructor:
16. Create a constructor for the Manager class that takes parameters to initialize the
attributes:
● Name
● Age
● phoneNumber
● address
● salary
● department
17. Create printDetails Method in Manager Class:
18. Create a method within the Manager class called printDetails that:
● Prints "Name: " followed by the name attribute.
● Prints "Age: " followed by the age attribute.
● Prints "Phone Number: " followed by the phoneNumber attribute.
● Prints "Address: " followed by the address attribute.
● Prints "Department: " followed by the department attribute.
Calls the printSalary method inherited from the Employee class.
19. Main Program:
In the main function of the main Program :
● Create instances of Officer and Manager classes, initializing their attributes.
● Print "Officer Details:" and call the printDetails method for the Officer object.

44
● Print an empty line.
● Print "Manager Details:" and call the printDetails method for the Manager object.

Source Code:
class Employee {
String name;
int age;
String phoneNumber;
String address;
double salary;

Employee(String name, int age, String phoneNumber, String address, double salary)
{
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
this.address = address;
this.salary = salary;
}

void printSalary() {
System.out.println("Salary: $" + salary);
}
}

class Officer extends Employee {


String specialization;

Officer(String name, int age, String phoneNumber, String address, double salary, String
specialization) {
super(name, age, phoneNumber, address, salary);
this.specialization = specialization;
}

void printDetails() {
System.out.println("Name: " + name);

45
System.out.println("Age: " + age);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Address: " + address);
System.out.println("Specialization: " + specialization);
printSalary();
}
}

class Manager extends Employee {


String department;

Manager(String name, int age, String phoneNumber, String address, double salary, String
department) {
super(name, age, phoneNumber, address, salary);
this.department = department;
}

void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Address: " + address);
System.out.println("Department: " + department);
printSalary();
}
}

public class Main {


public static void main(String[] args) {
Officer officer = new Officer("John Doe", 30, "555-123-4567", "123 Main St", 60000,
"Finance");
Manager manager = new Manager("Jane Smith", 35, "555-987-6543", "456 Elm St", 80000,
"HR");

System.out.println("Officer Details:");
officer.printDetails();
System.out.println("\nManager Details:");
manager.printDetails();

46
}
}

Output :

47
Program No:18
Aim : - Create an interface Volume, a class Circle and a derived class Cylinder from
Volume and Circle. Volume has member function calculateVolume(),and a
constant data member pi(3.14), Circle has data member readRadius(). Write a
java Program to compute the volume of the cylinder using the above relationship.

Algorithm:-

1. Create an interface called `Volume` with a method `calculateVolume()`.


2. Create a class called `Circle`:
- Declare a protected instance variable `radius` of type double.
- Create a default constructor `Circle()` that calls the `readRadius()` method.
- Create a method `readRadius()` that reads the radius value from the user.
3. Create a class called `Cylinder` that extends the `Circle` class and implements the `Volume`
interface:
- Declare a private instance variable `height` of type double.
- Create a default constructor `Cylinder()` that calls the `super()` constructor and the
`readHeight()` method.
- Create a method `readHeight()` that reads the height value from the user.
- Implement the `calculateVolume()` method from the `Volume` interface, which calculates and
returns the volume of the cylinder using the formula: `radius * radius * Math.PI * height`.
4. Create a class called `Main`:
- Create the `main()` method:
- Create an instance of `Cylinder` called `cylinder`.
- Call the `calculateVolume()` method on `cylinder` to calculate the volume.
5. Print the volume of the cylinder to the console.

Source Code:
import java.util.Scanner;
interface Volume
{
double calculateVolume();
}
class SCircle
{
protected double radius;
public SCircle()

48
{
readRadius();
}
protected void readRadius()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius: ");
radius = scanner.nextDouble();
}
}
class Cylinder extends SCircle implements Volume
{
private double height;
public Cylinder()
{
super();
readHeight();
} private void readHeight()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height: ");
height = scanner.nextDouble();
}
public double calculateVolume()
{
return radius * radius * Math.PI * height;
}
}
public class Circle
{
public static void main(String[] args)
{
Cylinder cylinder = new Cylinder();
double volume = cylinder.calculateVolume();
System.out.println("Volume of the cylinder: " + volume);
}
}

49
Output:

50
Program No:19
Aim : - .Design three classes Student, Exam and Result. Student class has data
members roll_no and name. Exam class which is derived from Student class has
data members representing marks scored in six subjects. Results which are
derived from Exam class have its own data member total marks. Write a Program
to model this relationship.

Algorithm:-
1. Create class student
- Declare integer roll_no
- Declare String name
2. Create class exam extends student
- Declare integer fields for physics, maths, english, chemistry, biology, and java
3. Create class result extends exam
- Declare integer total_marks
4. Create class marks
a. Create a Scanner object (sc) for user input
b. Create an instance of the result class (r)
c. Prompt the user to enter the following information:
- Name
- Roll number
- Physics marks
- Maths marks
- English marks
- Chemistry marks
- Biology marks
- Java marks
d. Calculate total marks (sum of all subject marks)
e. Display the following information:
- Roll number
- Name
- Physics marks
- Maths marks
- English marks
- Chemistry marks
- Biology marks
- Java marks

51
- Total marks out of 600

Source Code:
import java.util.*;
class student
{
int roll_no=0;
String name="";
}
class exam extends student
{
int physics=0,maths=0,english=0,chemistry=0,biology=0,java=0;
}
class result extends exam
{
int total_marks=0;
}
public class marks
{
public static void main(String[]args)
{
String boby;
Scanner sc=new Scanner(System.in);
result r=new result();
System.out.println("Enter Name : ");
r.name=sc.nextLine();
System.out.println("Enter roll number : ");
r.roll_no=sc.nextInt();
System.out.println("Enter physics marks : ");
r.physics=sc.nextInt();
System.out.println("Enter maths marks : ");
r.maths=sc.nextInt();
System.out.println("Enter english marks : ");
r.english=sc.nextInt();
System.out.println("Enter chemistry marks : ");
r.chemistry=sc.nextInt();
System.out.println("Enter biology marks : ");
r.biology=sc.nextInt();

52
System.out.println("Enter java marks : ");
r.java=sc.nextInt();
r.total_marks=r.physics+r.maths+r.english+r.chemistry+r.biology+r.java;
System.out.println("Roll number : "+r.roll_no);
System.out.println("Name : "+r.name);
System.out.println("Physics marks : "+r.physics);
System.out.println("English marks : "+r.english);
System.out.println("Maths marks : "+r.maths);
System.out.println("Chemistry marks : "+r.chemistry);
System.out.println("Biology marks : "+r.biology);
System.out.println("Java marks : "+r.java);
System.out.println("Total marks out of 600 : "+r.total_marks);
}
}

Output:

53
Program No:20
Aim : - Write a Java Program to create a class Factorial for computing factorial of
number under a user defined package fact.

Algorithm:-

1.) Define a variable ‘number’ to store number for which you want to calculate the factorial
2.) Call the ‘calculateFactorial’ method from the ‘Factorial’ class, passing ‘number’ as an
argument
3.) The ‘calculateFactorial’ method recursively calculates the factorial of a given number
4.) Print the result of the factorial calculation to the console

Source Code:
package fact;
public class Factorial {

public static long calculateFactorial(int n) {


if (n < 0) {
throw new IllegalArgumentException("Input should be a non-negative integer");
}
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}

import fact.Factorial;

public class MainApp {


public static void main(String[] args) {
int number = 5;

long result = Factorial.calculateFactorial(number);

System.out.println("Factorial of " + number + " is: " + result);

54
}
}

Output

55
Program No:21
Aim : -A bank maintains two kinds of accounts - Savings Account and Current
Account. The savings account provides compound interest, deposit and
withdrawal facilities. The current account only provides deposit and withdrawal
facilities. Current account holders should also maintain a minimum balance. If
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 classes Curr-acct and Sav-acct. Include the necessary methods in order
to achieve the following tasks. a. Accept deposits from a customer and update
the balance b. Display the balance. c. Compute interest and add to balance. d.
Permit withdrawal and update the balance ( Check for the minimum balance,
impose penalty if necessary).

Algorithm:-.

1. Import the Scanner class for user input.


2. Create instances of SavAcct and CurrAcct representing a savings account and a current
account, respectively.
3. Perform operations on the savings account: a. Deposit 500 into the savings account. b.
Compute and add interest (5% of the current balance). c. Display the updated balance of
the savings account.
4. Display a blank line for better readability.
5. Perform operations on the current account: a. Deposit 1000 into the current account. b.
Withdraw 800 from the current account. c. Display the updated balance of the current
account.
6. Close the Scanner.

Source Code:
import java.util.Scanner;

class Account {
String customerName;
int accountNumber;
String accountType;
double balance;

56
public Account(String customerName, int accountNumber, String accountType, double
balance) {
this.customerName = customerName;
this.accountNumber = accountNumber;
this.accountType = accountType;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposit successful. Updated balance: " + balance);
}

public void displayBalance() {


System.out.println("Account Balance: " + balance);
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Updated balance: " + balance);
} else {
System.out.println("Insufficient funds. Withdrawal not allowed.");
}
}
}

class CurrAcct extends Account {


double minBalance;
double serviceCharge;

public CurrAcct(String customerName, int accountNumber, double balance, double


minBalance, double serviceCharge) {

57
super(customerName, accountNumber, "Current", balance);
this.minBalance = minBalance;
this.serviceCharge = serviceCharge;
}

private void checkMinBalance() {


if (balance < minBalance) {
balance -= serviceCharge;
System.out.println("Service charge imposed. Updated balance: " + balance);
}
}

@Override
public void withdraw(double amount) {
super.withdraw(amount);
checkMinBalance();
}
}

class SavAcct extends Account {


double interestRate;

public SavAcct(String customerName, int accountNumber, double balance, double


interestRate) {
super(customerName, accountNumber, "Savings", balance);
this.interestRate = interestRate;
}

public void computeInterest() {


double interest = balance * interestRate / 100;
balance += interest;
System.out.println("Interest computed and added. Updated balance: " + balance);
}
}

public class BankManagementSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

58
SavAcct savingsAccount = new SavAcct("John Doe", 123456, 1000.0, 5.0);

CurrAcct currentAccount = new CurrAcct("Jane Doe", 789012, 2000.0, 500.0, 50.0);

savingsAccount.deposit(500);
savingsAccount.computeInterest();
savingsAccount.displayBalance();

System.out.println();

currentAccount.deposit(1000);
currentAccount.withdraw(800);
currentAccount.displayBalance();

scanner.close();
}
}

Output:

59
Program No:22
Aim : -.Create an interface Department containing attributes deptName and
deptHead.it as an abstract method showData() for printing the attribute. Create
a class Hostel containing hostelname, hostellocation and noofrooms and also
have methods readData() and printData() for reading and printing the details.
Then write another class named Student extending the Hostel class and
implementing the Department interface. This class contains which contains the
attributes studname, regno, electivesub and avgmark and use readData() and
showData() for reading and printing the details.

Algorithm:-.
1. Start the Program.
2. Create a `Student` object to represent a student.
3. Read student details using the `readData` method:
a. Prompt the user to enter the hostel name, location, number of rooms, student name,
registration number, elective subject, and average mark.
b. Read and store these details in the `Student` object, including the details inherited from the
`Hostel` class.
4. Display "Student Details:" to indicate the beginning of student information.
5. Print student and hostel details using the `printData` method.
a. Display the hostel name, location, and number of rooms from the `Hostel` class.
b. Display the student name, registration number, elective subject, and average mark from the
`Student` class.
6. End the Program.

Source Code:
import java.util.Scanner;

interface Department {
void showData();
}

class Hostel {
protected String hostelName;
protected String hostelLocation;
protected int noOfRooms;

60
public void readData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Hostel Name: ");
hostelName = scanner.nextLine();
System.out.print("Enter Hostel Location: ");
hostelLocation = scanner.nextLine();
System.out.print("Enter Number of Rooms: ");
noOfRooms = scanner.nextInt();
}

public void printData() {


System.out.println("Hostel Name: " + hostelName);
System.out.println("Hostel Location: " + hostelLocation);
System.out.println("Number of Rooms: " + noOfRooms);
}
}

class Student extends Hostel implements Department {


private String studName;
private int regNo;
private String electiveSub;
private double avgMark;

public void showData() {


System.out.println("Student Name: " + studName);
System.out.println("Registration Number: " + regNo);
System.out.println("Elective Subject: " + electiveSub);
System.out.println("Average Mark: " + avgMark);
}

public void readData() {


super.readData();
Scanner scanner = new Scanner(System.in);

61
System.out.print("Enter Student Name: ");
studName = scanner.nextLine();
System.out.print("Enter Registration Number: ");
regNo = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Elective Subject: ");
electiveSub = scanner.nextLine();
System.out.print("Enter Average Mark: ");
avgMark = scanner.nextDouble();
}

public void printData() {


super.printData();
showData();
}
}

public class hostell {


public static void main(String[] args) {
Student student = new Student();
student.readData();
System.out.println("\nStudent Details:");
student.printData();
}
}

62
Output:

63
Program No:23
Aim : -Create a class Student with attributes roll no, name, age and course. If age
of student is not in between 15 and 21 then generate user-defined exception
“AgeNotWithinRangeException”. If name contains numbers or special symbols
raise exception “NameNotValidException”. Define the two exception classes.

Algorithm:-.

Step 1:Define a class called AgeNotWithinRangeException that extends

Exception class and has a constructor that takes a String message as a

parameter and passes it to the super class constructor.

Step 2:Define a class called NameNotValidException that extends Exception class and has a
constructor that takes a String message as a parameter and passes it to the super class
constructor.

Step 3:Define a class called Student that has four private instance variables: int rollNo, String
name, int age, and String course.

Step 4:Define a public constructor for the Student class that takes four parameters: int rollNo,
String name, int age, and String course, and assigns them to the corresponding instance variables.

Step 5:In the constructor, use a try-catch block to check the validity of the parameters and throw
appropriate exceptions if they are invalid. For example:

○ If the age is not between 15 and 21, throw an AgeNotWithinRangeException with the
message “Age not within range”.
○ If the name contains any number or special symbol, use a regular expression to check
and throw a NameNotValidException with the message “Name not valid”.

Step 6:Define public getter and setter methods for each instance variable, such as getRollNo(),
setRollNo(int rollNo), etc.

Step 7:Define a public method called display() that prints the details of the student object, such
as roll no, name, age, and course

64
Source Code:
class AgeNotWithinRangeException extends Exception {
public AgeNotWithinRangeException(String message) {
super(message);
}
}

class NameNotValidException extends Exception {


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

class Student {
private int rollNo;
private String name;
private int age;
private String course;

public Student(int rollNo, String name, int age, String course) throws
AgeNotWithinRangeException, NameNotValidException {

if (age < 15 || age > 21) {


throw new AgeNotWithinRangeException("Age is not within the range of 15 to 21.");
}

if (!name.matches("^[a-zA-Z ]+$")) {
throw new NameNotValidException("Name contains invalid characters.");
}

this.rollNo = rollNo;
this.name = name;
this.age = age;
this.course = course;
}

65
public void displayInfo() {
System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
}

public class StudentRegistration {


public static void main(String[] args) {
try {
Student student1 = new Student(101, "John Doe", 19, "Computer Science");
student1.displayInfo();

Student student2 = new Student(102, "Alice Smith", 14, "Mathematics");


student2.displayInfo();
} catch (AgeNotWithinRangeException e) {
System.out.println("Age Exception: " + e.getMessage());
} catch (NameNotValidException e) {
System.out.println("Name Exception: " + e.getMessage());
}
}
}

Output:

66
Program No: 24
Aim: Program to find area of Rectangle and square using method overloading.

Algorithm:-.

Step 1:Start
Step 2:Define a class called Shape that has a method called Area with no parameters. This method
will print a message saying that the shape is not defined.
Step 3:Define a subclass of Shape called Square that has an attribute called side. This attribute
will store the length of the side of the square.
Step 4:Define a constructor for Square that takes one parameter and assigns it to the side
attribute.
Step 5:Override the Area method in Square to take no parameters and calculate the area of the
square by multiplying the side attribute by itself. This method will print the area of the
square.
Step 6:Define a subclass of Shape called Rectangle that has two attributes called length and
width. These attributes will store the dimensions of the rectangle.
Step 7:Define a constructor for Rectangle that takes two parameters and assigns them to the
length and width attributes.
Step 8:Override the Area method in Rectangle to take no parameters and calculate the area of
the rectangle by multiplying the length and width attributes. This method will
print the area of the rectangle.
Step 9:In the main method, create an object of Shape and call its Area method. This will print a
message saying that the shape is not defined.
Step 10:Create an object of Square with a side value of 5 and call its Area method. This will print
the area of the square as 25.
Step 11:Create an object of Rectangle with length and width values of 10 and 15 and call its Area
method. This will print the area of the rectangle as 150.
Step 12:Stop

Source Code:
public class AreaCalculator {
public double calculateArea(double length, double width) {
return length * width;
}
public double calculateArea(double sideLength) {
return sideLength * sideLength;

67
}

public static void main(String[] args) {


AreaCalculator calculator = new AreaCalculator();

double length = 5.0;


double width = 3.0;
double sideLength = 4.0;

double rectangleArea = calculator.calculateArea(length, width);


double squareArea = calculator.calculateArea(sideLength);
System.out.println("Area of Rectangle: " + rectangleArea);
System.out.println("Area of Square: " + squareArea);
}
}

Output:

68
Program No:25
Aim : -Write applet Program to print National Flag.

Algorithm:-.
1. Start
2. Import necessary Java packages:
- java.awt.*
- java.applet.*
3. Define a class named "flag" that extends the "Applet" class:
a. Override the "paint" method with a Graphics parameter.
4. Inside the "paint" method:
a. Set the color to orange using g.setColor(Color.orange)
b. Draw and fill a rectangle for the top part of the flag (50, 60, 200, 40)
c. Set the color to white using g.setColor(Color.white)
d. Draw and fill a rectangle for the middle part of the flag (50, 100, 200, 40)
e. Set the color to green using g.setColor(Color.green)
f. Draw and fill a rectangle for the bottom part of the flag (50, 140, 200, 40)
g. Set the color to blue using g.setColor(Color.blue)
h. Draw and fill a blue circle representing the Ashoka Chakra (oval) at (135, 105, 30, 30)
i. Draw a vertical line for the flagpole (g.drawLine(50, 300, 50, 50))
5. End

Source Code:

import java.awt.*;
import java.applet.*;
public class flag extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.orange);
g.drawRect(50,60,200,40);
g.fillRect(50,60,200,40);
g.setColor(Color.white);
g.drawRect(50,100,200,40);
g.fillRect(50,100,200,40);

69
g.setColor(Color.green);
g.drawRect(50,140,200,40);
g.fillRect(50,140,200,40);
g.setColor(Color.blue);
g.drawOval(135,105,30,30);
g.fillOval(135,105,30,30);
g.drawLine(50,300,50,50);
}
}
/*<applet code="flag.class" width=300 height=300></applet>*/

Output:

70
Program No:26
Aim : -Write an applet to draw polygon

Algorithm:-
1. Initialize a Java applet class that extends `java.applet.Applet`.
2. Define two arrays to hold the X and Y values.
3. Override the `paint(Graphics g)` method.
4. Set the origin point for the graph, e.g., `xOrigin` and `yOrigin`.
5. Draw the X and Y axes using `g.drawLine()`.
6. Loop through the X and Y arrays:
a. For each data point (X[i], Y[i]), calculate screen coordinates (x, y).
b. Draw a small circle at each data point using `g.fillOval()` to make them visible.
c. Connect the data points with lines using `g.drawLine()`.
7. Compile the Java Program.
8. Run the applet in an environment that supports Java applets (e.g., an older web browser or
Java applet viewer).
9. The applet will display the line graph based on the provided X and Y values.

Source Code:
import java.awt.*;
import java.applet.*;
public class tablegraph extends Applet
{
int x[]={0,60,120,180,240,300,360,400};
int y[]={400,280,220,140,60,60,100,220};
int n=x.length;
public void paint (Graphics g)
{
g.drawPolygon (x,y,n);
}
}

/* <applet code="tablegraph.java"width=100 height=100></applet>*/

71
Output:

72
Program No:27
Aim : -Write an applet to draw Traffic Signal.

Algorithm:-.
1. Start
2. Import necessary Java packages:
- java.awt.*
- java.applet.*
3. Define a class named "traffic" that extends Applet:
4. Implement the "paint" method:
a. Draw a rectangle representing the pole of the traffic light using g.drawRect(50, 100, 60, 180).
b. Set the color to black and fill the rectangle using g.setColor(Color.black) and g.fillRect(50,
100, 60, 180).
c. Draw the red light (top) of the traffic light:
i. Draw an oval using g.drawOval(60, 110, 40, 40).
ii. Set the color to red using g.setColor(Color.red) and fill the oval using g.fillOval(60, 110, 40,
40).
d. Draw the yellow light (middle) of the traffic light:
i. Draw an oval using g.drawOval(60, 170, 40, 40).
ii. Set the color to yellow using g.setColor(Color.yellow) and fill the oval using g.fillOval(60,
170, 40, 40).
e. Draw the green light (bottom) of the traffic light:
i. Draw an oval using g.drawOval(60, 230, 40, 40).
ii. Set the color to green using g.setColor(Color.green) and fill the oval using g.fillOval(60, 230,
40, 40).
5. End

Source Code:
import java.awt.*;
import java.applet.*;
public class traffic extends Applet
{
public void paint(Graphics g)
{
g.drawRect(50,100,60,180);
g.setColor(Color.black);
g.fillRect(50,100,60,180);

73
g.drawOval(60,110,40,40);
g.setColor(Color.red);
g.fillOval(60,110,40,40);

g.drawOval(60,170,40,40);
g.setColor(Color.yellow);
g.fillOval(60,170,40,40);

g.drawOval(60,230,40,40);
g.setColor(Color.green);
g.fillOval(60,230,40,40);

}
}

/*<applet code="traffic.java" width=800 height=800 ></applet>*/

Output:

74
Program No:28
Aim : -Write an applet to draw the following shape.

Algorithm:-.
1. Start
2. Import necessary Java packages:
- java.applet.*
- java.awt.*
3. Define a class named "applet" that extends the "Applet" class:
a. Override the "paint" method with a Graphics parameter.
4. Inside the "paint" method:
a. Draw an oval for the face using g.drawOval(80, 70, 150, 150)
b. Set the color to black using g.setColor(Color.BLACK)
c. Fill two small ovals for the eyes at (120, 120, 15, 15) and (170, 120, 15, 15)
d. Draw an arc for the mouth using g.drawArc(130, 180, 50, 20, 180, 180)
5. End

Source Code:
import java.applet.*;
import java.awt.*;
/*<applet code ="applet.java" width=600 height=600></applet>*/
public class applet extends Applet{
public void paint (Graphics g)
{

g.drawOval(80,70,150,150);
g.setColor(Color.BLACK);
g.fillOval(120,120,15,15);
g.fillOval(170,120,15,15);
g.drawArc(130,180,50,20,180,180);
}
}

75
Output:

76
Program No:29
Aim : -Write an applet Program to show how to pass a parameter from an applet
code.

Algorithm:-.
1.Start
2.Create a Java applet class named "Myapplet" that extends the "Applet" class.
3.Implement the paint method within the "Myapplet" class:
a. Set the drawing color to red using g.setColor(Color.red).
b. Retrieve the value of the "msg" parameter from the HTML using getParameter("msg") and
store it in a string variable "str."
c. Use the Graphics object (parameter "g") to draw the string "str" on the applet at coordinates
(50, 50).
4.Create an HTML file to embed the applet and pass the parameter:
a. Define the HTML structure.
b. Use the <applet> tag to embed the applet and specify its dimensions (width and height).
c. Use the <param> tag to pass the parameter to the applet with the following attributes:
name: Set to "msg."
value: Provide the message you want to display (e.g., "welcome to applet").
5.Compile the Java applet class (Myapplet.java).
6.Create an HTML file that embeds the applet and sets the parameter value.
7.Open the HTML file in a web browser that supports applets.
8.The applet will display the message passed as a parameter in red color at coordinates (50, 50)
on the applet's area.
9.End

Source Code:

77
/*<applet code = "Myapplet.class" width="300" height="300">
<param name="msg" value ="welcome to applet">
</applet>*/
import java .applet.*;
import java.awt.*;
public class Myapplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
String str = getParameter("msg");
g.drawString(str,50,50);

Output:

78
Program No:30
Aim : - Write an applet Program to draw a house.

Algorithm:-
1.) Initialize the Applet
2.) Draw the house using the drawHouse method in which you define the coordinates and
dimension of the different components of the house
3.) Draw the House Body by using the fillRect method of the Graphics
4.) Draw Roof using the fillPolygon method
5.) Draw Door using the fillRect method
6.) Draw Window using the fillRect method
7.) Customize Colors and Dimensions according to your preferences

Source Code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class house extends Applet {

public void paint(Graphics g) {

setBackground(Color.white);

g.setColor(Color.blue);
g.fillRect(100, 100, 200, 150);

g.setColor(Color.red);
g.fillRect(150, 150, 50, 100);

int[] xPoints = {100, 200, 300};


int[] yPoints = {100, 50, 100};
g.setColor(Color.green);
g.fillPolygon(xPoints, yPoints, 3);

79
}
}
//<applet code="house.class" width=200 height=200></applet>

Output:-

80
Program No:31
Aim : -Write a Program to count the number of words and number of characters
in a given text area.

Algorithm:-

1.)Import the ‘Scanner’ class for taking user input


2.)Create ‘Scanner’ object to take input from the user
3.)Print a prompt asking the user to enter text
4.)Use the ‘nextLine()’ method of ‘Scanner’ to get a line of text from the user
5.)Call the ‘countWords’ function, passing the user input as an argument and inside the function
split the input text using the regular expression “\s+” to get an array of words and then return
the length of the array as the word count
6.)Call the ‘countCharachters’ function, passing the user input as an argument and inside this
function return the length of the next input text as the character count
7.)Print the number of words and characters
8.)Close ‘Scanner’ to free up resources
9.)End the Program

Source Code:
import java.util.Scanner

public class WordAndCharacterCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter text:");
String inputText = scanner.nextLine();

int wordCount = countWords(inputText);


int charCount = countCharacters(inputText);

System.out.println("Number of words: " + wordCount);


System.out.println("Number of characters: " + charCount);

81
scanner.close();
}

private static int countWords(String text) {


String[] words = text.split("\\s+");
return words.length;
}

private static int countCharacters(String text) {


return text.length();
}
}

Output

82
Program No:32
Aim : -Write a Program to To perform several shapes using button.

Algorithm:-.

STEP 1: start the process.


STEP 2: create a class main that extends Applet and implement ActionListener.
STEP 3: declare five object for the button.
STEP 4: initialize a variable s for string.
STEP 5:define a method init().
STEP 6: create five button with their corresponding names circle,rect, line,fill D rect, 3D rect.
STEP 7: add button to the form using add() and perform the action according to the user click
using add actionlistener().
STEP 8: define a method actionPerformed() to perform the action of the button event.
STEP 9: define a method paint and include try catch exception handler to capture the
errors.
STEP 10: stop the process.

Source Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class shapes extends Applet implements ActionListener
{
String s;
Button b1,b2,b3,b4,b5;
public void init()
{
b1=new Button("Circle");
b2=new Button("Rect");
b3=new Button("Line");
b4=new Button("Fill3DRect");
b5=new Button("3DRect");
add(b1);
add(b2);
add(b3);
add(b4);

83
add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
s=ae.getActionCommand();
repaint();
}
public void paint(Graphics g)
{
try
{ if(s.equals("Circle")){
g.drawOval(122,53,62,75);}

if(s.equals("Rect")){
g.drawRect(100,200,100,300);}

if(s.equals("Line")){
g.drawLine(100,200,300,490);}

if(s.equals("Fill3DRect")){
g.draw3DRect(100,50,25,40,true);}

if(s.equals("3DRect")){
g.setColor(Color.black);
g.fill3DRect(100,80,65,78,true);
g.draw3DRect(100,80,65,78,true);}
}
catch(NullPointerException e)
{
System.out.println("Error in applet:"+e);
}
}
}

84
/*<applet code="shapes.class" width=100 height=100>
</applet> */

Output:

85
Program No:33
Aim : -Write a Program to perform Swings.

Algorithm:-.
1. Start
2. Import necessary Java packages:
- javax.swing.*
- java.awt.*
- java.awt.event.*
3. Define a class named "NumberOfWords" that implements "TextListener":
4. Declare instance variables:
- JFrame f
- JLabel l1, l2, l3
- TextField t1
5. Create a constructor for "NumberOfWords":
a. Initialize the JFrame (f) with a layout manager (FlowLayout), size, default close operation, and
make it visible.
b. Create JLabels (l1, l2, l3) and a TextField (t1) for user input.
c. Add components (labels and text field) to the JFrame.
d. Add the current instance of the class as a TextListener to the text field.
6. Implement the "textValueChanged" method (required by the TextListener interface):
a. Get the text from the text field using t1.getText().
b. Calculate the number of characters (length of the text) and update l2 accordingly.
c. Count the number of words by checking for spaces and update l3 accordingly.
7. Create the main method:
a. Instantiate an object of the "NumberOfWords" class.
8. End

Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberOfWords implements TextListener
{
TextField t1;
JLabel l1,l2,l3;
JFrame f;
NumberOfWords()

86
{
f=new JFrame();
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
l1=new JLabel(" ");
l2=new JLabel("Enter name");
l3=new JLabel();
t1=new TextField(15);
f.add(l2);
f.add(t1);
f.add(l1);
f.add(l3);
t1.addTextListener(this);
}
public void textValueChanged(TextEvent te)
{
int j=1;
String sl=t1.getText();
int l=sl.length();
l2.setText("Number of characters :"+String.valueOf(l));
for(int i=0;i<sl.length();i++)
{
if(sl.charAt(i)==' ')
{
j++;
}
}
l3.setText("Number of Words= "+String.valueOf(j));
}
public static void main(String[]args)
{
NumberOfWords t=new NumberOfWords();
}
}

87
Output:

88
Program No:34
Aim:-Write a swing Program to accept a value in a textbox then find the area of a
circle and display the result in the second textbox.

Algorithm:-

Step 1: Import the necessary packages for the Program, including javax.swing for GUI
components and java.awt.event for event handling.

Step 2: Create a class named circle that implements the ActionListener interface. Declare instance
variables to hold GUI components, a message, and a double value for the calculated area.

Step 3: Create a constructor for the circle class. Inside the constructor ,Create a new JFrame
window (f) for the GUI. Set the layout manager to FlowLayout and the window size to 500x300
pixels.Define the default close operation to exit when the window is closed and make the window
visible.

Step 4: Create a JButton (b1) labeled "Area",a JLabel (l1) labeled "value 1",a JTextField (t1) to
input the radius of the circle,a JTextField (t3) to display the calculated area.Add an action listener
(this) to the "Area" button.

Step 5: Add the "value 1" label (l1),the radius input text field (t1),the "Area" button (b1) and the
area display text field (t3) to the JFrame.

Step 6: Implement the actionPerformed method as required by the ActionListener


interface.Parse the user's input (radius) from t1 and store it in a variable a.Determine the action
command (button label) using ae.getActionCommand().

Step 7: Calculate the area of the circle using the formula c = 3.14 * a * a. Convert
the calculated area to a string and set it in the result text field (t3).

Step 8: Create a main method to execute the Program.Inside the main method,
Instantiate an object of the circle class, which triggers the GUI creation and event
handling.

89
Source code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class circle implements ActionListener
{
JFrame f;
JButton b1;
JTextField t1,t3;
String msg;
double c;
circle()
{
f=new JFrame();
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
b1=new JButton("Area");
JLabel l1=new JLabel("value 1");
t1=new JTextField(15);
t3=new JTextField(15);
b1.addActionListener(this);
f.add(l1);
f.add(t1);
f.add(b1);
f.add(t3);
}
public void actionPerformed(ActionEvent ae)
{
double a=Integer.parseInt(t1.getText());
String s=ae.getActionCommand();
c=3.14*a*a;
t3.setText(String.valueOf(c));
}
public static void main(String[]args)
{
circle c=new circle();

90
}
}

Output:

91
Program No:35
Aim:-Write a java GUI Program to find area of a circle(Area= 𝜋 ∗ 𝑟𝑎𝑑𝑖𝑢𝑠 ∗ 𝑟𝑎𝑑𝑖𝑢𝑠).

Algorithm:-

1. 1. Initialize a Swing GUI application.


2. 2. Create a window (JFrame) with a title and size.
3. 3. Create a panel (JPanel) with a 4x2 grid layout to organize components.
4. 4. Add a title label (JLabel) for the application title with a specified font.
5. 5. Add a label (JLabel) for the radius and a text field (JTextField) for user
input.
6. 6. Add a &quot;Calculate&quot; button (JButton) with an action listener.
7. 7. Add a label (JLabel) for displaying the calculation result.
8. 8. When the &quot;Calculate&quot; button is pressed: a. Parse the radius input from
the text field. b. Calculate the area of a circle using A = π * r^2. c. Display
the result with two decimal places in the result label. d. Handle exceptions
for invalid input.
9. 9. Display the GUI application.

Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CircleAreaCalculator {


private JFrame frame;
private JPanel panel;
private JLabel titleLabel, radiusLabel, resultLabel;
private JTextField radiusTextField;
private JButton calculateButton;

public CircleAreaCalculator() {
frame = new JFrame("Circle Area Calculator");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

92
panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));

titleLabel = new JLabel("Circle Area Calculator", SwingConstants.CENTER);


titleLabel.setFont(new Font("Arial", Font.BOLD, 18));

radiusLabel = new JLabel("Enter the radius:");


radiusTextField = new JTextField(10);

calculateButton = new JButton("Calculate");


calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calculateArea();
}
});
resultLabel = new JLabel("", SwingConstants.CENTER);

panel.add(titleLabel);
panel.add(new JLabel(""));
panel.add(radiusLabel);
panel.add(radiusTextField);
panel.add(new JLabel(""));
panel.add(calculateButton);
panel.add(new JLabel(""));
panel.add(resultLabel);

frame.add(panel);
frame.setVisible(true);
}

private void calculateArea() {


try {
double radius = Double.parseDouble(radiusTextField.getText());
double area = Math.PI * radius * radius;
resultLabel.setText("Area: " + String.format("%.2f", area));
} catch (NumberFormatException ex) {

93
resultLabel.setText("Invalid input. Please enter a valid number.");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleAreaCalculator();
}
});
}
}
//<applet code="CircleAreaCalculator.class" width=200 height=200></applet>

Output:

94
Program No:36
Aim : -Create a GUI using TextArea, TextField and Button. Delete all occurrences
of the TextField text in the TextArea using Button click.

Algorithm:-

1. Create a Java GUI application.


2. Create a JFrame (window) and set its title, size, and close operation.
3. Create a TextArea for displaying text.
4. Create a TextField for input.
5. Create a Button for triggering the deletion action.
6. Add an ActionListener to the Button to handle the deletion action.
7. When the Button is clicked:
a. Get the text to delete from the TextField.
b. Get the current text from the TextArea.
c. Use the `replace` method to remove all occurrences of the text to delete.
d. Update the TextArea with the modified text.
e. Clear the TextField.
8. Add the components to the JFrame.
9. Make the JFrame visible.

Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class deletetext {


public static void main(String[] args) {
JFrame frame = new JFrame("Text Deletion App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);

JTextArea textArea = new JTextArea();


JTextField textField = new JTextField(20);
JButton deleteButton = new JButton("Delete Text");

deleteButton.addActionListener(new ActionListener() {

95
public void actionPerformed(ActionEvent e) {
String textToDelete = textField.getText();
String currentText = textArea.getText();
String newText = currentText.replaceAll(textToDelete, "");
textArea.setText(newText);
}
});

JPanel panel = new JPanel();


panel.add(textField);
panel.add(deleteButton);
panel.setLayout(new FlowLayout());

JScrollPane scrollPane = new JScrollPane(textArea);

frame.add(scrollPane, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);

frame.setVisible(true);
}
}

96
Output:

97
Program No:37
Aim : -Write a swing Program to accept a value in a textbox then find the factorial
of that number and display the result in the second textbox.

Algorithm:-

1. Create a class called `AreaCalculator`.


2. Inside the `AreaCalculator` class, define two methods with the same name `calculateArea` but
different parameter lists:
- The first `calculateArea` method takes two parameters: `length` and `width` (for the
rectangle).
- The second `calculateArea` method takes one parameter: `sideLength` (for the square).
3. In the first `calculateArea` method:
- Multiply the `length` and `width` parameters to calculate the area of a rectangle.
- Return the calculated area
4. In the second `calculateArea` method:
- Multiply the `sideLength` parameter by itself to calculate the area of a square (since all sides
of a square are equal).
- Return the calculated area.
5. In the `main` method:
- Create an instance of the `AreaCalculator` class.
6. Calculate the area of a rectangle:
- Call the `calculateArea` method with two arguments (length and width) and store the result
in a variable (e.g., `rectangleArea`).
7. Calculate the area of a square:
- Call the `calculateArea` method with one argument (sideLength) and store the result in a
variable (e.g., `squareArea`).
8. Print the calculated areas to the console, indicating whether each area is for a rectangle or a
square.
9. The Program execution is complete

98
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;

public class CalcSwing extends JFrame {


private JTextField inputField;
private JTextField resultField;
private JButton calculateButton;

public CalcSwing() {
setTitle("Factorial Calculator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
inputField = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false); // Make result field read-only
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateFactorial();
}
});
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Enter a number:"));
panel.add(inputField);
panel.add(calculateButton);
panel.add(new JLabel("Factorial:"));
panel.add(resultField);
add(panel);
setVisible(true);
}

private void calculateFactorial() {

99
try {
int n = Integer.parseInt(inputField.getText());
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
resultField.setText(factorial.toString());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid input. Please enter a valid number.");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalcSwing();
}
});
}
}

Output:

100
Program No:38
Aim : -Write a Program using swing to accept values in two textboxes and display
the results of mathematical operations in third text box. Use four buttons add,
subtract, multiply and divide

Algorithm :-

1. Create a JFrame to hold the calculator interface.


2. Create buttons for addition, subtraction, multiplication, and division.
3. Create text fields for the two input values and the result.
4. Implement the ActionListener interface to handle button clicks.
5. Inside the actionPerformed method:
a. Parse the values from the input text fields.
b. Get the action command of the clicked button.
c. Use a switch statement to perform the corresponding operation based on . .
the action command.
d. Update the result text field with the calculated value.
6. Create an instance of the Calculator class in the main method to run the calculator.

Source Code :-

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator implements ActionListener
{
JFrame f;
JButton b1,b2,b3,b4;
JTextField t1,t2,t3;
String msg;
int c;
Calculator()
{
f=new JFrame();
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

101
f.setVisible(true);
b1=new JButton("Add");
b2=new JButton("Subtract");
b3=new JButton("Multiplication");
b4=new JButton("Division");
JLabel l1=new JLabel("value 1");
JLabel l2=new JLabel("value 2");
t1=new JTextField(15);
t2=new JTextField(15);
t3=new JTextField(15);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(t3);
}
public void actionPerformed(ActionEvent ae)
{
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
String s=ae.getActionCommand();
switch(s)
{
case "Add":
c=a+b;
break;
case "Subtract":
c=a-b;
break;
case "Multiplication":

102
c=a*b;
break;
case "Division":
c=a/b;
break;
}
t3.setText(String.valueOf(c));
}
public static void main(String[]args)
{
Calculator c=new Calculator();
}
}

Output:
Addition:

Multiplication:

103
Program No:39
Aim : -Write a java Program to accept a number then check whether a given
number is positive or negative and display the result in the second textbox.

Algorithm:-
1. Star
2. Import necessary Java packages:
- javax.swing.*
- java.awt.event.*
3. Define a class named "NumCheck" that creates a Swing application:
a. Declare instance variables:
- JFrame frame
- JTextField textField1, textField2
- JButton butto
b. Create the main method:
i. Instantiate an object of the "NumCheck" class.
c. Create a constructor for "NumCheck":
i. Call the "initialize" method.
d. Create a method named "initialize":
i. Initialize the JFrame (frame) with size, default close operation, and layout set to null.
ii. Create JTextField instances (textField1 and textField2) for user input and result display.
iii. Create a JButton (button) with the label "Check Number."
iv. Add action listener to the button:
- Parse the input from textField1 as an integer.
- If the number is greater than or equal to 0, set the result in textField2 as "The number is
Positive."
- Otherwise, set the result in textField2 as "The number is Negative."
4. End

Program code:

import javax.swing.*;
import java.awt.event.*;

public class NumCheck {


private JFrame frame;

104
private JTextField textField1;
private JTextField textField2;
private JButton button;

public static void main(String[] args) {


try {
NumCheck window = new NumCheck();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}

public NumCheck() {
initialize();
}

private void initialize() {


frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

textField1 = new JTextField();


textField1.setBounds(50, 50, 200, 20);
frame.getContentPane().add(textField1);
textField1.setColumns(10);

textField2 = new JTextField();


textField2.setBounds(50, 150, 200, 30);
frame.getContentPane().add(textField2);
textField2.setColumns(10);

button = new JButton("Check Number");


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int num = Integer.parseInt(textField1.getText());
if (num >= 0) {

105
textField2.setText("The number is Positive");
} else{
textField2.setText("The number is Negative");
}
}
});
button.setBounds(50, 100, 200, 20);
frame.getContentPane().add(button);
}
}

Output:

106
107
Program No:40
Aim : -Write a Program using swing to accept values in two textboxes and display
the results of mathematical operations in third text box. Use four buttons add,
subtract, multiply and divide.

Algorithm:-

1.Start
2.Create a class named "Calculator" that implements the "ActionListener" interface.
3.Inside the "Calculator" class:
a. Declare instance variables:
JFrame f
JButton b1, b2, b3, b4
JTextField t1, t2, t3
String msg
int c
4.Create a constructor for the "Calculator" class:
a. Initialize the JFrame (f).
b. Set the layout of the JFrame to "FlowLayout."
c. Set the size of the JFrame to 500x300 pixels.
d. Set the default close operation to exit when the window is closed.
e. Make the JFrame visible.
f. Create four buttons (b1, b2, b3, b4) for addition, subtraction, multiplication, and division.
g. Create two JLabels (l1 and l2) for "value 1" and "value 2."
h. Create three text fields (t1, t2, t3) for user input and displaying the result.
i. Add the action listener (this) to the buttons b1, b2, b3, and b4.
j. Add the labels, text fields, and buttons to the JFrame.
5.Implement the "actionPerformed" method (from the ActionListener interface) within the
"Calculator" class:

108
a. Get the integer values entered in t1 and t2.
b. Determine the action command of the event (e.g., "Add," "Subtract," "Multiplication,"
"Division").
c. Perform the corresponding calculation based on the action command:
For "Add," add a and b and store the result in variable c.
For "Subtract," subtract b from a and store the result in variable c.
For "Multiplication," multiply a and b and store the result in variable c.
For "Division," divide a by b and store the result in variable c.
d. Set the text of t3 to the string representation of c using "t3.setText(String.valueOf(c))".
6.Create a "main" method:
a. Instantiate a new "Calculator" object named "c."
7.End
Source Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator implements ActionListener
{
JFrame f;
JButton b1,b2,b3,b4;
JTextField t1,t2,t3;
String msg;
int c;
Calculator()
{
f=new JFrame();
f.setLayout(new FlowLayout());
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
b1=new JButton("Add");
b2=new JButton("Subtract");
b3=new JButton("Multiplication");
b4=new JButton("Division");

109
JLabel l1=new JLabel("value 1");
JLabel l2=new JLabel("value 2");
t1=new JTextField(15);
t2=new JTextField(15);
t3=new JTextField(15);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(t3);
}
public void actionPerformed(ActionEvent ae)
{
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
String s=ae.getActionCommand();
switch(s)
{
case "Add":
c=a+b;
break;
case "Subtract":
c=a-b;
break;
case "Multiplication":
c=a*b;
break;
case "Division":
c=a/b;
break;

110
}
t3.setText(String.valueOf(c));
}
public static void main(String[]args)
{
Calculator c=new Calculator();
}
}

Output:-

111
Program No:41
Aim : -write a Program for Card Layout.

Algorithm:-
1. Start
2. Import necessary Java packages:
- java.awt.*
- java.awt.event.*
- javax.swing.*
3. Define a class named "cardlayout" that extends JFrame and implements ActionListener:
a. Declare instance variables:
- CardLayout card
- JButton b1, b2, b3
- Container cp
- JFrame f
b. Create a constructor for "cardlayout":
i. Instantiate JFrame (f).
ii. Get the content pane (cp) of the JFrame.
iii. Create a CardLayout (card) with specified dimensions.
iv. Set the layout of the content pane to the CardLayout.
v. Set the size, visibility, and default close operation for the JFrame.
vi. Create three JButtons (b1, b2, b3) labeled "Apple," "Boy," and "Cat."
vii. Add ActionListener to each button (this).
viii. Add the buttons to the content pane.
ix. Add the content pane to the JFrame.
c. Implement the actionPerformed method:
i. Call card.next(cp) to switch to the next card in the layout.
4. End

Source Code:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class cardlayout extends JFrame implements ActionListener
{
CardLayout card;
JButton b1,b2,b3;
Container cp;

112
JFrame f;
cardlayout()
{
f=new JFrame();
cp=this.getContentPane();
card=new CardLayout(100,300);

cp.setLayout(card);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
cp.add(b1);
cp.add(b2);
cp.add(b3);
f.add(cp);
}
public void actionPerformed(ActionEvent e)
{
card.next(cp); }
public static void main(String[] args)
{
cardlayout cl=new cardlayout();
}
}

113
Output:

114
Program No:42
Aim : -write a Program for Border layout.

Algorithm:-
1. We create a JFrame to serve as the main window.
2. We set the layout manager of the frame to BorderLayout using frame.setLayout(new
BorderLayout()).
3. We create two components (startButton and endButton) that will be placed at the "start"
(WEST) and "end" (EAST) positions of the BorderLayout.
4. We add the "start" and "end" components to the frame using frame.add(startButton,
BorderLayout.WEST) and frame.add(endButton, BorderLayout.EAST).
5. We create a central component (centerPanel) with a label and add it to the center of the
BorderLayout using frame.add(centerPanel, BorderLayout.CENTER).
6. Finally, we set some properties for the frame, such as its size, close operation, and
visibility.

Source Code:

import javax.swing.*;
import java.awt.*;

public class BorderLayoutDemo {


public static void main(String[] args) {

JFrame frame = new JFrame("BorderLayout Demo");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);

JButton northButton = new JButton("North");


JButton southButton = new JButton("South");
JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JButton centerButton = new JButton("Center");

frame.setLayout(new BorderLayout());

115
frame.add(northButton, BorderLayout.NORTH);
frame.add(southButton, BorderLayout.SOUTH);
frame.add(eastButton, BorderLayout.EAST);
frame.add(westButton, BorderLayout.WEST);
frame.add(centerButton, BorderLayout.CENTER);

frame.setVisible(true);
}
}

Output:

116

You might also like