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

Notes Paper6

BCA paper 6 vvi question answer

Uploaded by

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

Notes Paper6

BCA paper 6 vvi question answer

Uploaded by

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

1:- C and C++ are both widely used programming languages, but they have some key

differences:
C is a procedural programming language, which means it focuses on procedures or functions to
operate on data.
C++ supports both procedural and object-oriented programming paradigms. It introduces
classes and objects, l
encapsulation, inheritance, and polymorphism.
Abstraction:C provides basic data types and structures for organizing data but lacks built-in
support for abstraction.
C++ supports abstraction through classes and objects, allowing for better organization and
modularization of code.
Encapsulation:C does not support encapsulation inherently. Data and functions are often
declared globally or within
structures, but there are no access control modifiers.C++ supports encapsulation through
access specifiers like public,
private, and protected, allowing the hiding of implementation details and better control over
access to class members.
Inheritance:C does not support inheritance.C++ supports inheritance, allowing a class to inherit
properties and behaviors
from another class. This facilitates code reuse and promotes the creation of hierarchies of
related classes.
Polymorphism:C does not support polymorphism.C++ supports polymorphism through function
overloading and virtual functions.
This enables functions to behave differently based on the object they are called with, enhancing
code flexibility and readability.
Standard Libraries:Both C and C++ have their own standard libraries, but C++ includes
additional libraries to support object-oriented
features and provides more extensive functionalities.
Compatibility:C code can generally be compiled by a C++ compiler, but the reverse is not
always true due to C++'s additional features.
C++ introduces new keywords and constructs that are not present in C, so C code might need
adjustments to be compiled as C++.
Memory Management:Both languages support manual memory management, but C++
introduces the concept of constructors and destructors, making
memory management more automated through the use of objects and classes.In summary,
while C and C++ share some similarities, C++ expands upon
C by adding support for object-oriented programming, which brings features like encapsulation,
inheritance, and polymorphism, making it more
suitable for complex and modular software development.

2:- Write programming structure using class and


their object in C++.
ChatGPT
Sure, here's a simple example of a C++ program structure using classes and objects:
#include <iostream>
#include <string>
using namespace std;
// Define a class called Person
class Person {
private:
string name;
int age;

public:
Person(string n, int a) {
name = n;
age = a;
}
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
string getName() {
return name;
}
int getAge() {
return age;
}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1("Alice", 25);
Person person2("Bob", 30);
cout << "Information about Person 1:" << endl;
person1.displayInfo();
cout << "\nInformation about Person 2:" << endl;
person2.displayInfo();
person1.setName("Carol");
person1.setAge(35);
cout << "\nUpdated information about Person 1:" << endl;
person1.displayInfo();
return 0;
}
In this program:

We define a class Person with private data members name and age, and public member
functions (methods) to set and get these
attributes, as well as a function
to display information about the person.In the main() function, we create two Person objects
(person1 and person2) with
different initial values for name and age.We then display information about these objects using
the displayInfo() method.
We also demonstrate how to update the information of a Person object using the setName() and
setAge() methods,
followed by displaying the updated information.

3:-What is friend function? Write using a suitable


example.
In C++, a friend function is a function that is not a member of a class but has access to the
private and protected members of the class.
This allows the function to operate on the private or protected data of the class without being a
member of that class.
Here's an example to illustrate the concept of a friend function:
#include <iostream>
using namespace std;
class Car;
void displaySpeed(const Car& car);
class Car {
private:
int speed;
public:
Car(int s) : speed(s) {}
friend void displaySpeed(const Car& car);
};
void displaySpeed(const Car& car) {
cout << "Current speed of the car: " << car.speed << " km/h" << endl;
}
int main() {
Car myCar(100);
displaySpeed(myCar);
return 0;
}
In this example:
We have a class Car with a private member variable speed.
We declare the function displaySpeed() outside the class Car.
Inside the Car class, we declare displaySpeed() as a friend function using the friend keyword.
This allows displaySpeed() to access the private member speed of the Car class.
In the main() function, we create an object myCar of type Car with an initial speed of 100.
We then call the displaySpeed() function, passing myCar as an argument, which displays the
current speed of the car by accessing the private member speed of the Car class.

