4 Ways to Reverse String in Java

In this tutorial you will learn about different ways to reverse string in java with examples.

 

For example:

Input: Hello World

Output: dlroW olleH

How to Reverse String in Java

Ways to Reverse String in Java

Method 1:

This is the simplest method in which we iterator through given string from end character by character and append to new empty string.

 

Output

Original String: I love programming
Reversed String: gnimmargorp evol I

 

Method 2:

It is also an iterative method in which we iterate through the string from start as well as end and keep swapping the characters. Below is the program to implement this.

 

Method 3:

StringBuffer class provides a method reverse() to reverse a string. This is the fastest and most efficient way to reverse a string.

 

Method 4:

In this method we first insert the characters of string in a linked list. Now reverse the linked list using Collections.reverse() method. Finally print the characters present in linked list.

 

Please mention in the comment section if you know any other way to reverse string in java.

2 comments

  • richd

    Push each character onto a stack, then pop em back off.

    Stack reverse = new Stack();

    String testString = “I love programming in Java”;
    char[] charArray = testString.toCharArray();
    for(char c:charArray){
    reverse.push(c);
    }

    String reversed = “”;
    while(!reverse.isEmpty()){
    reversed += (reverse.pop());
    }

    System.out.println(reversed.toString());
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *