Java String Examples

Java String Reverse Example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

5 Comments

  • [code]
    /* Here is the full example of reversing a string in the form of a method. It’s as simple as this!!! */

    import java.util.Scanner;

    public class PrintBack{

    public static void main(String[] args)

    {

    DoPrint();

    }

    static void DoPrint()
    {
    Scanner boom = new Scanner(System.in);

    String name;
    int i;

    System.out.print(“Enter a sentence: “);
    name = boom.nextLine();

    i = name.length()-1;

    while (i >= 0){
    System.out.print(name.charAt(i));
    i–;
    }

    }
    }
    [/code]

    • can you please edit it, that will print the sentence reversed without ruining the letters…

      example: I am cool
      reversed: cool am i

    • I managed to do this with a String array. I was wondering how to do it without using an array and then stumbled across this algorithm. Much simpler than I’d presumed. Thanks a lot.

      I have the site bookmarked.

      • It requires -1 because all strings end with a ‘\0’ character… while doing the reverse the null is not needed.. so -1 is used else the string will end up reversed one short.

Sponsors

Facebook Fans