Member-only story
What is the best way to reverse a string in Java?
1 min readJun 18, 2022
In this tutorial we will see which is the best approach to reverse a string in java.
package com.java.programs;
// Write a Java Program to reverse a string.
public class Reverse_A_String {
public static void main(String[] args) {
// 1st approach
Long startTime1 = System.currentTimeMillis();
String input1 = "Gain java knowledge";
String output1 = "";
for(int i = input1.length()-1; i >= 0 ;i--){
output1 = output1+input1.charAt(i);
}
System.out.println("input1 : " +input1);
System.out.println("output1 :"+ output1);
System.out.println("Time taken by Iteration :"+ (System.currentTimeMillis()-startTime1));
// 2nd approach
Long startTime2 = System.currentTimeMillis();
String input2 = "Gain java knowledge";
StringBuilder output2 = new StringBuilder(input2);
output2.reverse();
System.out.println("input2 : " +input2);
System.out.println("output2 :"+ output2);
System.out.println("Time taken by Inbuilt function :"+ (System.currentTimeMillis()-startTime2));
}
}
Here you can see the code above written for to reverse a string in java. I have defined to approaches and also calculated the time taken by both approaches.
2nd Approach is better . we can check the time comparison after running this code.
Watch Video Here :