How to reverse a string in Java

How to reverse a string in Java?

Way 1:Reverse a string in Java : Using Builtin Function

In Java, you can reverse a string by using the StringBuilder class which has a built-in reverse() method. Here’s an example code:

String str = "Hello World";
StringBuilder sb = new StringBuilder(str);
String reversedStr = sb.reverse().toString();
System.out.println(reversedStr); // Output: "dlroW olleH"

In the above code, we first create a string “Hello World” and then create a StringBuilder object and pass the string to its constructor. Then we call the reverse() method of the StringBuilder object to reverse the string. Finally, we convert the StringBuilder object back to a string using the toString() method and store it in the reversedStr variable. The output will be “dlroW olleH”.

Way 2: Reverse a string in Java : Without BuiltIn Function

you can reverse a string without using any built-in function in Java.

public static String reverseString(String str) {
char[] charArray = str.toCharArray();
int i = 0;
int j = str.length() – 1;
while (i < j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
i++;
j–;
}
return new String(charArray);
}

// Example usage:
String str = “Hello World”;
String reversedStr = reverseString(str);
System.out.println(reversedStr); // Output: “dlroW olleH”

In the above code, we first convert the input string str to a character array using the toCharArray() method. Then we use two pointers i and j to swap the characters from both ends until the midpoint of the string is reached. Finally, we create a new string from the reversed character array using the String constructor and return it. The output will be “dlroW olleH”.

Way 3 :Reverse a string in Java : Using Recursion

Here’s another example code that uses recursion to reverse the string:

public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
String str = "Hello World";
String reversedStr = reverseString(str);
System.out.println(reversedStr); // Output: "dlroW olleH"

How to check whether a string is a palindrome in Java?

How to check if a vowel is present in a string.

Ram Chadar

Hello! I'm Ram Chadar, a passionate software developer and freelancer based in Pune. Welcome to my blog, where I share my experiences, insights, and knowledge in the world of software development, different technologies, freelancing, and more.

View all posts by Ram Chadar →

One thought on “How to reverse a string in Java?

  1. I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

Leave a Reply

Your email address will not be published. Required fields are marked *