How to reverse a string in Java

4 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "java programming";
         
        s = new StringBuffer(s).reverse().toString();
         
        System.out.println(s);
    }
}
 
 
 
/*
run:
 
gnimmargorp avaj
 
*/

 



answered Oct 26, 2016 by avibootz
reshown Apr 26, 2024 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "java programming";
         
        s = new StringBuilder(s).reverse().toString();
         
        System.out.println(s);
    }
}
 
 
 
/*
run:
 
gnimmargorp avaj
 
*/

 



answered Oct 29, 2016 by avibootz
edited Apr 26, 2024 by avibootz
0 votes
public class MyClass {
    public static String reverseString(String s) {
        return new StringBuilder(s).reverse().toString();
    }
    public static void main(String args[]) {
        String s = "java programming";
          
        s = reverseString(s);
          
        System.out.println(s);
    }
}

    
     
/*
run:
    
gnimmargorp avaj
    
*/

 



answered Apr 26, 2024 by avibootz
0 votes
public class MyClass {
    public static String reverseString(String s) {
        if (s.isEmpty()) {
		    return s;
		}
		
		return reverseString(s.substring(1)) + s.charAt(0);
    }
    public static void main(String args[]) {
        String s = "java programming";
          
        s = reverseString(s);
          
        System.out.println(s);
    }
}

    
     
/*
run:
    
gnimmargorp avaj
    
*/

 



answered Apr 26, 2024 by avibootz

Related questions

3 answers 122 views
1 answer 108 views
1 answer 81 views
1 answer 140 views
1 answer 106 views
...