-1

I want to know what is going wrong with the below program as it is not returning reversed string.

public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev+ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
        obj.reverse("saumya");
    }
}
jps
  • 20,041
  • 15
  • 75
  • 79
  • "program as it is not returning reversed string" what makes you think so? You are not showing result of that method anywhere. Possibly related: [Differences between System.out.println() and return in Java](https://stackoverflow.com/q/25456472) – Pshemo Jan 22 '22 at 15:14
  • 1
    it probably is returning it - you are forgetting to print output to console. that is done by calling `System.out.println()` – J Asgarov Jan 22 '22 at 15:14
  • `reverse` clearly **is** returning the reversed string: `return rev;`. But you ignore the return value in `main`. Perhaps you're not sure what it means to have a method "return" a value? – passer-by Jan 22 '22 at 15:15
  • You do nothing with the reversed `String`. Also, your method could be `return new StringBuilder(str).reverse().toString();` – Elliott Frisch Jan 22 '22 at 15:24

2 Answers2

0

You forgot to print the returned string


public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev+ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
       System.out.println(obj.reverse("saumya"));
    }
}

I got this output

aymuas
Nabil
  • 1,130
  • 5
  • 11
0

There is nothing wrong with your code. Since you are not printing anything to the console, you are not getting anything on the output.You forgot to store the string that is returned by the reverse function. Just add it and it gives correct output.

public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev+ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
        String res = obj.reverse("saumya");
        System.out.println(res);
    }
}

and it gives the output

aymuas
Gurkirat Singh Guliani
  • 1,009
  • 1
  • 4
  • 19