• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

7 Java Reverse String Programs – Including Word by Word

May 1, 2018 by javainterviewpoint 1 Comment

How to Reverse a String in Java is one of the popular interview questions, but the interviewer might add some twist to it by asking you to write the code without using the reverse() method, recursion, etc. In this article, we will learn the possible ways of reversing a string in Java. We will look into techniques of reversing a single word and group of words in a sentence [Word by Word]

Java Reverse String

Method 1: Using reverse() function — Using StringBuilder (or) StringBuffer

This is the easiest way of reversing a String, we can use reverse() method of either StringBuilder (or) StringBuffer.

Note: StringBuilder can give a better performance as it is not Synchronized. StringBuffer is Synchronized

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        //Pass input to constructor of StringBuilder
        StringBuilder inputStr = new StringBuilder(input);
        
        //Use reverse() method to reverse the String
        reverseString = inputStr.reverse().toString();
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
    • Get the input string from the user and pass it to the constructor of the StringBuilder.
    • Use the reverse() method of the StringBuilder class to get the reversed String.

Output:

Java Reverse String

Method 2: Reverse String Using charAt()

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        //Convert input to inputArray using toCharArray()
        char[] inputArray = input.toCharArray();
        
        for(int i=inputArray.length-1;i>=0;i--)
        {
            reverseString = reverseString+inputArray[i];
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
  • Get the input string from the user and convert the input string into a character array inputArray using toCharArray() method
  • Iterate the inputArray from end to start, each time append it to the reverseString.

Output:

Enter string to reversed
JavaInterviewPoint
Original String : JavaInterviewPoint
Reversed String : tnioPweivretnIavaJ 

Method 3: using Recursion

package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reversedString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        reversedString = reverseString(input);
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reversedString);
    }
    public static String reverseString(String input)
    {
        if(input.isEmpty())
            return input;
        
        //Call reverseString() function recursively
        return reverseString(input.substring(1)) + input.charAt(0);
    }
}
  • Get the input string from the user and pass the input string to the reverseString() method.
  • In the reverseString() method, we will be recursively subString() the first character of the input String and append it to the end using charAt() method.

Method 4: Using Stack

import java.util.Scanner;
import java.util.Stack;

public class StringReverse
{
    public static void main(String[] args)
    {
        StringBuilder reverseString = new StringBuilder();

        System.out.println("Enter string to reversed");

        // Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        // Create a stack of characters
        Stack<Character> stack = new Stack<Character>();

        // Push each character into the stack
        for (int i = 0; i < input.length(); i++)
        {
            stack.push(input.charAt(i));
        }

        // pop each characters from the stack until it is empty
        while (!stack.empty())
        {
            reverseString.append(stack.pop());
        }

        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
  • Get the input string from the user.
  • Create a Stack of Character and push each character of the input string into the stack.
  • Pop each character from the stack until it is empty and append it to the reverseString.

Method 5: Using Collections reverse() method

  • Get the input string from the user
  • Create a List of Character (characterList) and push each character of the input string into the characterList.
  • Use Collections.reverse() method to reverse the elements of the characterList
  • Iterate the characterList from end to start, each time append it to the reverseString
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        StringBuilder reverseString = new StringBuilder();

        System.out.println("Enter string to reversed");

        // Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        //Create a list of characters
        List<Character> characterList =  new ArrayList<Character>();
        
        //Push each characters into the characterList
        for(Character c : input.toCharArray())
        {
           characterList.add(c);
        }
        
        //Reverse the List using Collections.reverse()
        Collections.reverse(characterList);
        
        //Convert ArrayList to String
        for(Character c : characterList)
        {
            reverseString.append(c);
        }

        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

Java Reverse String Word by Word

All the above methods will work good for a single word, lets now learn how to reverse a string in Java word by word,
We will reverse each word in a sentence.

Method 1: Using StringBuffer

  • Get the input string from the user
  • Using split() method split the sentence into words and save them to a String array (words)
  • Iterate through the String array and use reverse() method of the StringBuffer class to reverse the String and keep appending the reversedString.
package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
	public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        // Split sentence into seperate words
        String[] words = input.split(" "); 
        
        // Iterate the String array
        for(String word : words)
        {
        	// Append each reversed Words
        	reverseString = reverseString + new StringBuilder(word).reverse().toString()+" ";
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

Output:

Enter string to reversed
Hello World
Original String : Hello World
Reversed String : olleH dlroW

Method 2: Using charAt()

  • Get the input string from the user
  • Using split() method split the sentence into words and save them to a String array (words)
  • Iterate through the String array and convert each word into a character array using toCharArray() method
  • Iterate through the character array in the decreasing order and each time append the character to the reverseString
package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
	public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        // Split sentence into seperate words
        String[] words = input.split(" "); 
        
        // Iterate the String array
        for(String word : words)
        {
            //Convert input to inputArray using toCharArray()
            char[] inputArray = word.toCharArray();
            
            for(int i=inputArray.length-1; i>=0; i--)
            {
                reverseString = reverseString+inputArray[i];
            }
            reverseString = reverseString + " ";
            
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

Filed Under: Core Java, Java Tagged With: charAt, Recursion, reverse, reverse a String, Reverse a String in Java, stack, swap, Word by Word

Comments

  1. Yogesh Mangde says

    March 19, 2019 at 12:42 pm

    I like it! great explanation and different solutions for the same problem.

    Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·