MCS024 (1)
MCS024 (1)
Ques. 1 List the salient features of the object-oriented programming approach that
distinguishes it from procedural programming ?
Here are some of the salient features of OOP that distinguish it from procedural
programming:
• Abstraction: In OOP, data is abstracted into objects. This means that the data is not
exposed directly to the user, but is encapsulated within the object. This makes the
code more secure and easier to maintain.
• Encapsulation: Encapsulation is a mechanism that binds together code and data, and
keeps both safe from outside interference. This is achieved by declaring variables and
methods as private, which means that they can only be accessed by other code
within the same class.
• Inheritance: Inheritance is the ability of one object to inherit the properties and
methods of another object. This allows for code reuse and makes it easier to create
new objects.
• Polymorphism: Polymorphism is the ability of an object to respond to a message in
different ways, depending on its type. This allows for code to be written in a more
general way, and makes it easier to add new features to a program.
• Objects: OOP focuses on creating objects, which are instances of classes. Objects
encapsulate data (attributes) and behavior (methods) into a single entity. This allows
for better organization and modularity of code.
• Classes: Classes serve as blueprints or templates for creating objects. They define the
properties and behaviors that objects of a particular type should possess. Classes can
inherit properties and behaviors from other classes through inheritance, promoting
code reuse.
•
Procedural programming, on the other hand, is a programming paradigm that focuses on
the logic of a program, rather than the data. In procedural programming, code is organized
into functions, which are called to perform specific tasks. Procedural programming is not as
object-oriented as OOP, and does not use the same principles such as encapsulation,
inheritance, and polymorphism.
OOP is a more powerful and flexible programming paradigm than procedural programming.
It allows for code to be written in a more natural way, and makes it easier to create large,
complex programs.
Ques. 2 Explain the relationship between Data Abstraction and Encapsulation with an
example ?
Data abstraction and encapsulation are two closely related concepts in object-oriented
programming (OOP). Data abstraction is the process of hiding the implementation details of
a data type, while encapsulation is the mechanism that binds together data and code into a
single unit.
One way to think about the relationship between data abstraction and encapsulation is to
imagine a car. The car is a data type, and the engine, wheels, and other components are the
data that is hidden from the user. The car's owner doesn't need to know how the engine
works in order to drive the car. They just need to know how to use the car's interface, which
is the steering wheel, pedals, and other controls.
In OOP, data abstraction is implemented using abstract classes and interfaces. An abstract
class is a class that cannot be instantiated, but can be used to provide a common interface
for other classes. An interface is a contract that defines the methods that a class must
implement.
Encapsulation is implemented using access modifiers. Access modifiers control who can
access the data and code in a class. The most common access modifiers are public,
protected, and private.
Public members can be accessed from anywhere. Protected members can only be accessed
from within the class and its subclasses. Private members can only be accessed from within
the class.
Here is an example of how data abstraction and encapsulation can be used together:
The Car class is an example of data abstraction. The user of the Car class doesn't need to
know how the engine or wheels work. They just need to know how to use the drive()
method.
The engine and wheels variables are examples of encapsulation. The data is hidden from the
user, and can only be accessed by the Car class.
Data abstraction and encapsulation are two important concepts in OOP. They help to make
code more secure, maintainable, and reusable.
Ques. 3 What is class and object in Java? Explain its advantage and how it creates the
object in Java ?
In Java, a class is a blueprint for an object. It defines the object's properties and methods. An
object is an instance of a class. It has the properties and methods defined by its class.
Classes and objects are the two fundamental building blocks of Java programming. They are
used to represent real-world entities and to organize code into logical units.
The `car` variable is a reference to the newly created object. It can be used to access the
object's properties and methods.
**Properties and Methods**
Classes can have properties and methods. Properties are variables that are associated with
an object. Methods are functions that are associated with an object.
The following code defines a property and a method for the `Car` class:
The `name` property is a string that stores the car's name. The `drive()` method prints a
message to the console that says "The car is driving."
Ques. 4 Explain polymorphism? Explain the method overloading and overriding using an
example ?
Polymorphism is the ability of an object to behave differently depending on its type. It is one
of the most important concepts in object-oriented programming (OOP).
There are two types of polymorphism in Java: **method overloading** and **method
overriding**.
**Method overloading** occurs when a class has multiple methods with the same name,
but different parameters. The compiler will choose the correct method to call based on the
number and types of arguments that are passed to the method.
For example, the following code defines two methods with the same name, `add()`:
The `add()` method with two parameters is called when two arguments are passed to the
method. The `add()` method with three parameters is called when three arguments are
passed to the method.
**Method overriding** occurs when a subclass defines a method with the same name,
signature, and return type as a method in its superclass. The subclass method will override
the superclass method.
For example, the following code defines a superclass `Animal` and a subclass `Dog`:
The `makeSound()` method in the `Dog` class overrides the `makeSound()` method in the
`Animal` class. When an object of the `Dog` class is created and the `makeSound()` method
is called, the `makeSound()` method in the `Dog` class will be executed.
Ques. 5 Explain the uses and importance of byte code with the help of examples ?
Bytecode is a set of instructions that can be executed by a Java Virtual Machine (JVM). It is
generated by a Java compiler from Java source code.
Bytecode is important for several reasons:
Portability: Bytecode is platform-independent, meaning that it can be run on any platform
that has a JVM. This makes Java applications very portable.
Security: Bytecode can be verified by the JVM before it is executed. This helps to prevent
malicious code from running on a user's computer.
Performance: Bytecode can be JIT-compiled by the JVM, which can improve performance.
class Main{
public static void main (String[] args) {
System.out.println("JAVA!");
}
}
OUTPUT:-
JAVA!
The Java Virtual Machine (JVM) is a software program that enables Java code to be
executed on any platform that has a JVM installed. The JVM is responsible for interpreting
and executing Java bytecode, which is a compiled form of Java source code.
The JVM provides several advantages over other programming languages, including:
• Portability: Java bytecode is platform-independent, meaning that it can be run on
any platform that has a JVM installed. This makes Java applications very portable.
• Security: The JVM can verify Java bytecode before it is executed, which helps to
prevent malicious code from running on a user's computer.
• Performance: The JVM can JIT-compile Java bytecode, which can improve
performance.
• Multithreading: The JVM supports multithreading, which allows multiple tasks to run
simultaneously.
• Garbage collection: The JVM automatically manages memory, which eliminates the
need for manual memory management
• Platform Interdependence
• Memory Management
• Security
• Exception Handling
Block 2
Ques. 1 Explain constructor overloading with a suitable example ?
Constructor overloading is a feature of Java that allows a class to have multiple constructors
with the same name but different parameter lists. This can be useful when you want to
create objects with different properties or behavior.
For example, the following code shows a class with two constructors:
The first constructor is the default constructor. It does not have any parameters. The second
constructor has one parameter, which is a string.
When you create an object of the `Employee` class, the compiler will choose the correct
constructor to use based on the number and types of arguments that are passed to the
`new` keyword.
For example, the following code creates two objects of the `Employee` class:
The first line of code will call the default constructor. The second line of code will call the
constructor with one parameter.
The output of the above code will be:
Unknown Enployee
Employee name is: Rakesh
Ques. 2 What do you understand by the “this” keyword? Explain its usage with an example
?
In Java, the "this" keyword is a reference to the current instance of a class. It is used to refer
to the instance variables, instance methods, or constructors of the current object. The "this"
keyword is particularly useful when there is a need to disambiguate between instance
variables and local variables or when we want to invoke one constructor from another
constructor within the same class.
The "this" keyword is a powerful tool for differentiating between variables, invoking
constructors, and accessing instance members. It helps improve code clarity and
maintainability in situations where there is ambiguity or need for self-reference within a
class.
Here are some additional examples of how the `this` keyword can be used:
Ques. 3 Explain with the help of the program, how objects can be passed as parameters in
Java ?
class MyClass {
String name;
public MyClass(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
MyClass object = new MyClass("Bard");
// Pass object as a parameter by value
printName(object);
// Print the object's name
object.printName();
}
public static void printName(MyClass object) {
// Change the object's name
object.name = "John Doe";
// Print the object's name
System.out.println(object.name);
}
}
Bard
John Doe
As you can see, the object's name was changed inside the printName() method, but the
original object's name was not changed. This is because the object was passed as a
parameter by value.
The following program shows how to pass an object as a parameter by reference:
class MyClass {
String name;
public MyClass(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
MyClass object = new MyClass("Bard");
// Pass object as a parameter by reference
changeName(object);
// Print the object's name
object.printName();
}
public static void changeName(MyClass object) {
// Change the object's name
object.name = "John Doe";
}
}
The output of the above program will be:
John Doe
As you can see, the object's name was changed inside the changeName() method, and the
change was reflected in the original object. This is because the object was passed as a
parameter by reference.
Constructor overloading is used to create objects with different initial states, while method
overloading is used to provide different implementations of a method with the same name.
Constructor overloading is resolved at compile time, while method overloading is resolved at
runtime.
Constructor overloading is typically used when there are multiple ways to create an object of
a class. Method overloading is typically used when there are multiple ways to perform a
task.
class Car {
Car() {
System.out.println("Default constructor");
}
Car(String color) {
System.out.println("Constructor with color parameter");
this.color = color;
}
private String color;
}
class Math {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
In Java, the finalize() method is a special method defined in the Object class. It is called by
the garbage collector before an object is garbage collected and its memory is reclaimed. The
purpose of the finalize() method is to provide an opportunity for an object to perform any
necessary cleanup or resource release operations before it is destroyed.
@Override
protected void finalize() throws Throwable {
try {
// Cleanup code or resource release operations
} finally {
super.finalize();
}
}
}
Ques. 6 What is inheritance and explain the different forms of inheritance with the help of
diagrams? What are the advantages of using inheritance?
Ques. 7 What is public access specifier? How is it different from private access specifiers?
Explain with example ?
In object-oriented programming, access specifiers are used to determine the visibility and
accessibility of class members (attributes and methods). There are three access specifiers in
Java: public, private, and protected.
The public access specifier allows class members to be accessed from anywhere in the
program. This means that public members can be accessed by other classes, functions, and
objects. Here's an example:
class MyClass {
public:
int x; // Public attribute
};
In this example, the `x` attribute is declared as public. This means that it can be accessed
from anywhere in the program.
The private access specifier restricts class members to be accessed only by other members
of the same class. This means that private members cannot be accessed by other classes,
functions, or objects. Here's an example:
class MyClass {
private:
int x; // Private attribute
};
In this example, the `x` attribute is declared as private. This means that it can only be
accessed by other members of the `MyClass` class.
Here's a summary of the differences between public and private access specifiers:
OR
In Java, access specifiers are keywords used to define the visibility and accessibility of
classes, methods, and variables within a program. The `public` access specifier is one of the
access modifiers available in Java. Here's an explanation of the `public` access specifier and
how it differs from the `private` access specifier:
• The `public` access specifier is the most permissive access level. It allows classes,
methods, and variables to be accessed from anywhere within the program, including
other classes, packages, and even outside the package.
• When a class, method, or variable is declared as `public`, it can be accessed by any
other class in the program.
- Example:
In the example above, the `MyClass` class and its `myPublicVariable` and
`myPublicMethod()` are declared with the `public` access specifier. This means that they can
be accessed from any other class within the program.
• The `private` access specifier is the most restrictive access level. It restricts the
visibility of classes, methods, and variables to the same class in which they are
defined.
• When a class, method, or variable is declared as `private`, it can only be accessed
from within the same class and is not accessible from other classes, including
subclasses and other packages.
- Example:
In summary, the `public` access specifier allows classes, methods, and variables to be
accessible from anywhere in the program, while the `private` access specifier restricts access
to only the same class. The choice of access specifier depends on the desired level of
encapsulation and the need for other classes to access the members of a class.
Output:
Woof!
The animal is eating.
The "final" keyword can be used to improve the safety and readability of Java code. By
making variables, methods, and classes final, you can prevent accidental changes that could
lead to errors. You can also make it clear to other developers that these elements of your
code should not be changed.
Advantages:
• Safety
• Readability
• Performance
Ques. 10 What is a classpath? Discuss the utility of classpath with a suitable example ?
In Java, the classpath is an environment variable used by the Java Virtual Machine (JVM) to
locate and load classes when running a Java program. It specifies a list of directories, JAR
files, and ZIP files where the JVM should look to find and load class files. The classpath is
used by a Java application to locate the Java classes it needs to run. It provides the compiler
a way to find classes or packages that are used in our class .
The utility of the classpath is to enable the JVM to locate and load the necessary classes and
resources for a Java program to run successfully. It ensures that the JVM can find the
bytecode (.class files) for the classes referenced in your code.
Here's an example of how you can set the classpath:
OR
The utility of the classpath is that it allows Java programs to access classes that are located
in different directories and JAR files. This makes it possible to develop large and complex
Java applications that are made up of multiple independent components.
For example, consider a Java application that consists of a graphical user interface (GUI)
component, a database access component, and a business logic component. The GUI
component could be located in one directory, the database access component could be
located in another directory, and the business logic component could be located in a JAR file.
The classpath would need to include all of these directories and JAR files in order for the
Java application to be able to run.
interface is a reference type that defines a set of methods that a class must implement. Interfaces
are similar to abstract classes, but they cannot have any instance variables or constructors.
example of how implementation interfaces can be used to decouple the design of a class from its
implementation:
The finally statement in Java is used to execute code regardless of whether an exception is
thrown or not. The finally block is always executed, even if the try block is terminated by a
return, break, or continue statement.
The finally block is useful for performing cleanup tasks, such as closing files or releasing
resources. Even if an exception is thrown, the finally block will ensure that these tasks are
completed.
Here is an example of a finally block that closes a file:
The finally block is also useful for handling unexpected errors. For example, the following
finally block prints an error message if an exception is thrown:
try {
// Code that might throw an exception
} finally {
// Handle any exceptions
if (exception != null) {
System.out.println("An exception has occurred: " +
exception.getMessage());
}
}
The finally statement is a powerful tool that can be used to ensure that important code is
always executed. It can be used for cleanup, error handling, and other tasks.
Advantages:-
• Guaranteed execution
• Error handling
• Reliability
Ques. 13 What do you understand “exception” in the context of Java? How it is handled,
explain with the help of suitable example code in Java ?
An exception in Java is an event that occurs during the execution of a program that disrupts
the normal flow of the program. Exceptions can be caused by a variety of factors, such as
invalid input, division by zero, or an error in the program code.
When an exception occurs, the Java Virtual Machine (JVM) will throw an exception object.
This object contains information about the exception, such as its type, message, and stack
trace. The program can then handle the exception by catching the exception object and
taking appropriate action.
try {
// Code that might throw an exception
} catch (Exception e) {
// Handle the exception
System.out.println("An exception has occurred: " +
e.getMessage());
}
try {
// Code that might throw an exception
} finally {
// Handle any exceptions
if (exception != null) {
System.out.println("An exception has occurred: " +
exception.getMessage());
}
}
In this example, the user is prompted to enter a number. The number is then divided by 2. If
the number is zero, an exception will be thrown. The catch block handles the exception by
printing an error message to the console.
By using exceptions, you can write Java programs that can handle unexpected errors
gracefully. This will make your programs more reliable and robust.
Ques. 14 What is a checked exception in java? How it's from an unchecked exception?
Explain briefly?
Checked exception is an exception that must be declared in the method signature. This
means that the method that throws the exception must either handle the exception itself or
declare that it throws the exception.
Unchecked exceptions, on the other hand, do not need to be declared in the method
signature. This means that the method that throws the exception does not need to handle
the exception itself or declare that it throws the exception.
public class UncheckedExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
int result = numbers[5]; // Accessing an invalid index
System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
The Java compiler will check for checked exceptions and will not allow a method to be
compiled if it does not handle or declare the checked exceptions that it throws.
Checked exceptions are typically used for exceptions that can be anticipated and handled.
For example, an IOException might be thrown if a file cannot be opened. This is an exception
that can be anticipated and handled, so it makes sense to require that methods that might
throw this exception declare it.
Unchecked exceptions, on the other hand, are typically used for exceptions that are
unexpected and cannot be handled. For example, an ArithmeticException might be thrown if
a number is divided by zero. This is an exception that is unexpected and cannot be handled,
so it does not make sense to require that methods that might throw this exception declare
it.
Advantages:-
Ques. 2 What is synchronization? Explain how methods are synchronized in java with the
help of the program ?
Ques. 3 Explain with the help of an example program, how interthread communication is
performed in java using wait() and notify() ?
t1.start();
t2.start();
}
}
In this program, two threads are created, t1 and t2. Thread t1 is responsible for waiting for
the count variable to reach 10, while thread t2 is responsible for incrementing the count
variable to 10.
The wait() and notify() methods are used to coordinate the activities of the two threads. The
wait() method causes the current thread to wait until it is notified by another thread. The
notify() method wakes up one of the threads that is waiting on the object.
In this program, thread t1 calls the wait() method while it is waiting for the count variable to
reach 10. Thread t2 calls the notify() method when it increments the count variable to 10.
This wakes up thread t1, which then exits.
Ques. 4 What are input stream and Output stream classes in java? List and explain any
two methods of each ?
In Java, an InputStream is used to read data from a source while an OutputStream is used to
write data to a destination.
Here are two methods of each:
InputStream
• read(byte[] b) - Reads some number of bytes from the input stream and stores them
into the buffer array b.
• skip(long n) - Skips over and discards n bytes of data from this input stream.
OutputStream
• write(byte[] b) - Writes b.length bytes from the specified byte array to this output
stream.
• flush() - Flushes this output stream and forces any buffered output bytes to be
written out.
Ques. 5 Write a Java program that accepts the input from the keyboard and writes it to a
text file ?
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
Ques. 6 How does String Buffer diff from a string? Write a program in java, which takes
your name as input and prints it in upper case ?
String Stringbuffer
String is an immutable class and its String buffer is mutable classes which
object can’t be modified after it is created can be used to do operation on string
object
Methods are not synchronized All methods are synchronized in this class
It is slow and consumes more memory It is fast and consumes less memory while
while concat strings concat strings
Fixed length Its growable
Not Synchornized Synchronized
Less Effiicient More Efficient
Overrides equal() Doesn’t overrides equal()
immutable mutable
import java.util.Scanner;
Ques. 7 Explain the stream Tokenizer with the help of the program ?
The StringTokenizer class in Java is used to break a string into tokens or smaller parts. It
provides a way to split a string based on a delimiter or separators. It is part of the java.util
package.
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String text = "Hello, World! How are you today?";
Block 4
Ques. 1 What is an applet? Explain the life cycle of Applet? List the method involved in it ?
Applet is a special type of program that runs within a web browser. It is typically used to
create interactive web applications and is embedded within an HTML page. Applets were
popular in the early days of the internet but have been largely replaced by other web
technologies like JavaScript and HTML5.
The life cycle of an applet refers to the sequence of events that occur from the moment the
applet is loaded into the browser until it is terminated or unloaded.
The following methods are involved in the life cycle of an applet:
• init(): The init() method is called when the applet is initialized. This is the time to
perform any necessary setup, such as loading resources or creating objects.
• start(): The start() method is called when the applet is started. This is the time to
begin any background tasks or to display the initial user interface.
• stop(): The stop() method is called when the applet is stopped. This is the time to
stop any background tasks and to clean up any resources that are no longer needed.
• paint(): The paint() method is called whenever the applet needs to be redrawn. This
is the time to update the user interface to reflect any changes that have occurred.
• destroy(): The destroy() method is called when the applet is destroyed. This is the
time to free any resources that are no longer needed.
Ques. 2 How does Java handle events? Describe the different components of an event?
Write a program in Java to capture an event generated by the keyboard ?
Java handles events through an event-driven programming model. In this model, an event is
an action or occurrence that happens during the execution of a program, such as a button
click, mouse movement, or keyboard input. Java provides a robust event handling
mechanism that allows developers to write code that responds to these events.
The different components of an event in Java are as follows:
1. Event Source: The event source is the object that generates the event. It can be a GUI
component like a button, text field, or a user action like a key press or mouse click.
2. Event Object: The event object encapsulates information about the event. It contains
details such as the type of event, the source of the event, and any additional data associated
with the event
3. Event Listener: An event listener is an object that listens for events from a specific event
source. It implements an interface that defines the methods to be invoked when the
corresponding events occur.
4. Event Handler: An event handler is a block of code that responds to an event. It is typically
defined within the event listener and is executed when the corresponding event is triggered.
Import java.awt.*;
Import java.awt.event.*;
Public keyboardPanel(){
addKeyListener(this);
}
public void keyPressed(KeyEvent event) {
System.out.println("Key pressed: " + event.getKeyChar());
}
public void keyReleased(KeyEvent event) {
System.out.println("Key released: " + event.getKeyChar());
}
public void keyTyped(KeyEvent event) {
System.out.println("Key typed: " + event.getKeyChar());
}
The KeyListener interface has three methods that are called when a key event occurs:
keyPressed(): This method is called when a key is pressed.
keyReleased(): This method is called when a key is released.
keyTyped(): This method is called when a key is typed.
The KeyEvent object that is passed to these methods contains information about the event,
such as the key that was pressed, released, or typed.
FlowLayout arranges components in a row, flowing from left to right. When the row is filled,
the next component is placed on the next row.It is the default layout manager for many
containers, including JPanel.
Eample: flowlayput.java
import java.awt.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
}
GridLayout arranges components in a grid-like structure with rows and columns of equal
size. Each cell in the grid is of the same width and height.
The grid layout is ideal for creating forms, tables, or any layout where components need to
be evenly distributed in a grid pattern.
Example: Gridlayout.java
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridayout(){
f=new JFrame();
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
}
Ques. 5 Write the steps of JDBC in establishing a connection for creating a dynamic
website ?
To establish a connection using JDBC for creating a dynamic website, you can
follow these steps:
To establish a connection for creating a dynamic website using JDBC (Java Database
Connectivity), you need to follow these steps:
1. Load the JDBC driver:
Register the JDBC driver class using `Class.forName()` to load the appropriate driver for your
database. For example:
Class.forName("com.mysql.cj.jdbc.Driver");
3. Create a statement:
Create a statement object from the `Connection` to execute SQL queries. For example:
while (resultSet.next()) {
String username = resultSet.getString("username");
String email = resultSet.getString("email");
// Process the retrieved data
}
resultSet.close();
statement.close();
connection.close();
It's important to handle exceptions and ensure proper error handling in each step of the
JDBC process. Additionally, it's recommended to use connection pooling to improve
performance and manage database connections efficiently in a dynamic web application.
Ques. 6 Explain the Java RMI architecture with the help of a diagram ?
Java RMI is a mechanism that allows objects in one Java Virtual Machine (JVM) to invoke
methods on objects residing in a different JVM, either on the same physical machine or over
a network. It enables distributed computing and facilitates communication between
different Java applications or components.
The Java RMI architecture involves several key components:
1. Remote Interface:
The remote interface defines the methods that can be invoked remotely. It extends the
`java.rmi.Remote` interface and declares the remote methods that can be called by clients.
2. Remote Object:
The remote object is an implementation of the remote interface. It represents the object
that can be accessed remotely by clients. The remote object must extend
`java.rmi.server.UnicastRemoteObject` to enable remote invocation.
The Java RMI architecture follows a distributed object model, where the client invokes
methods on the stub object, which transparently forwards the request to the remote object
through the network. The remote object processes the request, and the result (if any) is
returned back to the client.
The Java RMI architecture simplifies distributed computing in Java by providing a transparent
mechanism for remote method invocation and object communication.
Ques. 7 What are cookies and session objects? Where do use them ?
Cookies and session objects are both ways for a web server to store information about a
user. However, they differ in how and where they store the information, and how long the
information is stored.
Cookies
Cookies are small text files that are stored on the user's computer by the web server. They
can be used to store information about the user, such as their preferences, login status, or
shopping cart contents. Cookies are typically used to improve the user experience by making
it easier for users to navigate a website and to personalize the content that they see.
Session Objects
Session objects are objects that are created by a web server and are associated with a
particular user session. They are stored in memory on the server and are destroyed when
the user session ends. Session objects can be used to store information about the user, such
as their login status, the pages that they have visited, or the items that they have added to
their shopping cart.
Where are they used?
Cookies and session objects are used in a variety of web applications, including:
E-commerce websites: E-commerce websites use cookies to store information about the
user's shopping cart, such as the items that they have added to the cart and the quantity of
each item. This information is used to calculate the total cost of the order and to process the
payment.
Social media websites: Social media websites use cookies to store information about the
user's preferences, such as their preferred language and the size of the text on the website.
This information is used to personalize the user's experience on the website.
News websites: News websites use cookies to store information about the articles that the
user has read. This information is used to recommend other articles that the user might be
interested in.
Advantages:
• The data (name and age) is encapsulated within the `PersonBean` class.
• Access to the properties is provided through public getter and setter methods.
• This ensures controlled access and allows for data validation or additional logic if
needed.
3. Default Constructor:
• The `PersonBean` class provides a public no-argument constructor.
• This allows frameworks or tools to create instances of the JavaBean using reflection
or other mechanisms.
4. Serializable:
• The getter and setter methods follow the naming conventions for JavaBeans.
• The getter method for the `name` property is `getName()`, and the setter method is
`setName()`.
• Similarly, the getter method for the `age` property is `getAge()`, and the setter
method is `setAge()`.
This example demonstrates the basic features of a JavaBean: encapsulated properties with
getter and setter methods, default constructor, serializability, and adherence to naming
conventions. JavaBeans are commonly used in Java development for creating modular and
reusable components that can be easily integrated into various frameworks and tools.