4:-What is virtual function? Write some advantage of virtual function.


ChatGPT
A virtual function in C++ is a member function of a class that is declared within a base class
using the virtual keyword and is intended to
be overridden by derived classes. When a virtual function is called through a base class pointer
or reference, the actual function
implementation that gets executed is determined dynamically based on the type of the object
being pointed to or referred to.
This is known as dynamic dispatch or late binding.
Advantages of virtual functions include:

Polymorphism: Virtual functions enable polymorphic behavior, allowing objects of different


derived classes to be treated uniformly through
pointers or references to their base class. This simplifies code and promotes flexibility.
Dynamic Binding: Virtual functions facilitate dynamic binding, meaning that the appropriate
function implementation is selected at runtime
based on the type of the object being referred to, rather than at compile time. This allows for
more flexible and adaptable code.
Code Reusability: Virtual functions promote code reuse by allowing a common interface to be
defined in the base class, while specific
behaviors can be implemented in derived classes. This reduces redundancy and improves
maintainability.
Extensibility: Virtual functions enable easy extension of classes by allowing derived classes to
add new behavior without modifying
the base class. This follows the Open-Closed Principle, where classes are open for extension
but closed for modification.
Encapsulation: Virtual functions support encapsulation by allowing the implementation details of
a function to be hidden in derived classes.
This enhances the separation of concerns and helps manage complexity in large software
systems.
Overall, virtual functions play a crucial role in enabling polymorphism and facilitating the design
of flexible, extensible,
and maintainable object-oriented software systems.
5:- Explain features of object oriented programming

Certainly! Object-oriented programming (OOP) is a programming paradigm that revolves around


the concept of objects, which encapsulate
data and behaviors. Here are the key features of object-oriented programming:
Classes and Objects:
Classes serve as blueprints for creating objects. They define the properties (attributes) and
behaviors (methods) that objects of the class will have.
Objects are instances of classes. They represent specific instances or entities in a program and
encapsulate both data and behavior.
Encapsulation:
Encapsulation is the bundling of data (attributes) and methods (behaviors) that operate on the
data into a single unit, called a class.
It hides the internal state of objects and restricts access to the data, allowing only specified
methods to manipulate the data.
This provides data integrity and security.
Inheritance:
Inheritance is a mechanism where a new class (subclass or derived class) can inherit properties
and behaviors (attributes and methods)
from an existing class (superclass or base class).It promotes code reuse, as common attributes
and methods can be defined in a superclass and reused by multiple subclasses.
Polymorphism:
Polymorphism allows objects to be treated as instances of their superclass, enabling different
objects to be used interchangeably through a common interface.
It enables functions or methods to behave differently based on the object they are operating on,
facilitating code flexibility and extensibility.
Abstraction:
Abstraction refers to the process of hiding the complex implementation details and exposing
only the essential features of an object.
It allows developers to focus on the relevant aspects of objects while hiding irrelevant details,
making the design more understandable and maintainable.
Message Passing:
Objects in an object-oriented system communicate with each other by sending and receiving
messages.
Messages are requests for an object to perform a certain action or respond with certain
information, facilitating object interaction and collaboration.
Association, Aggregation, and Composition:
Association represents relationships between objects, where one object is related to another
object.
Aggregation is a type of association where one object contains another object, but the contained
object can exist independently.
Composition is a stronger form of aggregation, where the contained object is part of the
containing object and cannot exist independently.
These features of object-oriented programming provide a powerful framework for organizing and
designing software systems, promoting concepts
such as modularity, reusability, and maintainability. By modeling real-world entities as objects
and defining their interactions, developers
can create more scalable, flexible, and understandable code.

