×

注意!页面内容来自https://www.geeksforgeeks.org/java/reverse-a-string-in-java/,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

<> #nprogress { pointer-events: none; } #nprogress .bar { background: #29D; position: fixed; z-index: 9999; top: 0; left: 0; width: 100%; height: 3px; } #nprogress .peg { display: block; position: absolute; right: 0px; width: 100px; height: 100%; box-shadow: 0 0 10px #29D0 0 5px #29D; opacity: 1; -webkit-transform: rotate(3deg) translate(0px-4px); -ms-transform: rotate(3deg) translate(0px-4px); transform: rotate(3deg) translate(0px-4px); } #nprogress .spinner { display: block; position: fixed; z-index: 1031; top: 15px; right: 15px; } #nprogress .spinner-icon { width: 18px; height: 18px; box-sizing: border-box; border: solid 2px transparent; border-top-color: #29D; border-left-color: #29D; border-radius: 50%; -webkit-animation: nprogresss-spinner 400ms linear infinite; animation: nprogress-spinner 400ms linear infinite; } .nprogress-custom-parent { overflow: hidden; position: relative; } .nprogress-custom-parent #nprogress .spinner, .nprogress-custom-parent #nprogress .bar { position: absolute; } @-webkit-keyframes nprogress-spinner { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes nprogress-spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
Data Structure
Java
Python
HTML
Interview Preparation
  • Interview Prep
  • Tutorials
  • Tracks

Reverse a String in Java

Last Updated : 14 Oct2025

In Javareversing a string means rearranging its characters from last to first. It’s a common programming task used in algorithmsdata processingand interviews. There are several ways to reverse a string in Javafrom using loops to built-in methods.

1. Using a For Loop

The for loop is the most basic and manual approach. It provides complete control over the reversal process without using additional classes.

Java
class GFG{
    
    public static void main(String[] args){
        
        String s = "Geeks";
        String r = "";

        for (int i = 0; i < s.length(); i++){
            
            // prepend each character
            r = s.charAt(i) + r; 
        }
        System.out.println(r);
    }
}

Output
skeeG

Explanation: Each character of the string is appended in reverse order to a new string rresulting in the reversed output.

2. Using StringBuilder.reverse()

StringBuilder provides a built-in reverse() methodmaking string reversal quick and efficient.

Java
import java.io.*;

class Main{
  
    public static void main(String[] args){
      
        String s = "Geeks";

      	// Object Initialised
        StringBuilder res = new StringBuilder();

        // Appending elements of s in res
        res.append(s);

        // reverse StringBuilder res
        res.reverse();

        // print reversed String
        System.out.println(res);
    }
}

Output
skeeG

Explanation: StringBuilder objects are mutableand their reverse() method reverses the content in-placewhich is faster than manual looping.

3. Using Character Array

We can use character array to reverse a string. Follow Steps mentioned below:

  • Firstconvert String to character array by using the built-in Java String class method toCharArray().
  • Thenscan the string from end to startand print the character one by one.
Java
import java.io.*;

class Main{
  
    public static void main(String[] args){
      
        String s = "Geeks";

        // Using toCharArray to copy elements
        char[] arr = s.toCharArray();

        for (int i = arr.length - 1; i >= 0; i--)
            System.out.print(arr[i]);
    }
}

Output
skeeG

Explanation: The string is converted into a char[] arrayand characters are printed in reverse order using a simple loop.

4. Using Collections.reverse()

The Collections.reverse() method can be used when dealing with lists. We can convert a string to a list of charactersreverse itand print it back.

Java
import java.util.*;

class Main {
  
    public static void main(String[] args){
      
        String s = "Geeks";
      
      	// Copying elements to Character Array
        char[] arr = s.toCharArray();
      
      	// Creating new ArrayList
        List<Character> l = new ArrayList<>();

      	// Adding char elements to ArrayList
        for (char c : arr)
            l.add(c);

      	// Reversing the ArrayList
        Collections.reverse(l);
      
      	// Using ListIterator
        ListIterator it = l.listIterator();
      
        while (it.hasNext())
            System.out.print(it.next());
    }
}

Output
skeeG

Explanation: Characters are stored in a list and reversed using Collections.reverse(). This approach is helpful when you’re already working with Java collections.

5. Using StringBuffer.reverse()

StringBuffer is similar to StringBuilder but thread-safe. It also provides the reverse() method.

Java
import java.io.*;

public class Main{
  
    public static void main(String[] args){
      
        String s = "Geeks";

        // Conversion from String object
      	// To StringBuffer
        StringBuffer sbf = new StringBuffer(s);
        
      	// Reverse String
        sbf.reverse();
      	
        System.out.println(sbf);
    }
}

Output
skeeG

Explanation: StringBuffer is synchronizedso it’s a good choice for multithreaded environments.

6. Using a Stack

The stack approach uses the Last-In-First-Out (LIFO) principle to reverse characters.

Java
import java.util.*;

class Main{
  
    public static void main(String[] args){
       
        String str = "Geeks";
        
        //initializing a stack of type char
        Stack<Character> s = new Stack<>();
        
        for(char c : str.toCharArray()){
            //pushing all the characters
            s.push(c);
        }
        
        String res="";
        
        while(!s.isEmpty()){
          
            //popping all the chars and appending to temp
            res+=s.pop();
        }
        
        System.out.println(res);
        
    }
}

Output
skeeG

Explanation: Each character is pushed onto the stack and then popped outreversing the order naturally.

7. Using getBytes()

This method works at the byte level and is useful for encoding or low-level string manipulation.

Java
import java.io.*;

class Main {
  
    public static void main(String[] args) {
      
        String s = "Geeks";

        // getBytes() method to convert string
        // into bytes[].
        byte[] arr = s.getBytes();

        byte[] res = new byte[arr.length];

        // Store reult in reverse order into the
        // res byte[]
        for (int i = 0; i < arr.length; i++)
            res[i] = arr[arr.length - i - 1];

        System.out.println(new String(res));
    }
}
Try it on GfG Practice
redirect icon

Output
skeeG

Explanation: The string is converted to bytesreversedand then reconstructed into a new String.

When to Use Which Method

  • For Loop: For simplicity and complete manual control over the reversal process.
  • StringBuilder/StringBuffer: Efficient and concise with built-in reverse() methods.
  • Character Array: When working with individual characters or for manual control.
  • Collections.reverse(): When already working with lists or collections.
  • Stack: When following the LIFO principle or using stacks in the algorithm.
  • getBytes(): When dealing with byte-level manipulations or encoding.


Comment