Ajava - III Unit
Ajava - III Unit
2 marks:
1. Write the any two differences between StringBuffer and StringBuilder class.
StringBuffer StringBuilder
Synchronized (thread-safe). Not synchronized (not thread-safe).
Slower performance due to synchronization overhead. Faster performance.
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)
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!");
buffer.insert(6, ", ");
System.out.println("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!");
buffer.deleteCharAt(5);
System.out.println("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 = str.substring(6);
String sub2 = str.substring(0, 5);
System.out.println(“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 = str.lastIndexOf(“o”);
int index2 = str.lastIndexOf(“o”, 7);
System.out.println(“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 = str.toCharArray();
System.out.println("Character array: " + Arrays.toString(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 = str1.equals(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 = str.indexOf('o');
System.out.println("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 = str.lastIndexOf('o');
System.out.println("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 Q.No. 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 = str1.concat(str2);
System.out.println(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");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}}
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 = String.valueOf(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.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output: After replace: This was a test.
13. With an example explain the four methods of StringBuffer class.
Refer Q.No. 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!");
buffer.delete(6,11);
System.out.println("After deletion: " + buffer); //Output: Hello!
1. Define the Remote Interface: You define a Java interface that extends the java.rmi.Remote
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 java.rmi.server.UnicastRemoteObject or java.rmi.server.RemoteObject 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 (java.rmi.Naming or java.rmi.registry.LocateRegistry). 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 java.rmi.RemoteException 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.
• 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.
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.
AddServerIntf.java, defines the remote interface that is provided by the server.
AddServerImpl.java, implements the remote interface.
AddServer.java, contains the main program for the server machine.
AddClient.java, implements the client side of this distributed application.
Compile all the four source code file using javac.
Step Two: Generate a Stub
To generate a stub, we use a tool called the RMI compiler, which is invoked from the command
line, as shown here: rmic AddServerImpl. This command generates the file
AddServerImpl_Stub.class.
Step Three: Install Files on the Client and Server Machines
Copy AddClient.class, AddServerImpl_Stub.class, and AddServerIntf.class to a directory Stub.class,
and AddServer.class to a directory on the server machine.
Step Four: Start the RMI Registry on the Server Machine
Start the RMI Registry from the command line, as shown here: start rmiregistry
When this command returns, a new window has been created.
Step Five: Start the Server
The server code is started from the command line, as shown here: java AddServer
Step Six: Start the Client
The Add Client software requires three arguments: the name or IP address of the server machine and
the two numbers that are to be summed together. We may invoke it from the command line by using
one of the two formats shown here: java AddClient server1 8 9 java
AddClient 11.12.13.14 8 9
In the first line, the name of the server is provided. The second line uses its IP address (11.12.13.14)
Sample output from this program is shown here:
The first number is: 8
The second number is: 9
The sum is: 17.0
24. Explain the Advantages and Disadvantages distributed computing.
Advantages of the Distributed Computing System are:
• Scalability: Distributed systems are generally more scalable than centralized systems, as they can
easily add new devices or systems to the network to increase processing and storage capacity.
• Reliability: Distributed systems are often more reliable than centralized systems, as they can
continue to operate even if one device or system fails.
• Flexibility: Distributed systems are generally more flexible than centralized systems, as they can
be configured and reconfigured more easily to meet changing computing needs.
There are a few limitations to Distributed Computing System
• Complexity: Distributed systems can be more complex than centralized systems, as they involve
multiple devices or systems that need to be coordinated and managed.
• Security: It can be more challenging to secure a distributed system, as security measures must be
implemented on each device or system to ensure the security of the entire system.
• Performance: Distributed systems may not offer the same level of performance as centralized
systems, as processing and data storage is distributed across multiple devices or systems.