Java Unit 3 Qbank
Java Unit 3 Qbank
Qns 1. Write the any two differences between StringBuffer and StringBuilder class.
• StringBuffer is synchronized → thread-safe (safe to use in multithreaded environments).
• StringBuilder is not synchronized → not thread-safe (faster but unsafe in concurrent use).
• StringBuffer is slower because of synchronization overhead.
• StringBuilder is faster since it doesn’t use synchronization.
Qns 3. Write two ways to create a String object using the String constructors, and provide an example for each
1. Creating a String from a character array
You can pass a char[] to the String constructor.
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str1 = new String(chars);
[Link](str1);
2. Creating a String from another String object
You can create a new String using an existing String.
String original = "Java";
String str2 = new String(original);
[Link](str2);
Qns 4. What is the purpose of the toString() method in the context of strings.
It converts an object into a readable String format.
When working with strings, it ensures that the object’s content can be displayed or printed as text.
It is commonly used when printing objects using [Link]()
Qns 6. What are the different ways to extract individual characters from a string? Give the syntax
1. Using charAt() method
• Returns the character at a specified index.
Syntax: char ch = [Link](index);
2. Using toCharArray() method
• Converts the string into a character array, then you can access elements.
Syntax: char[] arr = [Link]();
char ch = arr[index];
3. Using getChars() method
• Copies characters from a string into a character array.
Syntax: [Link](startIndex, endIndex, destinationArray, destStart);
Qns 7. Provide the syntax and an example for the charAt() method to extract characters from a string.
The charAt() method is used to extract a character from a string at a specified index.
Syntax: char variableName = [Link](index);
• stringName → the string variable
• index → position of the character (starts from 0)
Example:
Page : 1
Advanced Java Unit 3
public class Main {
public static void main(String[] args) {
String str = "Hello";
char ch = [Link](1);
[Link](ch);
}
}
Qns 8. Write the purpose and syntax of the regionMatches() method in string handling
The regionMatches() method is used to compare a specific region (substring) of one string with a region of another
string.
It checks whether the specified portions of two strings are equal.
• boolean result = [Link](ignoreCase, startIndex1, string2, startIndex2, length);
• startIndex1 → starting index in first string
• string2 → second string to compare
• startIndex2 → starting index in second string
• length → number of characters to compare
• ignoreCase → true (ignore case), false (case-sensitive)
Qns 9. Demonstrate the usage of the startsWith() and endsWith() methods in string handling.
1. startsWith() Method
Purpose:
Checks if a string starts with a specified prefix.
Syntax: boolean result = [Link](prefix);
Example:
public class Main {
public static void main(String[] args) {
String str = "Hello World";
boolean result = [Link]("Hello");
[Link](result);
}
}
Output:
true
2. endsWith() Method
Purpose:
Checks if a string ends with a specified suffix.
Syntax: boolean result = [Link](suffix);
Example:
public class Main {
public static void main(String[] args) {
String str = "Hello World";
[Link](result);
}
}
Page : 2
Advanced Java Unit 3
2. equals() Method
• Compares actual content (values) of two objects.
• In the String class, it checks whether the characters are the same.
Qns 11. Describe the functionalities of the indexOf and lastIndexOf methods used for string manipulation
1. indexOf() Method
• Returns the index of the first occurrence of a character or substring.
• Returns -1 if the character or substring is not found.
Syntax:
int index = [Link](charOrSubstring);
int index = [Link](charOrSubstring, fromIndex); // optional starting index
2. lastIndexOf() Method
• Returns the index of the last occurrence of a character or substring.
• Returns -1 if not found.
Syntax:
int index = [Link](charOrSubstring);
int index = [Link](charOrSubstring, fromIndex); // optional starting index
Qns 12. What are the two forms of the substring() method and what do their arguments represent?
1. substring(int beginIndex)
• Returns a substring starting from beginIndex to the end of the string.
Arguments:
• beginIndex → the starting index of the substring (inclusive, counting starts from 0).
Syntax: String sub = [Link](beginIndex);
2. substring(int beginIndex, int endIndex)
• Returns a substring starting from beginIndex up to but not including endIndex.
Arguments:
• beginIndex → starting index (inclusive)
• endIndex → ending index (exclusive)
Syntax: String sub = [Link](beginIndex, endIndex);
Qns 13. Describe the two forms of the replace() method and their functionalities.
replace() Method in Java
The replace() method is used to replace characters or substrings in a string. There are two forms of this method:
1. replace(char oldChar, char newChar)
• Replaces all occurrences of a specified character (oldChar) with another character (newChar).
Syntax: String newString = [Link](oldChar, newChar);
2. replace(CharSequence target, CharSequence replacement)
• Replaces all occurrences of a substring (target) with another substring (replacement).
Syntax: String newString = [Link](target, replacement);
Qns 14. What is the purpose of the valueOf() method in Java and how does it relate to the toString() method?
The valueOf() method is used to convert different types of values into a String. This is useful when you want to
represent numbers, characters, booleans, or objects as strings.
Primitive types to String
String str1 = [Link](123); // converts int to String
String str2 = [Link](45.6); // converts double to String
String str3 = [Link](true); // converts boolean to String
Object to String
Object obj = new Integer(10);
String str = [Link](obj); // calls [Link]() internally
Qns 15. How does StringBuffer differ from String in terms of mutability and growth?
Page : 3
Advanced Java Unit 3
String → Immutable, fixed length, slow for frequent modifications.
StringBuffer → Mutable, dynamically grows, faster for multiple modifications.
Qns 16. What is the purpose of the ensureCapacity() method in StringBuffer? give its general form
The ensureCapacity() method is used to ensure that a StringBuffer has at least the specified minimum capacity.
• If the current capacity is less than the specified value, the capacity is automatically increased.
• This helps improve performance when you know in advance that the buffer will need to grow, as it reduces
frequent reallocations.
Qns 17. How does the setLength() method modify the length of a StringBuffer and what happens to existing data when
the length is changed?
The setLength() method is used to change the length of a StringBuffer. It can either truncate or expand the
buffer.
Truncating the StringBuffer
If the new length is less than the current length, the extra characters at the end are removed.
Expanding the StringBuffer
If the new length is greater than the current length, the buffer is extended, and the new positions are filled
with null characters
Qns 18. What do the charAt() and setCharAt() methods do in StringBuffer?
1. charAt() Method
• Returns the character at a specified index in the StringBuffer.
• Does not modify the buffer.
2. setCharAt() Method
• Modifies the character at a specified index in the StringBuffer.
• Directly changes the buffer’s content (since StringBuffer is mutable).
Qns 19. What does the append() method do in StringBuffer?Which funciton is called for each parameter to obtain its
string representation.
The append() method is used to add (concatenate) data to the end of a StringBuffer. Since StringBuffer is mutable,
the original buffer is modified directly without creating a new object.
For objects and non-string data, the [Link]() method is called internally to convert the parameter into a string
representation before appending.
This ensures all types can be appended as strings.
Qns 20. What does the insert() method do in StringBuffer and how is it different from append()?
• The insert() method is used to insert data at a specified index in a StringBuffer.
• Unlike append(), which adds data only at the end, insert() can place data anywhere in the buffer.
• The StringBuffer is modified directly because it is mutable.
Qns 22. What are the roles of the Stub and Skeleton objects in RMI?
1. Stub
• Acts as the client-side proxy for the remote object.
• Provides the same methods as the remote interface.
• Handles network communication, including:
Page : 4
Advanced Java Unit 3
o Marshaling (converting method arguments into a transmittable format)
o Sending the request to the remote JVM
o Receiving the response and unmarshaling it back into Java objects
• Makes remote method invocation transparent to the client.
2. Skeleton
• Exists on the server-side (pre-Java 2 SDK; in modern RMI, skeleton is optional).
• Acts as the dispatcher for incoming calls from the stub.
• Handles:
o Unmarshaling incoming method parameters
o Invoking the actual method on the remote object implementation
o Marshaling the return value or exception back to the stub
Qns 27. State two advantages of using distributed computing over centralized computing.
1. Load sharing (better performance)
• In Java RMI, objects can run on different machines (servers)
• Work is distributed across multiple systems instead of one central server
• This reduces overload and improves response time
2. Fault tolerance (higher reliability)
• If one remote server fails, other servers can still provide services
• The system does not completely stop like in centralized computing
Qns 28. State any four key characteristics that define a distributed computing system.
Multiple Devices or Systems: Processing and data storage is distributed across multiple devices or systems.
Peer-to-Peer Architecture: Devices or systems in a distributed system can act as both clients and servers, as they can
both request and provide services to other devices or systems in the network.
Shared Resources: Resources such as computing power, storage, and networking are shared among the devices or
systems in the network.
Horizontal Scaling: Scaling a distributed computing system typically involves adding more devices or systems to the
network to increase processing and storage capacity. This can be done through hardware upgrades or by adding
additional devices or systems to the network.
Page : 5
Advanced Java Unit 3
Qns 30. Why is the RMI Registry important in Remote Method Invocation (RMI) applications?
RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers
this object with the RMIregistry (using bind() or reBind() methods). These are registered using a unique name known
as bind name. It allows remote clients to get a reference to these objects.
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the object from
the registry using its bind name (using lookup() method).
(4 to 6 marks)
Qns 1. With syntax and example explain the following String class methods
a. split()
You can reduce an input sequence into its individual tokens by using the split( ) method
defined by Pattern. One form of the split( ) method is shown here:
String[ ] split(CharSequence str)
It processes the input sequence passed in str, reducing it into tokens based on the delimiters
specified by the pattern.
For example, the following program finds tokens that are separated by spaces, commas,
periods, and exclamation points:
// Use split().
import [Link].*;
class RegExpr9 {
public static void main(String args[]) {
// Match lowercase words.
Pattern pat = [Link]("[ ,.!]");
String strs[] = [Link]("one two,alpha9 12!done.");
for(int i=0; i < [Link]; i++)
[Link]("Next token: " + strs[i]);
}
}
b. regionMatches()
Although the pattern-matching techniques described in the foregoing offer the greatest flexibility and power, there
are two alternatives which you might find useful in some circumstances. If you only need to perform a one-time
pattern match, you can use the matches( ) method defined by Pattern.
It is shown here: static boolean matches(String pattern, CharSequence str)
It returns true if pattern matches str and false otherwise. This method automatically compiles pattern and then looks
for a match. If you will be using the same pattern repeatedly, then using matches( ) is less efficient than compiling the
pattern and using the pattern-matching methods defined by Matcher, as described [Link] can also perform a
pattern match by using the matches( ) method implemented by String. It is shown here:
boolean matches(String pattern)
Page : 6
Advanced Java Unit 3
If the invoking string matches the regular expression in pattern, then matches( ) returns true. Otherwise, it returns
false.
Qns 2. With syntax and example explain the following String class methods
a. getChars()
If you need to extract more than one character at a time, you can use the getChars( ) method.
It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one
past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–
1. The array that will receive the characters is specified by target. The index within target at which the substring will
be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the
number of characters in the specified substring.
The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
[Link](start, end, buf, 0);
[Link](buf);
}
}
b. replace()
The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with
another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by [Link] resulting string is
returned. For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
The second form of replace( ) replaces one character sequence with another. It has this general form:
String replace(CharSequence original, CharSequence replacement
Qns 3. With syntax and example explain the following StringBuffer class methods
a. insert()
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus
Strings, Objects, and CharSequences. Like append( ), it calls [Link]( ) to obtain the string representation of
the value it is called with. This string is then inserted into the invoking StringBuffer object. 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.
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
[Link](2, "like ");
[Link](sb);
Page : 7
Advanced Java Unit 3
}}
The output of this example is shown here:
I like Java!
b. deleteCharAt()
You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ). These methods
are shown here:
StringBuffer deleteCharAt(int loc)
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer
object.
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](0);
[Link]("After deleteCharAt: " + sb);
}
}
The following output is produced:
After deleteCharAt: his is a test.
Qns 4. With syntax and example explain the following StringBuffer class methods
a. substring()
You can obtain a portion of a StringBuffer by calling substring( ). It has the following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object.
The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work
just like those defined for String that were described earlier.
b. lastIndexOf()
The lastIndexOf() method in strings is used to find the last occurrence of a character or substring within a string. It
returns the index (position) of that occurrence. If the value is not found, it returns -1
• [Link](value)
[Link](value, fromIndex)
• value → character or substring to search for
• fromIndex (optional) → position to start searching backward from
String text = "hello world hello";
int index = [Link]("hello");
[Link](index);
Page : 9
Advanced Java Unit 3
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes( ),
and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form: byte[ ]
getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a String value into an
environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file
formats use 8-bit ASCII for all text interchange.
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray(
). It returns an array of characters for the entire string. It has this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result.
Qns 8. Explain the difference between the indexOf() and lastIndexOf() methods in the String class. Give an example for
each method to illustrate their functionality.
The String class provides two methods that allow you to search a string for a specified character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.
Page : 10
Advanced Java Unit 3
These two methods are overloaded in several different ways. In all cases, the methods return the index at which the
character or substring was found, or –1 on failure.
To search for the first occurrence of a character, use
int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the substring.
You can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex
to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of Strings:
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
[Link](s);
[Link]("indexOf(t) = " +
[Link]('t'));
[Link]("lastIndexOf(t) = " +
[Link]('t'));
[Link]("indexOf(the) = " +
[Link]("the"));
[Link]("lastIndexOf(the) = " +
[Link]("the"));
[Link]("indexOf(t, 10) = " +
[Link]('t', 10));
[Link]("lastIndexOf(t, 60) = " +
[Link]('t', 60));
[Link]("indexOf(the, 10) = " +
[Link]("the", 10));
[Link]("lastIndexOf(the, 60) = " +
[Link]("the", 60));
}
}
Qns 9. Describe two common approaches for modifying Strings in Java with an example
substring( )
You can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that
begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
Page : 11
Advanced Java Unit 3
Here, startIndex specifies the beginning index, and endIndex specifies the stopping [Link] string returned
contains all the characters from the beginning index, up to, but not including, the ending index.
The following program uses substring( ) to replace all instances of one substring with another within a string:
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings
[Link](org);
i = [Link](search);
if(i != -1) {
result = [Link](0, i);
result = result + sub;
result = result + [Link](i + [Link]());
org = result;
}
} while(i != -1);
}
}
The output from this program is shown here:
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str appended to the end.
concat( ) performs the same function as +. For example, String s1 = "one";
String s2 = [Link]("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
Qns 10. Explain the use of charAt() and setCharAt() methods with suitable example.
charAt( ) and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt( ) [Link] can set the value of
a character within a StringBuffer using setCharAt( ). Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index
of the character being set, and ch specifies the new value of that character. For both methods, where must be
nonnegative and must not specify a location beyond the end of the buffer.
The following example demonstrates charAt( ) and setCharAt( ):
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
Page : 12
Advanced Java Unit 3
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " + [Link](1));
[Link](1, 'i');
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}
}
Here is the output generated by this program:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
Qns 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 their string representation.
The main purpose of [Link]() is to:
• Convert primitive data types (like int, float, boolean, etc.) into a String
• Convert objects into a string form (by calling their toString() method internally)
• Provide a safe way to handle null values (returns "null" instead of throwing an error)
[Link](str1); // "100"
[Link](str2); // "true"
}
}
replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with
another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement.
The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
The second form of replace( ) replaces one character sequence with another. It has this general form:
String replace(CharSequence original, CharSequence replacement)
Qns 13. With an example explain the four methods of StringBuffer class
length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be
found through the capacity( ) method. They have the following general forms:
int length( )
int capacity( )
Page : 13
Advanced Java Unit 3
Here is an example:
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());
}
}
Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16
additional characters is automatically added.
ensureCapacity( )
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.
setLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative. 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. The
setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.
charAt( ) and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of
a character within a StringBuffer using setCharAt( ). Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index
of the character being set, and ch specifies the new value of that character. For both methods, where must be
nonnegative and must not specify a location beyond the end of the buffer.
The following example demonstrates charAt( ) and setCharAt( ):
// Demonstrate charAt() and setCharAt().
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](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}
}
Here is the output generated by this program:
buffer before = Hello
charAt(1) before = e
Page : 14
Advanced Java Unit 3
buffer after = Hi
charAt(1) after = i
14. What is the usage of delete() and deleteCharAt() methods? Explain them using their syntax and an example
delete( ) and deleteCharAt( )
You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ). These methods
are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index
of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the
substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer
object.
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
[Link](4, 7);
[Link]("After delete: " + sb);
[Link](0);
[Link]("After deleteCharAt: " + sb);
}
}
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test
15. Explain in detail the method that is used by the RMI client to connect to remote RMI servers?
[Link]()
The [Link]() method allows an RMI client to:
• Locate a remote object registered on an RMI server
• Obtain a stub (proxy) for that remote object
• Invoke methods on the remote object as if it were local
Syntax
Remote reference = [Link]("rmi://host:port/serviceName");
Parameters
• host → Server’s IP address or hostname
• port → Registry port (default is 1099)
• serviceName → Name under which the object is registered
How It Works (Step-by-Step)
1. The RMI server:
o Creates a remote object
o Registers it with the RMI registry using a name
2. The RMI client:
o Calls [Link]() with the URL
o Contacts the RMI registry on the server
o Retrieves a stub object
3. The stub:
o Acts as a local representative of the remote object
o Handles communication over the network
Page : 15
Advanced Java Unit 3
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 and serialization are two related concepts in Java that deal with the storage and retrieval of Java
objects in a persistent form, typically to a file or over a network.
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.
Challenges of Distributed Systems
While distributed systems offer many advantages, they also present some challenges that must be addressed. These
challenges include:
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.
Qns 18. Describe the three key components that make up a Distributed Computing System.
Distributed computing is the method of making multiple computers work together to solve a common problem. It
makes a computer network appear as a powerful single computer that provides large-scale resources to deal with
complex challenges. It is a collection of independent components located on different machines that share messages
with each other in order to achieve common goals.
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.
Page : 16
Advanced Java Unit 3
19. Explain how a Social Media platform can be considered a Distributed Computing System. Identify the key
components involved and their roles.
A social media platform (like Facebook, Instagram, or Twitter (X)) is a classic example of a distributed computing
system because it operates across many interconnected computers (servers) that work together to provide a
seamless experience to millions or billions of users.
A distributed system is one where:
• Multiple machines (nodes) collaborate
• They communicate over a network
• The system appears as a single unified service to users
Social media platforms fit this perfectly because:
• Data is stored across many servers worldwide
• Requests (likes, posts, messages) are handled by different machines
• Users interact with a single interface, unaware of the complexity behind it
Key Components & Their Roles
1. Client Devices (Users)
• Examples: smartphones, laptops
• Role:
o Send requests (post, like, comment)
o Display content received from servers
• These are the entry points into the distributed system
2. Frontend Servers (Web/App Servers)
• Handle incoming user requests
• Serve UI content (feeds, profiles, notifications)
• Communicate with backend services
3. Backend Application Servers
• Core logic of the platform:
o Feed generation
o Authentication
o Posting & commenting
• Break down tasks into smaller services (microservices architecture)
4. Databases (Distributed Storage)
• Store:
o User profiles
o Posts, likes, comments
o Messages
• Often distributed across multiple locations (data centers)
5. Content Delivery Network (CDN)
• Stores cached copies of images, videos, and static content
• Delivers content from servers closest to the user
6. Load Balancers
• Distribute incoming traffic across multiple servers
• Prevent overload and ensure availability
7. Messaging & Queue Systems
• Handle asynchronous tasks:
o Notifications
o Background processing (e.g., video processing)
• Examples: message queues, event streams
8. Microservices
• Independent services for specific tasks:
o User service
o Post service
o Notification service
Benefits:
Page : 17
Advanced Java Unit 3
• Easier scaling
• Fault isolation
• Faster development
9. Data Centers (Geographically Distributed)
• Servers located across different regions worldwide
• Provide:
o Redundancy
o Faster access for global users
10. Monitoring & Fault Tolerance Systems
• Detect failures
• Automatically recover or reroute traffic
Qns 20. Explain the concept of Remote Procedure Calls (RPC) and its working mechanism with its five key elements
Remote Procedure Call (RPC) is a technique in distributed computing that allows a program to execute a function
(procedure) on another machine as if it were a local function call. It hides the complexity of network communication,
making distributed systems easier to design and use.
Concept of RPC
In a normal program:
• A function calls another function within the same system.
In RPC:
• A function on one machine (client) calls a function on another machine (server).
• The system automatically handles communication, data transfer, and execution.
Working Mechanism of RPC
Here’s the step-by-step flow:
1. Client calls a function (like a local call)
2. Client stub packages the request (arguments) into a message
3. Request is sent over the network to the server
4. Server stub unpacks the message
5. Actual procedure is executed on the server
6. Result is packaged and sent back
7. Client receives and returns the result
Five Key Elements of RPC
1. Client
• The program that initiates the request
• Calls the remote function
2. Client Stub (Proxy)
• Acts as a local representative of the remote function
• Converts function call into a network request (marshalling)
3. Communication Module (RPC Runtime)
• Handles network communication between client and server
• Uses protocols like TCP/HTTP
4. Server Stub (Skeleton)
• Receives the request from the network
• Converts it back into a function call (unmarshalling)
Page : 18
Advanced Java Unit 3
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
1. Define the Remote Interface:
You define a Java interface that extends the [Link] interface. Each method in this interface must declare
[Link] in its throws clause to handle remote method invocation errors. 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. You can start the RMI registry from the command line using the rmiregistry tool provided
with the JDK.
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.
Qns 23. Outline the key steps involved in developing a basic Remote Method Invocation (RMI) application.
• Define the remote interface
Page : 19
Advanced Java Unit 3
A remote interface provides the description of all the methods of a particular remote object. The client
communicates with this remote interface.
To create a remote interface −
Create an interface that extends the predefined interface Remote which belongs to the package.
Declare all the business methods that can be invoked by the client in this interface.
Since there is a chance of network issues during remote calls, an exception named RemoteException may
occur throw it.
• Develop the implementation class (remote object)
Implement the interface created in the previous step.
Provide implementation to all the abstract methods of the remote interface.
• Develop the server program
An RMI server program should implement the remote interface or extend the implementation class. Here, we
should create a remote object and bind it to the RMIregistry
• Develop the client program
Create a client class from where your intended to invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the
package [Link].
• Compile the application
• Execute the application
Page : 20