6:- Write a program in C++ using a member function passing object of class to display smallest
between two number.
Here's a C++ program that demonstrates passing objects of a class to a member function to
display the smallest between two numbers:
#include <iostream>
using namespace std;
class Number {
private:
int num1, num2;

public:
Number(int n1, int n2) {
num1 = n1;
num2 = n2;
}
void displaySmallest() {
if (num1 < num2) {
cout << "The smallest number is: " << num1 << endl;
} else {
cout << "The smallest number is: " << num2 << endl;
}
}
};
int main() {
Number numbers(10, 5);
numbers.displaySmallest();
return 0;
}
In this program:
We define a class called Number, which has two private member variables num1 and num2.
The class has a constructor that initializes these member variables.
The class also has a member function displaySmallest() that compares the two numbers and
displays the smallest one.
In the main() function, we create an object numbers of the Number class with initial values 10
and 5.
We then call the displaySmallest() member function on the numbers object to display the
smallest number between the two.
7:- Write a program using class and object in java to check a number is Palindrome or not.
Sure, here's a Java program using a class and object to check if a number is a palindrome or
not:
import java.util.Scanner;
class PalindromeNumber {
public boolean isPalindrome(int number) {
int originalNumber = number;
int reverse = 0;
while (number != 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
return originalNumber == reverse;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
PalindromeNumber palindromeNumber = new PalindromeNumber();
boolean isPalindrome = palindromeNumber.isPalindrome(number);
if (isPalindrome) {
System.out.println(number + " is a palindrome number.");
} else {
System.out.println(number + " is not a palindrome number.");
}
scanner.close();
}
}
In this program:
We define a class called PalindromeNumber with a member function isPalindrome() that checks
whether a given
number is a palindrome or not.Inside the isPalindrome() method, we reverse the given number
and compare it with
the original number to determine if it's a palindrome.In the main() method, we prompt the user to
enter a number.
We create an object palindromeNumber of the PalindromeNumber class.We call the
isPalindrome() method on the object
to check if the entered number is a palindrome or not, and then display the result accordingly.
8:- Write _any five features of Java.

Certainly! Here are five features of Java:


Simple and Easy to Learn:
Java was designed to be simple, straightforward, and easy to learn. It has a clean syntax with
fewer complex features,
making it accessible to beginners and experienced programmers alike.
Platform Independence (Write Once, Run Anywhere):
Java programs are compiled into platform-independent bytecode, which can be executed on
any platform with a Java Virtual Machine (JVM).
This "write once, run anywhere" (WORA) capability enables Java applications to run on diverse
hardware and operating systems without modification.
Object-Oriented Programming (OOP):
Java is a fully object-oriented programming language, supporting concepts such as classes,
objects, inheritance, encapsulation, and polymorphism.
OOP principles promote modularity, code reusability, and maintainability, making Java
well-suited for large-scale software development.
Robustness and Security:
Java incorporates features like strong type checking, exception handling, and automatic
memory management (garbage collection) to ensure
robustness and reliability. Its strict compile-time and runtime checks help detect errors early and
prevent common programming mistakes.
Additionally, Java's security model includes built-in protections against vulnerabilities like buffer
overflows and pointer manipulation.
Rich Standard Library:
Java comes with a comprehensive standard library, known as the Java API (Application
Programming Interface), which provides a wide range
of classes and utilities for common tasks such as I/O operations, networking, data manipulation,
GUI development, and more. The Java API
simplifies development by offering pre-built components and functionality, reducing the need to
reinvent the wheel.

9:- What is constructor in Java? Discuss the types of constructor in Java.


In Java, a constructor is a special type of method that is called automatically when an object of
a class is created.
It is used to initialize the newly created object and set its initial state. Constructors have the
same name as the
class and do not have a return type, not even void. They can have parameters to initialize the
object with specific values.
Types of constructors in Java:

Default Constructor:
A default constructor is automatically provided by Java if no constructor is explicitly defined in a
class.
It initializes the object with default values (0, null, false) for primitive data types and null for
reference data types.
Its signature is public ClassName() { }.
Parameterized Constructor:
A parameterized constructor is a constructor with parameters used to initialize the object with
specific values.
It allows for custom initialization of objects based on the values passed as arguments.
Its signature includes parameters and looks like public ClassName(parameter1Type
parameter1, parameter2Type parameter2, ...) { }.
Copy Constructor:
A copy constructor is used to create a new object as a copy of an existing object.
It initializes the new object with the same state as the existing object.
Its signature includes a single parameter of the same type as the class, and it typically performs
a deep copy of the object.
For example:
public ClassName(ClassName originalObject) {

}
Constructor Overloading:
Constructor overloading is the practice of having multiple constructors in a class with different
parameter lists.
It allows objects to be initialized in different ways, providing flexibility and convenience to the
users of the class.
The constructors must have unique parameter lists to avoid ambiguity.
Example of constructor overloading:
java
Copy code
public ClassName() { }
public ClassName(int x) { }
public ClassName(int x, int y) { }
Constructors play a crucial role in Java programming as they ensure that objects are properly
initialized before they are used.
They help maintain the integrity of objects by setting their initial state, and their flexibility allows
for various
initialization scenarios to be accommodated.

10:- Write a program using constructor to take two number and display arithmetical operation.
Here's a Java program that uses a constructor to take two numbers and display arithmetic
operations:
import java.util.Scanner;
class ArithmeticOperations {
private int number1;
private int number2;
public ArithmeticOperations(int num1, int num2) {
number1 = num1;
number2 = num2;
}
public void displayOperations() {
System.out.println("Arithmetic Operations:");
System.out.println("Addition: " + (number1 + number2));
System.out.println("Subtraction: " + (number1 - number2));
System.out.println("Multiplication: " + (number1 * number2));
System.out.println("Division: " + (number1 / number2));
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
ArithmeticOperations arithmeticOperations = new ArithmeticOperations(num1, num2);
arithmeticOperations.displayOperations();
scanner.close();
}
}
In this program:
We define a class ArithmeticOperations with private member variables number1 and number2.
We have a constructor ArithmeticOperations(int num1, int num2) that takes two numbers as
parameters and initializes the member variables.
The class also has a method displayOperations() that displays the arithmetic operations
(addition, subtraction, multiplication, and division)
of the two numbers.In the main() method, we prompt the user to enter two numbers.
We create an object arithmeticOperations of the ArithmeticOperations class using the
constructor, passing the entered numbers as arguments.
We then call the displayOperations() method on the object to display the arithmetic operations.

11:- Explain pure virtual function in C++ with suitable


example.
In C++, a pure virtual function is a virtual function declared in a base class that has no
implementation in the base class and is meant to
be overridden in derived classes. It is declared using the virtual keyword followed by = 0 in the
base class. Classes containing
pure virtual functions are called abstract classes, and they cannot be instantiated directly; they
can only serve as base classes for other classes.
Here's an example to illustrate pure virtual functions in C++:
#include <iostream>
using namespace std;

class Shape {
public:
// Pure virtual function to calculate area
virtual float calculateArea() = 0;
};
class Rectangle : public Shape {
private:
float length;
float width;

public:
Rectangle(float l, float w) : length(l), width(w) {}
float calculateArea() override {
return length * width;
}
};
class Circle : public Shape {
private:
float radius;
public:

Circle(float r) : radius(r) {}
float calculateArea() override {
return 3.14 * radius * radius;
}
};
int main() {
Rectangle rectangle(5, 4);
Circle circle(3);
cout << "Area of rectangle: " << rectangle.calculateArea() << endl;
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
In this example:
We have an abstract class Shape with a pure virtual function calculateArea().
We have two derived classes, Rectangle and Circle, which inherit from the Shape class.
Each derived class provides its own implementation of the calculateArea() function.
We create objects of the derived classes (rectangle and circle) and call the calculateArea()
function on them.
The appropriate implementation of calculateArea() (from the derived class) is called based on
the object's type,
demonstrating polymorphic behavior.

12:- What is template class in C++? Write a program in C++ to print greatest between two value
integer, float and character.

A template class in C++ allows you to define a class with generic types, meaning you can use
the same class definition with
different data types without having to rewrite the code for each type. This enables you to create
flexible and reusable code
that can work with various data types.
Here's a program in C++ using a template class to print the greatest value between two values
of different types (integer, float, and character):
#include <iostream>
using namespace std;
template<typename T>
class Greatest {
private:
T value1;
T value2;

public:
Greatest(T v1, T v2) : value1(v1), value2(v2) {}
T findGreatest() {
return (value1 > value2) ? value1 : value2;
}
};
int main() {
Greatest<int> greatestInt(10, 20);
cout << "Greatest integer: " << greatestInt.findGreatest() << endl;
Greatest<float> greatestFloat(3.14, 2.718);
cout << "Greatest float: " << greatestFloat.findGreatest() << endl;
Greatest<char> greatestChar('A', 'B');
cout << "Greatest character: " << greatestChar.findGreatest() << endl;
return 0;
}
In this program:
We define a template class Greatest with a single type parameter T.
The class has two private member variables value1 and value2, which represent the two values
to compare.
The constructor initializes these member variables with the values passed as arguments.
The findGreatest() method compares the two values and returns the greatest value.
In the main() function, we create instances of the Greatest class for different data types (integer,
float, and character)
and call the findGreatest() method to print the greatest value for each type.

13:- Explain lnheritanee in C++ with some advantages and their types in Java.
Inheritance in C++ and Java is a mechanism by which a class (subclass or derived class) can
inherit properties and behaviors
(attributes and methods) from another class (superclass or base class). This enables code
reuse, promotes modularity,
and supports the concept of hierarchical classification.
Inheritance in C++:
In C++, inheritance is implemented using classes. Here's how inheritance works in C++:
Base Class (Superclass):
The base class is the class whose properties and behaviors are inherited by another class.
It defines the common attributes and methods shared by its subclasses.
Example:
class Shape {
protected:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
Derived Class (Subclass):
The derived class is the class that inherits properties and behaviors from a base class.
It extends the functionality of the base class by adding new attributes and methods or by
overriding existing ones.
Example:
class Rectangle : public Shape {
public:
int calculateArea() {
return width * height;
}
};
Advantages of Inheritance in C++:
Code Reuse: Inheritance allows subclasses to inherit attributes and methods from their
superclass, reducing code duplication
and promoting modularity.Polymorphism: Inheritance facilitates polymorphism, allowing objects
of different subclasses to be treated as objects of the
same superclass type, promoting flexibility and extensibility.Modularity: Inheritance promotes
modularity by organizing classes into hierarchical
structures, making the codebase easier to understand and maintain.
Inheritance Types in Java:
In Java, inheritance operates similarly to C++. However, Java supports single inheritance (a
subclass can inherit from only one superclass)
and multiple inheritance through interfaces. Here are the types of inheritance in Java:

Single Inheritance:
In single inheritance, a subclass inherits from only one superclass.
Example:
class Subclass extends Superclass {
}
Multiple Inheritance through Interfaces:
Java supports multiple inheritance through interfaces, where a class can implement multiple
interfaces.
Interfaces define a contract that classes must adhere to by implementing their methods.
Example:
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
class MyClass implements Interface1, Interface2 {
}
Advantages of Inheritance in Java:
Code Reuse: Inheritance enables classes to inherit attributes and methods from their
superclass or interfaces, promoting code reuse and modularity.
Interface-Based Polymorphism: Java's support for interface-based inheritance allows for
polymorphic behavior, where objects of different classes
that implement the same interface can be treated uniformly.
Method Overriding: Inheritance allows subclasses to override methods inherited from their
superclass, enabling customization and specialization of behavior.
Overall, inheritance in both C++ and Java provides a powerful mechanism for building complex
software systems by promoting code reuse, modularity, and polymorphism.

14:- Explain loop and their types in Java.


In Java, a loop is a control structure that allows you to execute a block of code repeatedly based
on a certain condition. Loops are essential for automating
repetitive tasks and iterating over data structures. Java provides several types of loops, each
with its own specific use cases:
1. while Loop:
The while loop repeatedly executes a block of code as long as a specified condition is true. It
checks the condition before each iteration
while (condition) {
}
2. do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the block of code is
executed at least once before checking the condition.
It checks the condition after each iteration.
do {
} while (condition);
3. for Loop:
The for loop is used when you know the number of iterations in advance. It consists of an
initialization, a condition, and an update expression, separated by semicolons.
for (initialization; condition; update) {
}
4. Enhanced for Loop (for-each Loop):
The enhanced for loop is used to iterate over elements of arrays or collections without using an
index. It simplifies the syntax for iterating over collections.
for (type variable : array/collection) {
}
5. Nested Loops:
Nested loops are loops within loops. They allow you to execute one or more loops inside
another loop's body.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
}
}
Loop Control Statements:
Java provides loop control statements to alter the flow of loops:
break: Terminates the loop and transfers control to the next statement after the loop.
continue: Skips the current iteration of the loop and proceeds to the next iteration.
Advantages of Loops:
Automation of Repetitive Tasks: Loops automate the execution of repetitive tasks, reducing
manual effort and minimizing code redundancy.
Efficient Iteration: Loops provide an efficient way to iterate over arrays, collections, or ranges of
values, making it easier to process large amounts of data.
Flexibility: Different types of loops provide flexibility in handling various looping scenarios, such
as iterating over collections, processing data sequentially,
or executing code based on specific conditions.In Java, choosing the appropriate type of loop
depends on the specific requirements of the task at hand,
such as the type of iteration, the condition for termination, and the need for explicit control over
loop execution.
15:- What is array? Discuss types of array in Java with suitable example.
In Java, an array is a data structure that stores a fixed-size sequential collection of elements of
the same data type. Arrays are used to store multiple
values of the same type under a single variable name, allowing for efficient storage and retrieval
of data. Each element in an array is accessed using an
index, which represents its position within the array.

Types of Arrays in Java:


Single-Dimensional Array:
A single-dimensional array stores elements in a linear sequence.
It is declared using square brackets [].
Example:
int[] numbers = {10, 20, 30, 40, 50};
Multidimensional Array:
A multidimensional array stores elements in multiple dimensions, such as rows and columns.
It is declared using multiple sets of square brackets [][].
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Multidimensional arrays can have more than two dimensions, such as 3D arrays, 4D arrays,
etc., by adding additional sets of square brackets.
Advantages of Arrays in Java:
Efficient Storage: Arrays provide efficient storage for a fixed number of elements of the same
data type, with each element occupying a contiguous memory location.
Random Access: Elements in an array are accessed using index-based random access,
allowing for quick retrieval and manipulation of data.
Iterative Processing: Arrays support iterative processing, making it easy to perform operations
on each element of the array using loops.
Compact Syntax: Java provides a compact syntax for declaring and initializing arrays,
simplifying the code for array manipulation.
Example:
Here's an example demonstrating the use of single-dimensional and multidimensional arrays in
Java:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Print elements of the single-dimensional array
System.out.println("Single-Dimensional Array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// Multidimensional array (2D)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print elements of the 2D array
System.out.println("\nMultidimensional Array (2D):");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
This program demonstrates the declaration, initialization, and iteration over elements of both
single-dimensional and multidimensional arrays in Java.

16:- What is Applet? Write a program in Applet to Add two number and display values in Applet
on Button Click.
In Java, an applet is a small program that runs within a web browser or applet viewer. It is
primarily used to create dynamic and
interactive content on web pages. Applets are embedded in HTML documents and executed by
a web browser or applet viewer.
Here's a program in Java applet to add two numbers and display the result in an applet window
when a button is clicked:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AddApplet extends Applet implements ActionListener {
TextField num1Field, num2Field, resultField;
Button addButton;
public void init() {
num1Field = new TextField(10);
num2Field = new TextField(10);
resultField = new TextField(10);
resultField.setEditable(false); // Make the result field read-only
addButton = new Button("Add");
addButton.addActionListener(this); // Register action listener for button
add(new Label("Enter first number:"));
add(num1Field);
add(new Label("Enter second number:"));
add(num2Field);
add(addButton);
add(new Label("Result:"));
add(resultField);
}
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 + num2;
resultField.setText(String.valueOf(result));
}
}
In this applet:

We create an applet class AddApplet that extends the Applet class and implements the
ActionListener interface to handle button click events.
In the init() method, we initialize the applet by creating text fields for entering numbers, a text
field for displaying the result, and a
button for performing addition. We add these components to the applet.
We register the applet as the action listener for the button using
addButton.addActionListener(this).
In the actionPerformed() method, we handle the button click event by retrieving the numbers
from the text fields, performing addition,
and displaying the result in the result field.

You might also like