Let’s learn reverse a string in java without using reverse function.
Reverse a string in java without using reverse function
Here are ways to reverse a string without using reverse function. One using for loop, while loop, and recursion.
Here’s the program to reverse a string using for loop without using reverse method. for loop loops until condition for(int a = strInput.length(); a > 0; –a) is false.
import java.util.Scanner; public class ReverseWithoutFunction { public static void main(String[] args) { String strInput; Scanner sc = new Scanner(System.in); System.out.print("Please enter a string: "); strInput = sc.nextLine(); System.out.print("After reversing string is: "); for(int a = strInput.length(); a > 0; --a) { System.out.print(strInput.charAt(a - 1)); } sc.close(); } }
Output:
Please enter a string: flowerbrackets
After reversing string is: stekcarbrewolf
Please enter a string: helloworld
After reversing string is: dlrowolleh
Let’s see program to reverse a string using recursion. Recursive function is one which calls itself.
import java.util.Scanner; public class ReverseStringUsingRecursion { String reverseRecursive(String str) { if(str.length() == 0) return " "; return str.charAt(str.length() - 1) + reverseRecursive(str.substring(0, str.length() - 1)); } public static void main(String[] args) { ReverseUsingRecursion obj = new ReverseUsingRecursion(); Scanner sc = new Scanner(System.in); System.out.println("Please enter a string: "); String strInput = sc.nextLine(); System.out.println("Reverse string using recursion: " + obj.reverseRecursive(strInput)); sc.close(); } }
Output:
Please enter a string: helloworld
Reverse string using recursion: dlrowolleh
Please enter a string: java
Reverse string using recursion: avaj
Now let’s learn to reverse a string in java using while loop. while loop loops until s > 0 becomes false.
import java.util.Scanner; public class ReverseWithoutFunction { public static void main(String[] args) { String strInput; Scanner sc = new Scanner(System.in); System.out.print("Please enter a string: "); strInput = sc.nextLine(); System.out.print("After reversing string is: "); int s = strInput.length(); while(s > 0) { System.out.print(strInput.charAt(s - 1)); s--; } sc.close(); } }
Output:
Please enter a string: corejava
After reversing string is: avajeroc
Also read – abstraction in java