OOPs Lab-E1-CSE-SEM2
OOPs Lab-E1-CSE-SEM2
OOPs Lab-E1-CSE-SEM2
3. Write a Java program to check whether the give number is a palindrome or not?
Code:
//program to check whether the give number is a palindrome or not?
import java.util.Scanner;
class palindrone
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter a number:");
int n=s.nextInt();
int rev=0,rem,temp=n;
while(n!=0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(temp==rev)
{
System.out.println(temp+" is a palindrone number");
}
else
{
System.out.println(temp+ " is not a palindrone number");
}
}
}
4. Write a Java program to check whether the given number is prime number or not?
Code:
//program to check whether the given nuber is prime number or not
import java.util.Scanner;
class prime
{
public static void main(String args[])
{
int i,fact=0;
Scanner s=new Scanner(System.in);
System.out.print("enter a number:");
int n=s.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)
{
fact++;
}
}
if(fact!=0)
{
System.out.println(n+" is not a prime number");
}
else
{
System.out.println(n+" is a prime number");
}
}
}
8. Write a Java program to print the pyramid triangle shape with stars and numbers range
upto five lines?
import java.util.*;
class pyramid
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
9. Write a Java program to convert temperature in Celsius to Fahrenheit?
Code:
import java.util.Scanner;
class CelsiusToFahrenheit
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter temperature in celcius:");
double celcius=scan.nextDouble();
double fahrenheit=(celcius*9/5)+32;
System.out.print("Temperature in fahrenheit:" +fahrenheit+"°F");
}
}
10. Write a Java program to perform basic Calculator operations(switch case: +,-,*,/,%)
Code:
import java.util.Scanner;
class Calculator
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Basic Calculator:");
System.out.println("Enter two numbers:");
System.out.print("a=");
double a=scan.nextDouble();
System.out.print("b=");
double b=scan.nextDouble();
System.out.println("Choose an operation:");
System.out.println("1.Addition\n2.Substraction\n3.Multiplication\n4.Division
\n5.Modulus\n");
System.out.print("Enter which operation you want to do:");
int choice=scan.nextInt();
double result=0;
switch(choice)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
if(b!=0){
result=a/b;
}
else{
System.out.println("Cannot divisible by zero;");
System.exit(0);
}
break;
case 5:
result=a%b;
break;
default:
System.out.println("Invalid Operation");
System.exit(0);
}
System.out.println("Result="+result);
}
}
11. Write a Java program to find the student grade based on the marks using switch case?
Code:
import java.util.Scanner;
class StudentGrade
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter the marks of the student: ");
int marks=scan.nextInt();
char grade=calculategrade(marks);
System.out.println("Student grade:"+grade);
}
public static char calculategrade(int marks)
{
switch(marks/10)
{
case 10:
case 9:
return 'A';
case 8:
return 'B';
case 7:
return 'C';
case 6:
return 'D';
case 5:
return 'E';
default:
return 'F';
}
}
}
int vowelCount = 0;
int consonantCount = 0;
2. Write a Java program to find sum and average of 10 numbers using arrays?
Code:
import java.util.Scanner;
// Input numbers
System.out.println("Enter " + NUMBERS_COUNT + " numbers:");
for (int i = 0; i < NUMBERS_COUNT; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();
// Calculate sum
int sum = 0;
for (int number : numbers) {
sum += number;
}
// Calculate average
double average = (double) sum / NUMBERS_COUNT;
// Input matrices
System.out.println("Enter elements of the first matrix:");
int[][] matrix1 = inputMatrix(rows, columns, scanner);
// Input matrices
System.out.println("Enter elements of the first matrix:");
int[][] matrix1 = inputMatrix(rowsMatrix1, columnsMatrix1, scanner);
return resultMatrix;
}
Sorting:
// Move elements that are greater than the key to one position
ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
// Swap the found minimum element with the first element of the
unsorted portion
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
Searching:
1. Write a Java Program to search an element using linear search technique?
Code:
import java.util.Scanner;
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
}
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
}
if (arr[mid] == key) {
return mid; // Element found, return its index
} else if (arr[mid] < key) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}
Topic: Strings
System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry :
charFrequencyMap.entrySet()) {
char c = entry.getKey();
int frequency = entry.getValue();
System.out.println("'" + c + "': " + frequency);
}
}
return charFrequencyMap;
}
}
2. Write a Java program to find number of vowels, consonants, digits and spaces in a given
sentence?
Code:
import java.util.Scanner;
int vowelCount = 0;
int consonantCount = 0;
int digitCount = 0;
int spaceCount = 0;
if (Character.isLetter(c)) {
if (isVowel(c)) {
vowelCount++;
} else {
consonantCount++;
}
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isWhitespace(c)) {
spaceCount++;
}
}
3. Write a Java program to remove all the characters except alphabets yin a given sentence
(Ex: IDNO)?
Code:
import java.util.Scanner;
return sb.toString();
}
}
// length() method
int length = str.length();
System.out.println("Length of the string: " + length);
// charAt() method
char firstChar = str.charAt(0);
System.out.println("First character of the string: " + firstChar);
// indexOf() method
int index = str.indexOf("World");
System.out.println("Index of 'World': " + index);
// substring() method
String substring = str.substring(7);
System.out.println("Substring from index 7: " + substring);
// replace() method
String replacedStr = str.replace('o', 'X');
System.out.println("String after replacing 'o' with 'X': " +
replacedStr);
// split() method
String[] splitArray = str.split(",");
System.out.println("Splitting the string with ',' as delimiter:");
for (String s : splitArray) {
System.out.println(s.trim());
}
// trim() method
String stringWithSpaces = " Hello, World! ";
String trimmedString = stringWithSpaces.trim();
System.out.println("Trimmed string: '" + trimmedString + "'");
}
}
5. Write a Java Program to implement all String Buffer Class and String Builder Class
Methods
Code:
public class StringBufferAndStringBuilder {
// append() method
stringBuffer.append("Hello, ");
stringBuffer.append("World!");
System.out.println("StringBuffer after appending: " + stringBuffer);
// insert() method
stringBuffer.insert(7, "Java ");
System.out.println("StringBuffer after insertion: " + stringBuffer);
// delete() method
stringBuffer.delete(0, 7);
System.out.println("StringBuffer after deletion: " + stringBuffer);
// replace() method
stringBuffer.replace(0, 5, "Hi");
System.out.println("StringBuffer after replacement: " +
stringBuffer);
// reverse() method
stringBuffer.reverse();
System.out.println("Reversed StringBuffer: " + stringBuffer);
// length() method
int length = stringBuffer.length();
System.out.println("Length of StringBuffer: " + length);
// substring() method
String substring = stringBuffer.substring(0, 4);
System.out.println("Substring of StringBuffer: " + substring);
// StringBuilder examples
StringBuilder stringBuilder = new StringBuilder();
// append() method
stringBuilder.append("Hello, ");
stringBuilder.append("World!");
System.out.println("StringBuilder after appending: " +
stringBuilder);
// insert() method
stringBuilder.insert(7, "Java ");
System.out.println("StringBuilder after insertion: " +
stringBuilder);
// delete() method
stringBuilder.delete(0, 7);
System.out.println("StringBuilder after deletion: " +
stringBuilder);
// replace() method
stringBuilder.replace(0, 2, "Hi");
System.out.println("StringBuilder after replacement: " +
stringBuilder);
// reverse() method
stringBuilder.reverse();
System.out.println("Reversed StringBuilder: " + stringBuilder);
// length() method
length = stringBuilder.length();
System.out.println("Length of StringBuilder: " + length);
// substring() method
substring = stringBuilder.substring(0, 4);
System.out.println("Substring of StringBuilder: " + substring);
}
}
6. Write a Java Program to print only alphabets in email id and count the characters in your
rgukt email id
Code:
import java.util.Scanner;
return alphabetsOnly.toString();
}
}
3. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units
by creating a class named 'Triangle' with a function to print the area and perimeter.
Code:
public class Triangle {
private double side1;
private double side2;
private double side3;
4. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5
units by creating a class named 'Triangle' with the constructor having the three sides as its
parameters.
code:
public class Triangle1 {
private double side1;
private double side2;
private double side3;
5. Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively
by creating a class named 'Rectangle' with a function named 'Area' which returns the area.
Length and breadth are passed as parameters to its constructor.
Code:
public class Rectangle {
private double length;
private double breadth;
6. Print the average of three numbers entered by the user by creating a class named 'Average'
having a function to calculate and print the average without creating any object of the
Average class.
Code:
import java.util.Scanner;
public class Average {
// Function to calculate and print the average of three numbers
public static void calculateAndPrintAverage(double num1, double num2,
double num3) {
double average = (num1 + num2 + num3) / 3.0;
System.out.println("The average of the three numbers is: " + average);
}
// Main method to take user input and call the static function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
7. Write a program that would print the information (name, year of joining, salary, address)
of three employees by creating a class named 'Employee'. The output should be as follows:
Name Year of joining Address Robert 1994 64C- WallsStreat Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat
Code:
public class Employee {
private String name;
private int yearOfJoining;
private double salary;
private String address;
dog.eat();
dog.move();
dog.bark();
}
}
public Student(int id, String name, String branch, int ntMidMarks, int
ntEndSemMarks, int oopsMidMarks, int oopsEndSemMarks) {
this.id = id;
this.name = name;
this.branch = branch;
this.ntMidMarks = ntMidMarks;
this.ntEndSemMarks = ntEndSemMarks;
this.oopsMidMarks = oopsMidMarks;
this.oopsEndSemMarks = oopsEndSemMarks;
}
@Override
public int getNTMidMarks() {
return ntMidMarks;
}
@Override
public int getNTEndSemMarks() {
return ntEndSemMarks;
}
@Override
public int getOOPsMidMarks() {
return oopsMidMarks;
}
@Override
public int getOOPsEndSemMarks() {
return oopsEndSemMarks;
}
3. Write a program to implement Multilevel Inheritance with example( Base class- Animal,
Derived Class – Dog , Derived Class- Babydog) and display the details of (Animal, Dog,
Babydog)
Code:
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
System.out.println("Animal Details:");
animal.sound();
System.out.println("\nDog Details:");
dog.sound();
System.out.println("\nBabyDog Details:");
babyDog.sound();
}
}
void displayDetails() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Branch: " + branch);
System.out.println("College: " + college);
}
}
System.out.println("Student1 Details:");
student1.displayDetails();
System.out.println("\nStudent2 Details:");
student2.displayDetails();
}
}
7. Write a program to implement Overriding with example Base Class(Animal) and Derived
Class(Dog) variables and methods should be same display the details
Code:
class Animal {
String name;
int age;
System.out.println("Dog Details:");
dog.displayDetails();
}
}
2. Write a program to create a class for employee and display Employee details(empid,
empname, salary etc)
Code:
class Employee {
private int empId;
private String empName;
private double salary;
// Add more attributes as needed
3. Write a program to create a class for student and display student details (id, name,
class,branch) through method (insert, display)
Code:
class Student {
private int id;
private String name;
private String className;
private String branch;
5. Write a program to print addition of two numbers using default constructor and
parameterized constructor?
Code:
class Addition {
private int num1;
private int num2;
// Default Constructor
public Addition() {
num1 = 0;
num2 = 0;
}
// Parameterized Constructor
public Addition(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
6. Write a program to print area of triangle using default and parameterized constructor?
import java.util.Scanner;
class Triangle {
private double base;
private double height;
private double area;
// Default Constructor
public Triangle() {
base = 0.0;
height = 0.0;
}
// Parameterized Constructor
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
7. Write a program to differentiate the public and private access specifiers considering data
members x ,y as private and a , b as public and display the output?
Code:
class AccessSpecifiersDemo {
private int x;
private int y;
public int a;
public int b;
public Student(int id, String name, String batch, String branch, String collegeName) {
this.id = id;
this.name = name;
this.batch = batch;
this.branch = branch;
this.collegeName = collegeName;
}
// Interface Mother
interface Mother {
void displayMotherDetails();
}
@Override
public void displayFatherDetails() {
System.out.println("Father: John Doe");
}
@Override
public void displayMotherDetails() {
System.out.println("Mother: Jane Smith");
}
public void displayChildDetails() {
System.out.println("Child Name: " + childName);
System.out.println("Child Age: " + childAge);
}
}
public Student(int id, String name, String batch, String branch, String collegeName) {
this.id = id;
this.name = name;
this.batch = batch;
this.branch = branch;
this.collegeName = collegeName;
}
Code:
class Subject {
this.mid1 = mid1;
this.mid2 = mid2;
this.endSem = endSem;
}
// Derived class OOPS inheriting from Subject
ntSubject.totalMarks();
oopsSubject.totalMarks();
edsSubject.totalMarks();
Array of Objects
Interfaces:
1. Write a Program to implement Drawable interface with example like Circle and
Rectangle class
Code:
// Drawable interface
interface Drawable {
void draw();
}
// Circle class implementing Drawable interface
class Circle implements Drawable {
private double radius;
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}
@Override
public void draw() {
System.out.println("Drawing a rectangle with length " + length + " and width " + width);
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}
// Example usage:
sbi.deposit(5000);
sbi.withdraw(2000);
pnb.deposit(10000);
pnb.withdraw(3000);
icici.deposit(8000);
icici.withdraw(5000);
}
}
3. Write a program to implement multiple inheritance in java by interface
Code:
// First Interface
interface Shape {
double getArea();
double getPerimeter();
}
// Second Interface
interface Color {
String getColor();
this.radius = radius;
this.color = color;
@Override
@Override
@Override
return color;
4. Write a Java program to create an interface Shape with the getArea() method.
Create three classes Rectangle, Circle, and Triangle that implement the Shape
interface. Implement the getArea() method for each of the three classes.
Code:
// Shape interface
interface Shape {
double getArea();
this.length = length;
this.width = width;
@Override
this.radius = radius;
@Override
this.base = base;
this.height = height;
@Override
Abstract:
1. Write a Java Program to create an Abstract class with example of Shape , Rectangle
and Circle
Code:
}
// Rectangle class extending Shape
this.length = length;
this.width = width;
@Override
double getArea() {
@Override
double getArea() {
2. Write a Java Program to implement Abstract Class (Bank) by extending class SBI,
PNB to implement Abstract class
Code:
@Override
@Override
Code:
this.brand = brand;
}
// Abstract method
// Concrete method
void displayBrand() {
super(brand);
@Override
void start() {
}
// Concrete subclass Yamaha extending Bike
super(brand);
@Override
void start() {
hondaBike.displayBrand();
hondaBike.start();
yamahaBike.displayBrand();
yamahaBike.start();
Polymorphism:
1. Explain about Compile Time Polymorphism(Method Overloading) and
Runtime Polymorphism(Method Overriding)
Code:
class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
try {
// Reading data from the source file using FileReader and BufferedReader
FileReader fileReader = new FileReader(sourceFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// Process the data (e.g., convert to uppercase) before writing to the destination file
String processedLine = line.toUpperCase();
bufferedWriter.write(processedLine);
bufferedWriter.newLine(); // Add a new line after each processed line
}
try {
File file = new File(filePath);
if (file.createNewFile()) {
System.out.println("New file created successfully at: " + filePath);
} else {
System.out.println("File already exists at: " + filePath);
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file: " + e.getMessage());
}
}
}
3. Write a Java Program to Get File Information from the exiting file or create a new file
Code:
import java.io.File;
if (file.exists()) {
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("File Size (bytes): " + file.length());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("Is File: " + file.isFile());
System.out.println("Can Read: " + file.canRead());
System.out.println("Can Write: " + file.canWrite());
System.out.println("Can Execute: " + file.canExecute());
} else {
System.out.println("File does not exist.");
}
}
}
4. Write a Java Program to write into file using File Writer
Code:
import java.io.FileWriter;
import java.io.IOException;
try {
// Create a FileWriter object with the specified file path
FileWriter fileWriter = new FileWriter(filePath);
// Close the FileWriter to release resources and flush the data to the file
fileWriter.close();
if (file.exists()) {
if (file.delete()) {
System.out.println("File deleted successfully: " + filePath);
} else {
System.out.println("Failed to delete the file: " + filePath);
}
} else {
System.out.println("File does not exist: " + filePath);
}
}
}
Packages:
1. Write a Java Program to create a Package
Code:
import com.example.mypackage.MyClass;
package com.example.package2;
import com.example.package1.ClassInPackage1;
try {
// Array Index Out of Bounds Exception
int[] arr = {1, 2, 3};
int element = getElementAtIndex(arr, 5);
System.out.println("Element at index: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
}
try {
// Null Pointer Exception
String str = null;
int length = str.length();
System.out.println("Length of the string: " + length);
} catch (NullPointerException e) {
System.out.println("Null Pointer Exception: " + e.getMessage());
}
try {
// Number Format Exception
String numStr = "abc";
int number = Integer.parseInt(numStr);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
}
}
// Method to divide two numbers and throw ArithmeticException if the divisor is zero.
private static int divideNumbers(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return dividend / divisor;
}
try {
int[] arr = {1, 2, 3};
int element = getElementAtIndex(arr, 5);
System.out.println("Element at index: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
Code:
super(message);
try {
} catch (MyCustomException e) {
System.out.println("Custom Exception: " + e.getMessage());
if (divisor == 0) {
Multithreading
1. Implementation of Thread using Inheritance
Code:
// Define a custom thread class by extending Thread
class MyThread extends Thread {
@Override
public void run() {
// Define the task you want the thread to perform
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// You can do other tasks in the main thread while the custom thread is running
for (int i = 1; i <= 3; i++) {
System.out.println("Main thread is running: " + i);
try {
Thread.sleep(2000); // Pause the main thread for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. Implementation of Thread using Runnable Interface
Code:
// Define a class that implements the Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
// Define the task you want the thread to perform
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// You can do other tasks in the main thread while the custom thread is running
for (int i = 1; i <= 3; i++) {
System.out.println("Main thread is running: " + i);
try {
Thread.sleep(2000); // Pause the main thread for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. Life Cycle of a Thread (Program to implement thread class)
Code:
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
// Create a custom Runnable implementation
Runnable myRunnable = () -> {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " is in 'Runnable' state.");
try {
// Wait for the custom thread to complete its work
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
// Wait for both threads to complete
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Create multiple threads that increment the counter using an anonymous class
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
obj.increment();
}
});
try {
// Wait for both threads to complete
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Code:
System.out.println("Thread 1 is running.");
});
thread1.setPriority(Thread.MIN_PRIORITY);
thread1.setName("Thread 1");
System.out.println("Thread 2 is running.");
};
thread2.start();
try {
} catch (InterruptedException e) {
e.printStackTrace();
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread 3 is running.");
} catch (InterruptedException e) {
System.out.println("Thread 3 is interrupted.");
}
});
thread3.start();
try {
Thread.sleep(2000);
thread3.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
The `ActionListener` interface is a part of the `java.awt.event` package and is used for
handling action events, such as button clicks. It contains a single method
`actionPerformed(ActionEvent e)` that needs to be implemented.
import java.awt.*;
import java.awt.event.*;
public ActionListenerExample() {
button = new Button("Click Me");
button.setBounds(100, 100, 80, 30);
add(button);
setSize(300, 200);
setTitle("ActionListener Example");
setLayout(null);
setVisible(true);
}
In this example, we create a window using `Frame` and add a button to it. We register an
instance of `ActionListenerExample` (which implements `ActionListener`) as the listener
for the button. When the button is clicked, the `actionPerformed()` method will be called,
and it will print "Button Clicked!" to the console.