Sunday, May 1, 2022

Question 1: How to reverse a string in java? Can you write a program without using any java inbuilt methods?

 Solution: There are many ways to do it, some of them are:

  • Using for loop
  • Using recursion
  • Using StringBuffer

Using for loop

  1. Declare empty String reverse. This will contain our final reversed string.
  2. Iterate over an array using for loop from last index to 0th index
  3. Add character to String reverse while iterating.
public class ReverseStringForMain {
    public static void main(String[] args) {
        String blogName = "techTwitter";
        String reverse = "";
        for (int i = blogName.length() - 1; i >= 0; i--) {
            reverse = reverse + blogName.charAt(i);
        System.out.println("Reverse of cloud.techtwitter is: " + reverse);

Using recursion

We can also use recursion to reverse a String in java

public class ReverseStringRecursive {
    public static void main(String[] args) {
        ReverseStringRecursive rsr = new ReverseStringRecursive();
        String blogName = "techTwitter";
        String reverse = rsr.recursiveReverse(blogName);
        System.out.println("Reverse of cloud.techtwitter is:" + reverse);
    public String recursiveReverse(String orig) {
        if (orig.length() == 1)
            return orig;
            return orig.charAt(orig.length() - 1) +
                          recursiveReverse(orig.substring(0, orig.length() - 1));


Don't miss the next article!

Be the first to be notified when a new article or Kubernetes experiment is published.    

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS