KnowledgeBoat Logo

Computer Applications

What will be the output of the following code snippet when combined with suitable declarations and run?

StringBuffer city = new StringBuffer("Madras"); 
StringBuffer string = new StringBuffer( ); 
string.append(new String(city)); 
string.insert(0, "Central "); 
String.out.println(string);

Java

Java String Handling

2 Likes

Answer

The given snippet will generate an error in the statement — String.out.println(string); as the correct statement for printing is — System.out.println(string);. After this correction is done, the output will be as follows:

Central Madras

Working

StatementRemark
StringBuffer city = new StringBuffer("Madras");It creates a StringBuffer objectcity which stores "Madras".
StringBuffer string = new StringBuffer( );It creates an empty StringBuffer object string.
string.append(new String(city));It adds the value of city i.e. "Madras" at the end of the StringBuffer object string. string = " Madras".
string.insert(0, "Central ");It modifies StringBuffer object string and adds "Central" at 0 index or beginning. Now, string = "Central Madras".
System.out.println(string);It prints "Central Madras".

Answered By

1 Like


Related Questions