In many MNC they ask how to reverse the content of String without using loop and methods of String class
Answer : We can reverse the content of String using the following algorithm
Step#1: Create object of StringBuilder class
Step#2: Store string type data inside object of StringBuilder using append() method
Step#3: Reverse the content of StringBuilder using reverse() method
Step#4: Convert the content of StringBuilder into String using toString() method and store it inside a reference-variable of String
Now, we can show the entire process using a java program
Note: Create Java project in Eclipse IDE and save this class inside ReverseTheString.java file
public class ReverseTheString
{
public static void main(String[] args)
{
// take a string
String str = "I am a string";
// Step#1
StringBuilder s = new StringBuilder();
// Step#2
s.append(str);
}
Output of code ===>>>
String after reverse is -> gnirts a ma I
Answer : We can reverse the content of String using the following algorithm
Step#1: Create object of StringBuilder class
Step#2: Store string type data inside object of StringBuilder using append() method
Step#3: Reverse the content of StringBuilder using reverse() method
Step#4: Convert the content of StringBuilder into String using toString() method and store it inside a reference-variable of String
Now, we can show the entire process using a java program
Note: Create Java project in Eclipse IDE and save this class inside ReverseTheString.java file
public class ReverseTheString
{
public static void main(String[] args)
{
// take a string
String str = "I am a string";
// Step#1
StringBuilder s = new StringBuilder();
// Step#2
s.append(str);
// Step#3
s.reverse();
// Step#4
str = s.toString();
// show the data of string
System.out.println("String after reverse is -> "+str);
}}
Output of code ===>>>
String after reverse is -> gnirts a ma I