Java Lab Record
Java Lab Record
TECHNOLOGY
PULLIKKANAM, VAGAMON
(Affiliated to Mahatma Gandhi University, Kottayam)
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
External Examiner
INDEX
Sl.no. Program Page no
7 Floyd’s triangle 17
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
2
27 Applet Program to draw Traffic Signal 73
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
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:-
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.");
}
}
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
Step 7: After the loop, calculate the difference between the two sum variables
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;
9
String num = sc.nextLine();
int digitSumEve = 0;
int digitSumOdd = 0;
Output:
10
Program No:4
Aim : - Write a Program to find the smallest number among 3 numbers.
Algorithm:-
Source Code:
import java.util.Scanner;
scanner.close();
11
double smallest = findSmallest(num1, num2, 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);
}
}
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
7. Output "******************"
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);
rows=input.nextInt();
System.out.println("Floyd's triangle");
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:
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:
31
int sum = 0;
int originalNumber = number;
while (number != 0)
{
int digit = number % 10;
sum += digit;
number /= 10;
}
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;
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"); }
}
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:-
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();
}
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();
}
}
}
}
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 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;
}
int totalMarks = 0;
for (int mark : marks) {
totalMarks += mark;
40
}
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);
}
}
scanner.nextLine();
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:-.
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);
}
}
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();
}
}
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();
}
}
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:-
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 {
import fact.Factorial;
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:-.
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;
}
57
super(customerName, accountNumber, "Current", balance);
this.minBalance = minBalance;
this.serviceCharge = serviceCharge;
}
@Override
public void withdraw(double amount) {
super.withdraw(amount);
checkMinBalance();
}
}
58
SavAcct savingsAccount = new SavAcct("John Doe", 123456, 1000.0, 5.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();
}
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();
}
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 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 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 (!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);
}
}
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
}
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);
}
}
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);
}
}
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;
setBackground(Color.white);
g.setColor(Color.blue);
g.fillRect(100, 100, 200, 150);
g.setColor(Color.red);
g.fillRect(150, 150, 50, 100);
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:-
Source Code:
import java.util.Scanner
System.out.println("Enter text:");
String inputText = scanner.nextLine();
81
scanner.close();
}
Output
82
Program No:32
Aim : -Write a Program to To perform several shapes using button.
Algorithm:-.
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 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:-
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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));
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);
}
93
resultLabel.setText("Invalid input. Please enter a valid number.");
}
}
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:-
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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);
}
});
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:-
98
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
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);
}
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.");
}
}
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 :-
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.*;
104
private JTextField textField1;
private JTextField textField2;
private JButton button;
public NumCheck() {
initialize();
}
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.*;
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