Advance Java Unit 3
Advance Java Unit 3
8. Write the purpose and syntax of the regionMatches() method in string handling.
The regionMatches( ) method compares a specific region inside a string with another specific region
in another string. There is an overloaded form that allows you to ignore case in such comparisons.
Here are the general forms for these two methods:
16. What is the purpose of the ensureCapacity() method in StringBuffer? give its general form
If you want to preallocate room for a certain number of characters after a StringBuffer has been
constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in
advance that you will be appending a large number of small strings to a StringBuffer.
ensureCapacity( ) has this general form: void ensureCapacity(int capacity). Here, capacity specifies
the size of the buffer.
17. How does the setLength() method modify the length of a StringBuffer and what happens
to existing data when the length is changed?
setLength() method is used to set the length of the buffer within a StringBuffer object.
void setLength(int len)
When you increase the size of the buffer, null characters are added to the end of the existing buffer.
If you call setLength( ) with a value less than the current value returned by length( ), then the
characters stored beyond the new length will be lost.
18. What do the charAt() and setCharAt() methods do in StringBuffer?
The value of a single character can be obtained from a StringBuffer via the charAt( ) method.
char charAt(int where) , where specifies the index of the character being obtained.
You can set the value of a character within a StringBuffer using setCharAt( ).
void setCharAt(int where, char ch) , where specifies the index of the character being set,
and ch specifies the new value of that character.
19. What does the append() method do in StringBuffer? Which function is called for each
parameter to obtain its string representation.
The append( ) method concatenates the string representation of any other type of data to the end of
the invoking StringBuffer object. Here are a few of its forms:
StringBuffer append(String str), StringBuffer append(int num), StringBuffer append(Object obj)
[Link]( ) is called for each parameter to obtain its string representation. The result is
appended to the current StringBuffer object.
20. What does the insert() method do in StringBuffer and how is it different from append()?
The insert() method inserts a specified string at a given index position within the existing string
buffer content.
The append() method appends a given string to the end of the existing string buffer content.
21. How does StringBuilder differ from StringBuffer?
Refer [Link]. 1
22. What are the roles of the Stub and Skeleton objects in RMI?
The communication between client and server is handled by using two intermediate objects: Stub
object (on client side) and Skeleton object (on server-side).
23. What is RMI?
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM. The RMI provides remote communication between the applications using two objects stub
and skeleton.
24. What is Syntactic transparency?
Syntactic transparency implies that there should be a similarity between the remote process and a
local procedure.
lOMoARcPSD|56807518
3. With syntax and example, explain the following StringBuffer class methods
a. insert() b. deleteCharAt()
a. insert() : This method inserts a specified string at a given index position within the existing
string buffer content. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
lOMoARcPSD|56807518
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object.
Example: StringBuffer buffer = new StringBuffer("Hello World!");
[Link](6, ", ");
[Link]("Inserted string: " + buffer);
b. deleteCharAt(): The deleteCharAt( ) method deletes the character at the specified index from
the StringBuffer object.
Syntax: StringBuffer deleteCharAt(int loc)
Here, loc specifies the index of the character to be deleted.
Example: StringBuffer buffer = new StringBuffer("Hello World!");
[Link](5);
[Link]("String after deletion: " + buffer);
4. With syntax and example, explain the following StringBuffer class methods
a. substring() b. lastIndexOf()
a. substring() : You can obtain a portion of a StringBuffer by calling substring( ). It has the
following two forms:
i. String substring(int startIndex). This form returns the substring that starts at startIndex and runs
to the end of the invoking StringBuffer object.
ii. String substring(int startIndex, int endIndex). It returns the substring that starts at startIndex and
runs through endIndex–1.
Example: StringBuffer str = new StringBuffer (“Hello World!”);
String sub1 = [Link](6);
String sub2 = [Link](0, 5);
[Link](“Substrings:“ +sub1+ “,“ +sub2);
//Output:World!,Hello
b. lastIndexOf() : Searches for the last occurrence of a character or substring. It has the following
two forms:
i. int lastIndexOf(String str) : Searches the invoking StringBuffer for the last occurrence of str.
Returns the index of the match, or –1 if no match is found.
ii. int lastIndexOf(String str, int startIndex) : Searches the invoking StringBuffer for the last
occurrence of str, beginning at startIndex. Returns the index of the match, or –1 if no match is
found.
Example: StringBuffer str = new StringBuffer (“Hello World!”);
int index1 = [Link](“o”);
int index2 = [Link](“o”, 7);
[Link](“Indexes: “ +index1+ “, “ +index2); //Output:7,7
iv. toCharArray() : To convert all the characters in a String object into a character array. It has this
general form: char[ ] toCharArray( )
Example: String str = "Hello";
char[] charArray = [Link]();
[Link]("Character array: " + [Link](charArray));
//Output: [H,e,l,l,o]
ii. equalsIgnoreCase() : This method compares the content of two strings ignoring their case and
returns `true` if they are equal, otherwise `false`. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object.
Example: String str1 = "hello";
String str2 = "HELLO";
boolean result2 = [Link](str2); // true
8. Explain the difference between the indexOf() and lastIndexOf() methods in the String class.
Give an example for each method to illustrate their functionality.
• indexOf( ) - Searches for the first occurrence of a character or substring.
Returns the index of the first occurrence or -1 on failure.
Searches the string from the beginning to the end.
Syntax: int indexOf(int ch), int indexOf(String str)
Example: String str = "hello world";
int index = [Link]('o');
[Link]("Index of 'o': " + index); // Output: Index of 'o': 4
• lastIndexOf( ) - Searches for the last occurrence of a character or substring.
Returns the index of the last occurrence or -1 on failure.
Searches the string from the end to the beginning.
Syntax: int lastIndexOf(int ch), int lastIndexOf(String str)
Example: String str = "hello world";
int index = [Link]('o');
[Link]("Index of 'o': " + index); // Output: Index of 'o': 7
9. Describe two common approaches for modifying Strings in Java with an example.
a. substring() : Refer [Link]. 4(a)
b. concat() : The `concat()` method is used to concatenate one string with another string. It returns a
new string that represents the concatenation of the two strings.
Syntax: String concat(String str)
Example: String str1 = "Hello";
String str2 = " World!";
String result = [Link](str2);
[Link](result); // Output: Hello World!
10. Explain the use of charAt() and setCharAt() methods with suitable example.
The value of a single character can be obtained from a StringBuffer via the charAt( ) method. It
returns the character at the specified index within the StringBuffer object.
char charAt(int where) , where specifies the index of the character being obtained.
You can set the value of a character within a StringBuffer using setCharAt( ).
void setCharAt(int where, char ch) , where specifies the index of the character being set,
and ch specifies the new value of that character.
Example: class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " + [Link](1));
[Link](1, 'i');
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}}
lOMoARcPSD|56807518
11. Explain the purpose of the valueOf() method in the String class with an example.
The `valueOf()` method in the String class is used to convert different data types into string
representation. It provides a convenient way to create strings from various types of data.
Purpose of valueOf() Method:
• Converts Other Data Types to Strings: The `valueOf()` method converts data types such as
integers, floating-point numbers, characters, booleans, and objects into their string representation.
• String Concatenation: It's often used in string concatenation operations where non-string data
needs to be combined with strings.
Here are a few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
Example: String str = [Link](10); // Convert integer to string-
In this example, the `valueOf()` method is used to convert the integer value `10` into its string
representation. The result is assigned to the string variable `str`. Now, `str` holds the string value
"10", which can be used in string operations.
12. What is the use of replace() method? Explain.
You can replace one set of characters with another set inside a StringBuffer object by calling
replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the
substring at startIndex through endIndex–1 is replaced. The replacement string is passed in
str. The resulting StringBuffer object is returned.
Example: class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](5, 7, "was");
[Link]("After replace: " + sb);
}
}
Output: After replace: This was a test.
13. With an example explain the four methods of StringBuffer class.
Refer [Link]. 3, 10, 12,
14. What is the usage of delete() and deleteCharAt() methods? Explain them using their
syntax and an example.
i. delete() : The delete( ) method deletes a sequence of characters from the invoking object.
Syntax: StringBuffer delete(int startIndex, int endIndex)
Here, startIndex specifies the index of the first character to remove, and endIndex
specifies an index one past the last character to remove.
Example: StringBuffer buffer = new StringBuffer("Hello World!");
[Link](6,11);
[Link]("After deletion: " + buffer); //Output: Hello!
15. Explain in detail the method that is used by the RMI client to connect to remote RMI
servers?
The communication between client and server is handled by using two intermediate objects: Stub
object (on client side) and Skeleton object (on server-side) as also can be depicted from below
media as follows:
1. Define the Remote Interface: You define a Java interface that extends the [Link]
interface. This interface defines the methods that the client can invoke on the remote object.
2. Implement the Remote Object: You implement the remote interface on the server side. This
class will extend [Link] or [Link] and
implement the methods defined in the remote interface. The server class provides the
implementation for the methods declared in the remote interface.
3. Create and Start the RMI Registry: The server creates an RMI registry, which acts as a central
registry for remote objects. The registry listens for incoming requests on a specific port.
4. Bind the Remote Object to the Registry: The server binds the remote object to the RMI registry
using a unique name. This makes the remote object accessible to clients by its name.
5. Lookup the Remote Object on the Client Side: The client looks up the remote object in the
RMI registry using the naming service ([Link] or [Link]). The
client obtains a reference to the remote object, which it can then use to invoke remote methods.
6. Invoke Remote Methods: The client invokes methods on the remote object reference obtained
from the RMI registry. RMI handles the communication details, including parameter organizing,
network communication, and error handling, transparently to the client.
7. Handle Exceptions: Both the client and server should handle [Link] and
any other application-specific exceptions that may occur during remote method invocation.
16. Explain the concepts of object persistence and serialization in Java. Provide a brief
overview of each concept, highlighting their significance in software development.
Object Persistence:
• Object persistence refers to the ability to store and retrieve objects beyond the lifetime of the
application's execution.
• With object persistence, the state of an object can be saved to a persistent storage medium (such as
a database, file system, or cloud storage) and later can be restored, allowing the application to work
with the same data across different runs or even different instances of the application.
• Persistence is essential for applications that need to maintain data integrity, share data between
multiple users or instances, or store data for long-term use.
Serialization:
• Serialization is the process of converting an object into a stream of bytes, which can be easily
stored or transmitted and later reconstructed to create an identical copy of the original object.
• In Java, serialization is achieved by implementing the Serializable interface, which is a marker
interface indicating that the class is serializable.
lOMoARcPSD|56807518
• Serializable objects can be written to an output stream (e.g., a file or network socket) using an
ObjectOutputStream, and later read from an input stream using an ObjectInputStream.
• Serialization allows objects to be easily stored to disk, transmitted over a network, or saved to a
database, enabling object persistence.
17. Explain four key challenges associated with distributed computing systems.
• Network latency: The communication network in a distributed system can introduce latency,
which can affect the performance of the system.
• Distributed coordination: Distributed systems require coordination among the nodes, which can
be challenging due to the distributed nature of the system.
• Security: Distributed systems are more vulnerable to security threats than centralized systems due
to the distributed nature of the system.
• Data consistency: Maintaining data consistency across multiple nodes in a distributed system can
be challenging.
18. Describe the three key components that make up a Distributed Computing System.
• Devices or Systems: The devices or systems in a distributed system have their own processing
capabilities and may also store and manage their own data.
• Network: The network connects the devices or systems in the distributed system, allowing them
to communicate and exchange data.
• Resource Management: Distributed systems often have some type of resource management
system in place to allocate and manage shared resources such as computing power, storage, and
networking.
19. Explain how a Social Media platform can be considered a Distributed Computing System.
Identify the key components involved and their roles.
Any Social Media can have its Centralized Computer Network as its Headquarters and computer
systems that can be accessed by any user and using their services will be the Autonomous Systems
in the Distributed System Architecture.
• As we can see that each Autonomous System has a common Application that can have its own
data that is shared by the Centralized Database System.
• To Transfer the Data to Autonomous Systems, Centralized System should be having a Middleware
Service and should be connected to a Network.
• Middleware Services enable some services which are not present in the local systems or
centralized system default by acting as an interface between the Centralized System and the local
systems. By using components of Middleware Services systems communicate and manage data.
• The Data which is been transferred through the database will be divided into segments or modules
and shared with Autonomous systems for processing.
• The Data will be processed and then will be transferred to the Centralized system through the
network and will be stored in the database.
20. Explain the concept of Remote Procedure Calls (RPC) and its working mechanism with its
five key elements.
Client: The client process initiates RPC. The client makes a
standard call, which triggers a correlated procedure in the client
stub.
Client Stub: Stubs are used by RPC to achieve semantic
transparency. The client calls the client stub. Client stub does
the following tasks:
When the client stub receives a request from a client, it
packs(marshalls) the parameters and required specifications of
remote/target procedure in a message.
When the client stub receives the result values after execution,
it unpacks (unmarshalled) those results and sends them to the
Client.
RPC Runtime: The RPC runtime is in charge of message
transmission between client and server via the network.
Retransmission, acknowledgement, routing, and encryption are
all tasks performed by it.
On the client-side, it receives the result values in a message from the server-side, and then it further
sends it to the client stub whereas, on the server-side, RPC Runtime got the same message from the
server stub when then it forwards to the client machine.
Server Stub: The first task performed by server stub is that it unpacks(unmarshalled) the call
request message which is received from the local RPC Runtime and makes a regular call to invoke
the required procedure in the server.
The second task performed by server stub is that when it receives the server’s procedure execution
result, it packs it into a message and asks the local RPC Runtime to transmit it to the client stub
where it is unpacked.
Server: After receiving a call request from the client machine, the server stub passes it to the server.
The execution of the required procedure is made by the server and finally, it returns the result to the
server stub so that it can be passed to the client machine using the local RPC Runtime.
21. What is RMI? Explain its key components.
The Remote Method Invocation (RMI) architecture in Java facilitates communication between Java
objects residing in different Java Virtual Machines (JVMs) over a network. It allows objects to
invoke methods on remote objects as if they were local objects. The RMI architecture typically
involves several components and follows a client-server model:
lOMoARcPSD|56807518
1. Remote Interface: It is a Java interface that defines the methods that can be invoked remotely by
clients. It extends the [Link] interface. Each method in the remote interface must declare
[Link] in its throws clause to handle remote method invocation errors.
2. Remote Object Implementation: It is a Java class that provides the actual implementation of the
methods defined in the remote interface. It is responsible for executing the methods invoked
remotely by clients.
3. RMI Registry: It is a simple naming service provided by Java RMI that allows clients to look up
remote objects by name. It acts as a central registry where remote objects are bound to names,
making them accessible to clients. The server creates an RMI registry, and clients use it to locate
remote objects.
4. Client: It is the application or component that initiates communication with remote objects. It
obtains a reference to the remote object from the RMI registry using the naming service provided by
[Link]. Once it has the reference, the client can invoke methods on the remote object as if
it were a local object.
5. Marshalling and Unmarshalling: RMI handles the marshalling (serialization) and
unmarshalling (deserialization) of method parameters and return values transparently to the client
and server.
6. Network Communication: RMI uses TCP/IP as the underlying network protocol for
communication between the client and server JVMs. It establishes a connection between the client
and server JVMs, allowing them to exchange method invocations and data.
23. Outline the key steps involved in developing a basic Remote Method Invocation (RMI)
application.
In this example, the request specifies two numbers. The server adds these together and returns the
sum.
Step One: Enter and Compile the Source Code
This application uses four source files.
[Link], defines the remote interface that is provided by the server.
[Link], implements the remote interface.
[Link], contains the main program for the server machine.
[Link], implements the client side of this distributed application.
Compile all the four source code file using javac.
lOMoARcPSD|56807518