Various ways to reverse a string in Java.

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-07-23 23:56:10 Viewed : 357


There are various ways to reverse a string in Java. Here are a few different methods:

  1. Using a StringBuilder:
java
import java.util.Scanner; public class ReverseString { public static String reverseWithStringBuilder(String inputString) { StringBuilder reversedString = new StringBuilder(inputString); reversedString = reversedString.reverse(); return reversedString.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string to reverse: "); String userInput = scanner.nextLine(); String reversedString = reverseWithStringBuilder(userInput); System.out.println("Reversed string: " + reversedString); } }
  1. Using a character array:
java
import java.util.Scanner; public class ReverseString { public static String reverseWithCharArray(String inputString) { char[] charArray = inputString.toCharArray(); int start = 0; int end = inputString.length() - 1; while (start < end) { char temp = charArray[start]; charArray[start] = charArray[end]; charArray[end] = temp; start++; end--; } return new String(charArray); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string to reverse: "); String userInput = scanner.nextLine(); String reversedString = reverseWithCharArray(userInput); System.out.println("Reversed string: " + reversedString); } }
  1. Using recursion:
java
import java.util.Scanner; public class ReverseString { public static String reverseWithRecursion(String inputString) { if (inputString.isEmpty()) { return inputString; } else { return reverseWithRecursion(inputString.substring(1)) + inputString.charAt(0); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string to reverse: "); String userInput = scanner.nextLine(); String reversedString = reverseWithRecursion(userInput); System.out.println("Reversed string: " + reversedString); } }

You can choose any of these methods to reverse a string in Java based on your preference and requirements. Each method has its own advantages and may be more suitable in different situations.

Search
Related Articles

Leave a Comment: